@rawdash/connector-app-store-connect 0.24.0 → 0.25.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/README.md CHANGED
@@ -45,12 +45,12 @@ App Store Connect API uses an ES256-signed JWT minted per request from an issuer
45
45
  - `bundleId`: Bundle identifier, e.g. com.example.app.
46
46
  - `sku`: App SKU set when the app was registered.
47
47
  - `primaryLocale`: Primary App Store locale, e.g. en-US.
48
- - **`app_store_connect_app_installs`** _(metric)_ - Daily installs (units sold or downloaded) aggregated from the SALES SUMMARY report by (date, app, country code, product type). One sample per (day, app, country, productTypeIdentifier).
48
+ - **`app_store_connect_app_installs`** _(metric)_ - Daily units from the SALES SUMMARY report by (date, app, country code, product type). Counts units across ALL product types (paid and free downloads, app updates, redownloads, and in-app-purchase units; refunds appear as negative units), so this is not first-installs - filter by productTypeIdentifier for true installs. One sample per (day, app, country, productTypeIdentifier).
49
49
  - Endpoint: `GET /v1/salesReports`
50
50
  - Granularity: daily
51
51
  - Dimensions: `appId`, `countryCode`, `productTypeIdentifier`
52
52
  - Requires a vendor number. Apple delays daily reports by ~24-48 hours; the connector backs off two days from today to avoid empty / partial reports. Reports are gzipped TSV under the hood.
53
- - **`app_store_connect_app_revenue`** _(metric)_ - Daily developer proceeds aggregated from the SALES SUMMARY report by (date, app, country code, product type). Values are summed across rows that share a currency; rows are emitted per currency.
53
+ - **`app_store_connect_app_revenue`** _(metric)_ - Daily developer proceeds from the SALES SUMMARY report by (date, app, country code, product type). Each sample's value is total proceeds for the row (Apple's per-unit Developer Proceeds multiplied by Units), so multi-unit rows are fully counted and refund rows (negative units) subtract. Values stay in the row's native currency and are NOT FX-normalised; one sample per currency.
54
54
  - Endpoint: `GET /v1/salesReports`
55
55
  - Unit: native currency (see currency attribute)
56
56
  - Granularity: daily
@@ -126,7 +126,7 @@ App Store Connect enforces a 3,600 requests-per-hour quota per team. The shared
126
126
 
127
127
  ## Links
128
128
 
129
- - [Rawdash docs](https://rawdash.dev/docs/connectors/)
129
+ - [Rawdash docs](https://rawdash.dev/docs/connectors)
130
130
  - [Apple API docs](https://developer.apple.com/documentation/appstoreconnectapi)
131
131
  - [GitHub](https://github.com/rawdash/rawdash)
132
132
 
package/dist/index.d.ts CHANGED
@@ -82,7 +82,7 @@ declare const appStoreConnectResources: {
82
82
  };
83
83
  readonly app_store_connect_app_installs: {
84
84
  readonly shape: "metric";
85
- readonly description: "Daily installs (units sold or downloaded) aggregated from the SALES SUMMARY report by (date, app, country code, product type). One sample per (day, app, country, productTypeIdentifier).";
85
+ readonly description: "Daily units from the SALES SUMMARY report by (date, app, country code, product type). Counts units across ALL product types (paid and free downloads, app updates, redownloads, and in-app-purchase units; refunds appear as negative units), so this is not first-installs - filter by productTypeIdentifier for true installs. One sample per (day, app, country, productTypeIdentifier).";
86
86
  readonly endpoint: "GET /v1/salesReports";
87
87
  readonly granularity: "daily";
88
88
  readonly notes: "Requires a vendor number. Apple delays daily reports by ~24-48 hours; the connector backs off two days from today to avoid empty / partial reports. Reports are gzipped TSV under the hood.";
@@ -102,7 +102,7 @@ declare const appStoreConnectResources: {
102
102
  };
103
103
  readonly app_store_connect_app_revenue: {
104
104
  readonly shape: "metric";
105
- readonly description: "Daily developer proceeds aggregated from the SALES SUMMARY report by (date, app, country code, product type). Values are summed across rows that share a currency; rows are emitted per currency.";
105
+ readonly description: "Daily developer proceeds from the SALES SUMMARY report by (date, app, country code, product type). Each sample's value is total proceeds for the row (Apple's per-unit Developer Proceeds multiplied by Units), so multi-unit rows are fully counted and refund rows (negative units) subtract. Values stay in the row's native currency and are NOT FX-normalised; one sample per currency.";
106
106
  readonly endpoint: "GET /v1/salesReports";
107
107
  readonly unit: "native currency (see currency attribute)";
108
108
  readonly granularity: "daily";
@@ -198,7 +198,7 @@ declare class AppStoreConnectConnector extends BaseConnector<AppStoreConnectSett
198
198
  };
199
199
  readonly app_store_connect_app_installs: {
200
200
  readonly shape: "metric";
201
- readonly description: "Daily installs (units sold or downloaded) aggregated from the SALES SUMMARY report by (date, app, country code, product type). One sample per (day, app, country, productTypeIdentifier).";
201
+ readonly description: "Daily units from the SALES SUMMARY report by (date, app, country code, product type). Counts units across ALL product types (paid and free downloads, app updates, redownloads, and in-app-purchase units; refunds appear as negative units), so this is not first-installs - filter by productTypeIdentifier for true installs. One sample per (day, app, country, productTypeIdentifier).";
202
202
  readonly endpoint: "GET /v1/salesReports";
203
203
  readonly granularity: "daily";
204
204
  readonly notes: "Requires a vendor number. Apple delays daily reports by ~24-48 hours; the connector backs off two days from today to avoid empty / partial reports. Reports are gzipped TSV under the hood.";
@@ -218,7 +218,7 @@ declare class AppStoreConnectConnector extends BaseConnector<AppStoreConnectSett
218
218
  };
219
219
  readonly app_store_connect_app_revenue: {
220
220
  readonly shape: "metric";
221
- readonly description: "Daily developer proceeds aggregated from the SALES SUMMARY report by (date, app, country code, product type). Values are summed across rows that share a currency; rows are emitted per currency.";
221
+ readonly description: "Daily developer proceeds from the SALES SUMMARY report by (date, app, country code, product type). Each sample's value is total proceeds for the row (Apple's per-unit Developer Proceeds multiplied by Units), so multi-unit rows are fully counted and refund rows (negative units) subtract. Values stay in the row's native currency and are NOT FX-normalised; one sample per currency.";
222
222
  readonly endpoint: "GET /v1/salesReports";
223
223
  readonly unit: "native currency (see currency attribute)";
224
224
  readonly granularity: "daily";
package/dist/index.js CHANGED
@@ -211,7 +211,7 @@ var appStoreConnectResources = defineResources({
211
211
  },
212
212
  [APP_INSTALLS_METRIC]: {
213
213
  shape: "metric",
214
- description: "Daily installs (units sold or downloaded) aggregated from the SALES SUMMARY report by (date, app, country code, product type). One sample per (day, app, country, productTypeIdentifier).",
214
+ description: "Daily units from the SALES SUMMARY report by (date, app, country code, product type). Counts units across ALL product types (paid and free downloads, app updates, redownloads, and in-app-purchase units; refunds appear as negative units), so this is not first-installs - filter by productTypeIdentifier for true installs. One sample per (day, app, country, productTypeIdentifier).",
215
215
  endpoint: "GET /v1/salesReports",
216
216
  granularity: "daily",
217
217
  notes: "Requires a vendor number. Apple delays daily reports by ~24-48 hours; the connector backs off two days from today to avoid empty / partial reports. Reports are gzipped TSV under the hood.",
@@ -233,7 +233,7 @@ var appStoreConnectResources = defineResources({
233
233
  },
234
234
  [APP_REVENUE_METRIC]: {
235
235
  shape: "metric",
236
- description: "Daily developer proceeds aggregated from the SALES SUMMARY report by (date, app, country code, product type). Values are summed across rows that share a currency; rows are emitted per currency.",
236
+ description: "Daily developer proceeds from the SALES SUMMARY report by (date, app, country code, product type). Each sample's value is total proceeds for the row (Apple's per-unit Developer Proceeds multiplied by Units), so multi-unit rows are fully counted and refund rows (negative units) subtract. Values stay in the row's native currency and are NOT FX-normalised; one sample per currency.",
237
237
  endpoint: "GET /v1/salesReports",
238
238
  unit: "native currency (see currency attribute)",
239
239
  granularity: "daily",
@@ -533,7 +533,7 @@ var AppStoreConnectConnector = class _AppStoreConnectConnector extends BaseConne
533
533
  if (tsv === null || tsv.length === 0) {
534
534
  continue;
535
535
  }
536
- for (const sample of parseSalesReportTsv(tsv, metricName)) {
536
+ for (const sample of parseSalesReportTsv(tsv, metricName, this.logger)) {
537
537
  samples.push(sample);
538
538
  }
539
539
  }
@@ -673,7 +673,7 @@ function computeSalesReportDates(options, settings) {
673
673
  }
674
674
  return dates;
675
675
  }
676
- function parseSalesReportTsv(tsv, metricName) {
676
+ function parseSalesReportTsv(tsv, metricName, logger) {
677
677
  const lines = tsv.split(/\r?\n/u).filter((l) => l.length > 0);
678
678
  if (lines.length < 2) {
679
679
  return [];
@@ -687,7 +687,25 @@ function parseSalesReportTsv(tsv, metricName) {
687
687
  const appleIdIdx = idx("Apple Identifier");
688
688
  const currencyIdx = idx("Currency of Proceeds");
689
689
  const productTypeIdx = idx("Product Type Identifier");
690
- if (beginDateIdx === -1 || appleIdIdx === -1 || countryIdx === -1 || metricName === APP_INSTALLS_METRIC && unitsIdx === -1 || metricName === APP_REVENUE_METRIC && (proceedsIdx === -1 || currencyIdx === -1)) {
690
+ const required = [
691
+ ["Begin Date", beginDateIdx],
692
+ ["Apple Identifier", appleIdIdx],
693
+ ["Country Code", countryIdx],
694
+ ["Units", unitsIdx]
695
+ ];
696
+ if (metricName === APP_REVENUE_METRIC) {
697
+ required.push(
698
+ ["Developer Proceeds", proceedsIdx],
699
+ ["Currency of Proceeds", currencyIdx]
700
+ );
701
+ }
702
+ const missing = required.filter(([, i]) => i === -1).map(([name]) => name);
703
+ if (missing.length > 0) {
704
+ logger?.warn("sales report missing required column(s)", {
705
+ metric: metricName,
706
+ missing: missing.join(", "),
707
+ header: lines[0]
708
+ });
691
709
  return [];
692
710
  }
693
711
  const samples = [];
@@ -716,11 +734,12 @@ function parseSalesReportTsv(tsv, metricName) {
716
734
  };
717
735
  samples.push({ name: metricName, ts, value, attributes });
718
736
  } else {
719
- const raw = row[proceedsIdx]?.trim() ?? "";
720
- const value = Number.parseFloat(raw);
721
- if (!Number.isFinite(value)) {
737
+ const proceedsPerUnit = Number.parseFloat(row[proceedsIdx]?.trim() ?? "");
738
+ const units = Number.parseFloat(row[unitsIdx]?.trim() ?? "");
739
+ if (!Number.isFinite(proceedsPerUnit) || !Number.isFinite(units)) {
722
740
  continue;
723
741
  }
742
+ const value = proceedsPerUnit * units;
724
743
  const currency = row[currencyIdx]?.trim() ?? "";
725
744
  const attributes = {
726
745
  appId,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/app-store-connect.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n AuthError,\n connectorUserAgent,\n sanitizeAllowedUrl,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorCost,\n type ConnectorDoc,\n type CredentialsSchema,\n type FetchPageResult,\n type JSONValue,\n type MetricSample,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n issuerId: z.string().min(1).meta({\n label: 'Issuer ID',\n description:\n 'App Store Connect API issuer ID (UUID). Found at Users and Access -> Integrations -> App Store Connect API.',\n placeholder: '69a6de7f-...',\n }),\n keyId: z.string().min(1).meta({\n label: 'Key ID',\n description:\n 'App Store Connect API key ID (10 characters). Shown next to the key in Users and Access -> Integrations -> App Store Connect API.',\n placeholder: 'ABC1234DEF',\n }),\n privateKey: z.object({ $secret: z.string() }).meta({\n label: 'Private key (.p8)',\n description:\n 'Contents of the App Store Connect API private key file (.p8). PKCS#8 PEM, starting with -----BEGIN PRIVATE KEY-----. Apple only lets you download the key once on creation.',\n placeholder: '-----BEGIN PRIVATE KEY-----\\n...',\n secret: true,\n }),\n vendorNumber: z\n .string()\n .regex(/^\\d{8,9}$/u, 'Vendor number must be an 8-9 digit numeric string')\n .optional()\n .meta({\n label: 'Vendor number',\n description:\n 'Apple vendor number (8-9 digit numeric). Required to sync sales reports (app_installs and app_revenue). Found in App Store Connect -> Payments and Financial Reports -> top-left dropdown.',\n placeholder: '85912345',\n }),\n resources: z\n .array(z.enum(['apps', 'app_installs', 'app_revenue', 'app_ratings']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which App Store Connect resources to sync. Omit to sync all resources. Sales-derived resources (app_installs, app_revenue) require vendorNumber and are silently skipped without it.',\n }),\n salesBackfillDays: z.number().int().positive().max(365).optional().meta({\n label: 'Sales backfill window (days)',\n description:\n 'How many days of daily sales reports to pull on a full sync. Defaults to 30. Apple keeps daily reports for the last 365 days.',\n placeholder: '30',\n }),\n reviewLimit: z.number().int().positive().max(2000).optional().meta({\n label: 'Review sample size',\n description:\n 'Most-recent customer reviews to fetch per app for the app_ratings metric. Defaults to 200 (one Apple page). Higher values smooth the rolling rating at the cost of more requests.',\n placeholder: '200',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'App Store Connect',\n category: 'mobile',\n brandColor: '#0D96F6',\n tagline:\n 'Sync your iOS / macOS apps, daily sales (downloads and proceeds), and customer review ratings from the App Store Connect API for mobile-team dashboards.',\n vendor: {\n name: 'Apple',\n domain: 'apple.com',\n apiDocs: 'https://developer.apple.com/documentation/appstoreconnectapi',\n website: 'https://appstoreconnect.apple.com',\n },\n auth: {\n summary:\n 'App Store Connect API uses an ES256-signed JWT minted per request from an issuer ID, key ID, and a PKCS#8 EC private key (.p8) downloaded from App Store Connect. The key only needs read access to Sales and Reports.',\n setup: [\n 'Open App Store Connect -> Users and Access -> Integrations -> App Store Connect API.',\n 'Generate a key with the \"Sales\" or \"Finance\" role (read-only is enough). Copy the key ID shown in the table; capture the issuer ID at the top of the page.',\n 'Download the .p8 file once on creation - Apple does not let you re-download it.',\n 'Store the .p8 contents as a secret (e.g. APPSTORECONNECT_P8) and reference it as `privateKey: secret(\"APPSTORECONNECT_P8\")`.',\n 'Set `vendorNumber` from App Store Connect -> Payments and Financial Reports (the top-left dropdown shows the 8-9 digit number). Only required for app_installs and app_revenue.',\n ],\n },\n rateLimit:\n 'App Store Connect enforces a 3,600 requests-per-hour quota per team. The shared HTTP client backs off on 429 using Retry-After. Sales report endpoints are billed in the same bucket and cost one request per (day, report) pair.',\n limitations: [\n 'app_crashes (per-build crash counts) is not implemented. Apple only exposes crash analytics via the asynchronous Analytics Reports flow (create report request -> poll for completion -> download gzipped CSV) which spans multiple syncs; a follow-up will add it.',\n 'app_ratings is sampled from the most recent N customer reviews per app (default 200, capped at 2,000). It is a rolling rating, not the lifetime average shown in the App Store, because Apple does not expose lifetime aggregates over the REST API.',\n 'Sales reports are pulled in DAILY frequency only; weekly, monthly, and yearly summaries are not synced.',\n 'Subscription, in-app-purchase, and refund line items in the SALES summary report are aggregated into `units` and `proceeds` rather than broken out by product type. Filter by `productTypeIdentifier` on the metric sample attributes if you need to separate them.',\n ],\n});\n\nexport const cost: ConnectorCost = {\n recommendedInterval: '6 hours',\n minInterval: '1 hour',\n warning:\n 'Daily sales reports are only finalized 24-48 hours after the day closes; syncing more often than the recommended interval will not bring fresher revenue data.',\n};\n\nexport interface AppStoreConnectSettings {\n resources?: readonly AppStoreConnectResource[];\n vendorNumber?: string;\n salesBackfillDays?: number;\n reviewLimit?: number;\n}\n\nconst appStoreConnectCredentials = {\n issuerId: {\n description: 'App Store Connect API issuer ID',\n auth: 'required' as const,\n },\n keyId: {\n description: 'App Store Connect API key ID',\n auth: 'required' as const,\n },\n privateKey: {\n description: 'App Store Connect API private key (.p8 PEM contents)',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype AppStoreConnectCredentials = typeof appStoreConnectCredentials;\n\nconst PHASE_ORDER = [\n 'apps',\n 'app_installs',\n 'app_revenue',\n 'app_ratings',\n] as const;\n\ntype AppStoreConnectPhase = (typeof PHASE_ORDER)[number];\n\nexport type AppStoreConnectResource = AppStoreConnectPhase;\n\nconst isAppStoreConnectCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\ntype AppStoreConnectCursor = ChunkedSyncCursor<AppStoreConnectPhase, string>;\n\nconst API_HOST = 'api.appstoreconnect.apple.com';\nconst API_BASE = `https://${API_HOST}`;\nconst APPS_PATH = '/v1/apps';\nconst SALES_REPORTS_PATH = '/v1/salesReports';\nconst PER_PAGE = 200;\nconst DEFAULT_SALES_BACKFILL_DAYS = 30;\nconst DEFAULT_REVIEW_LIMIT = 200;\nconst SALES_REPORT_DELAY_HOURS = 48;\nconst MS_PER_DAY = 86_400_000;\nconst MS_PER_HOUR = 3_600_000;\n\nconst APP_ENTITY = 'app_store_connect_app';\nconst APP_INSTALLS_METRIC = 'app_store_connect_app_installs';\nconst APP_REVENUE_METRIC = 'app_store_connect_app_revenue';\nconst APP_RATINGS_METRIC = 'app_store_connect_app_ratings';\n\ninterface AppRecord {\n id: string;\n attributes?: {\n name?: string | null;\n bundleId?: string | null;\n sku?: string | null;\n primaryLocale?: string | null;\n } | null;\n}\n\ninterface ReviewRecord {\n id: string;\n attributes?: {\n rating?: number | null;\n territory?: string | null;\n title?: string | null;\n reviewerNickname?: string | null;\n createdDate?: string | null;\n } | null;\n}\n\nconst appAttributesSchema = z.object({\n name: z.string().nullish(),\n bundleId: z.string().nullish(),\n sku: z.string().nullish(),\n primaryLocale: z.string().nullish(),\n});\n\nconst appSchema = z.object({\n id: z.string().min(1),\n type: z.string().optional(),\n attributes: appAttributesSchema.nullish(),\n});\n\nconst appsResponseSchema = z.object({\n data: z.array(appSchema),\n links: z\n .object({\n next: z.string().nullish(),\n })\n .nullish(),\n});\n\nconst reviewAttributesSchema = z.object({\n rating: z.number().int().min(1).max(5).nullish(),\n territory: z.string().nullish(),\n title: z.string().nullish(),\n reviewerNickname: z.string().nullish(),\n createdDate: z.string().nullish(),\n});\n\nconst reviewSchema = z.object({\n id: z.string().min(1),\n type: z.string().optional(),\n attributes: reviewAttributesSchema.nullish(),\n});\n\nconst reviewsResponseSchema = z.object({\n data: z.array(reviewSchema),\n links: z\n .object({\n next: z.string().nullish(),\n })\n .nullish(),\n});\n\nexport const appStoreConnectResources = defineResources({\n [APP_ENTITY]: {\n shape: 'entity',\n description:\n 'Apps registered in the team, with bundle id, SKU, and primary locale. Synced from /v1/apps.',\n endpoint: 'GET /v1/apps',\n filterable: [],\n fields: [\n { name: 'name', description: 'App display name.' },\n {\n name: 'bundleId',\n description: 'Bundle identifier, e.g. com.example.app.',\n },\n {\n name: 'sku',\n description: 'App SKU set when the app was registered.',\n },\n {\n name: 'primaryLocale',\n description: 'Primary App Store locale, e.g. en-US.',\n },\n ],\n responses: { apps: appsResponseSchema },\n },\n [APP_INSTALLS_METRIC]: {\n shape: 'metric',\n description:\n 'Daily installs (units sold or downloaded) aggregated from the SALES SUMMARY report by (date, app, country code, product type). One sample per (day, app, country, productTypeIdentifier).',\n endpoint: 'GET /v1/salesReports',\n granularity: 'daily',\n notes:\n 'Requires a vendor number. Apple delays daily reports by ~24-48 hours; the connector backs off two days from today to avoid empty / partial reports. Reports are gzipped TSV under the hood.',\n dimensions: [\n {\n name: 'appId',\n description:\n 'App Store Connect app id (Apple Identifier from the report).',\n },\n {\n name: 'countryCode',\n description: 'Two-letter ISO country code from the sale.',\n },\n {\n name: 'productTypeIdentifier',\n description:\n 'Apple product type, e.g. 1 (paid app), 1F (universal app), IA1 (in-app purchase).',\n },\n ],\n responses: { sales_installs_report: z.string() },\n },\n [APP_REVENUE_METRIC]: {\n shape: 'metric',\n description:\n 'Daily developer proceeds aggregated from the SALES SUMMARY report by (date, app, country code, product type). Values are summed across rows that share a currency; rows are emitted per currency.',\n endpoint: 'GET /v1/salesReports',\n unit: 'native currency (see currency attribute)',\n granularity: 'daily',\n notes:\n 'Proceeds are NOT FX-normalised; each sample carries its native currency in the `currency` attribute. Filter or convert downstream.',\n dimensions: [\n {\n name: 'appId',\n description: 'App Store Connect app id.',\n },\n {\n name: 'countryCode',\n description: 'Two-letter ISO country code from the sale.',\n },\n {\n name: 'currency',\n description:\n 'ISO 4217 currency of the proceeds, e.g. USD, EUR, JPY (matches Apple \"Currency of Proceeds\").',\n },\n {\n name: 'productTypeIdentifier',\n description: 'Apple product type code (same as app_installs).',\n },\n ],\n responses: { sales_revenue_report: z.string() },\n },\n [APP_RATINGS_METRIC]: {\n shape: 'metric',\n description:\n 'Rolling per-review ratings sampled from the most-recent N customer reviews per app (default 200). Each sample carries one review with the rating (1-5) as the value and the territory on the attribute.',\n endpoint: 'GET /v1/apps/{id}/customerReviews',\n notes:\n 'Apple does NOT expose the lifetime average rating over the REST API. Average over a time window downstream to get a rolling rating.',\n dimensions: [\n {\n name: 'appId',\n description: 'App Store Connect app id.',\n },\n {\n name: 'territory',\n description: 'Two-letter ISO country code where the review was filed.',\n },\n ],\n responses: { customer_reviews: reviewsResponseSchema },\n },\n});\n\nexport const id = 'app-store-connect';\n\nexport class AppStoreConnectConnector extends BaseConnector<\n AppStoreConnectSettings,\n AppStoreConnectCredentials\n> {\n static readonly id = id;\n\n static readonly resources = appStoreConnectResources;\n\n static readonly schemas = schemasFromResources(appStoreConnectResources);\n\n static readonly cost = cost;\n\n static create(\n input: unknown,\n ctx?: ConnectorContext,\n ): AppStoreConnectConnector {\n const parsed = configFields.parse(input);\n return new AppStoreConnectConnector(\n {\n resources: parsed.resources,\n vendorNumber: parsed.vendorNumber,\n salesBackfillDays: parsed.salesBackfillDays,\n reviewLimit: parsed.reviewLimit,\n },\n {\n issuerId: parsed.issuerId,\n keyId: parsed.keyId,\n privateKey: parsed.privateKey,\n },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = appStoreConnectCredentials;\n\n private cachedJwt: { token: string; expiresAt: number } | null = null;\n private cachedAppIds: string[] | null = null;\n\n private async buildAuthHeader(): Promise<string> {\n const now = Math.floor(Date.now() / 1000);\n if (this.cachedJwt && this.cachedJwt.expiresAt > now + 60) {\n return `Bearer ${this.cachedJwt.token}`;\n }\n const { issuerId, keyId, privateKey } = this.creds;\n if (!issuerId || !keyId || !privateKey) {\n throw new AuthError(`${this.id}: missing App Store Connect credentials`);\n }\n const exp = now + 900;\n const jwt = await signES256Jwt({\n header: { alg: 'ES256', kid: keyId, typ: 'JWT' },\n payload: {\n iss: issuerId,\n iat: now,\n exp,\n aud: 'appstoreconnect-v1',\n },\n privateKeyPem: privateKey,\n });\n this.cachedJwt = { token: jwt, expiresAt: exp };\n return `Bearer ${jwt}`;\n }\n\n private async authHeaders(): Promise<Record<string, string>> {\n return {\n Authorization: await this.buildAuthHeader(),\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent(this.id),\n };\n }\n\n private sanitizeListUrl(\n phase: AppStoreConnectPhase,\n pageUrl: string | null,\n ): string | null {\n const allowedPath = phase === 'apps' ? APPS_PATH : null;\n if (allowedPath === null) {\n return null;\n }\n return sanitizeAllowedUrl({\n url: pageUrl,\n host: API_HOST,\n pathname: allowedPath,\n });\n }\n\n private resolveCursor(cursor: unknown): AppStoreConnectCursor | undefined {\n if (!isAppStoreConnectCursor(cursor)) {\n return undefined;\n }\n if (cursor.phase === 'apps') {\n return {\n phase: cursor.phase,\n page: this.sanitizeListUrl(cursor.phase, cursor.page),\n };\n }\n return { phase: cursor.phase, page: null };\n }\n\n private async listApps(signal?: AbortSignal): Promise<string[]> {\n if (this.cachedAppIds !== null) {\n return this.cachedAppIds;\n }\n const ids: string[] = [];\n let url: string | null = `${API_BASE}${APPS_PATH}?limit=${PER_PAGE}`;\n while (url !== null) {\n if (signal?.aborted) {\n return ids;\n }\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof appsResponseSchema>>(url, {\n resource: 'apps',\n headers,\n signal,\n });\n for (const app of res.body.data ?? []) {\n ids.push(app.id);\n }\n const next = res.body.links?.next ?? null;\n url = this.sanitizeListUrl('apps', next);\n }\n this.cachedAppIds = ids;\n return ids;\n }\n\n private async fetchAppsPage(\n page: string | null,\n signal?: AbortSignal,\n ): Promise<FetchPageResult<string>> {\n const url = page ?? `${API_BASE}${APPS_PATH}?limit=${PER_PAGE}`;\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof appsResponseSchema>>(url, {\n resource: 'apps',\n headers,\n signal,\n });\n const items = res.body.data ?? [];\n if (this.cachedAppIds === null) {\n this.cachedAppIds = [];\n }\n for (const app of items) {\n if (!this.cachedAppIds.includes(app.id)) {\n this.cachedAppIds.push(app.id);\n }\n }\n const rawNext = res.body.links?.next ?? null;\n const next = this.sanitizeListUrl('apps', rawNext);\n return { items, next };\n }\n\n private buildSalesReportUrl(reportDate: string): string {\n const vendor = this.settings.vendorNumber;\n if (!vendor) {\n throw new Error(\n 'vendorNumber is required for app_installs / app_revenue resources',\n );\n }\n const params = new URLSearchParams();\n params.set('filter[frequency]', 'DAILY');\n params.set('filter[reportType]', 'SALES');\n params.set('filter[reportSubType]', 'SUMMARY');\n params.set('filter[vendorNumber]', vendor);\n params.set('filter[reportDate]', reportDate);\n return `${API_BASE}${SALES_REPORTS_PATH}?${params.toString()}`;\n }\n\n private async fetchSalesReportTsv(\n reportDate: string,\n signal?: AbortSignal,\n ): Promise<string | null> {\n const url = this.buildSalesReportUrl(reportDate);\n\n const res = await this.withRetry<Response>(\n async (sig) => {\n const headers = await this.authHeaders();\n headers['Accept'] = 'application/a-gzip';\n const response = await globalThis.fetch(url, {\n method: 'GET',\n headers,\n signal: sig,\n });\n if (response.status === 429) {\n const retryAfter = Number(response.headers.get('retry-after') ?? '');\n if (Number.isFinite(retryAfter) && retryAfter > 0) {\n await this.sleep(retryAfter * 1000, sig);\n }\n return { status: 'retry' };\n }\n return { status: 'done', value: response };\n },\n { signal },\n );\n if (res === null) {\n throw new Error(\n `App Store Connect sales report ${reportDate} failed: exhausted retries on HTTP 429`,\n );\n }\n if (res.status === 404) {\n return null;\n }\n if (!res.ok) {\n throw new Error(\n `App Store Connect sales report ${reportDate} failed: HTTP ${res.status}`,\n );\n }\n const body = res.body;\n if (!body) {\n return null;\n }\n const decompressed = body.pipeThrough(new DecompressionStream('gzip'));\n return await new Response(decompressed).text();\n }\n\n private async fetchReviewsForApp(\n appId: string,\n limit: number,\n signal?: AbortSignal,\n ): Promise<ReviewRecord[]> {\n const reviews: ReviewRecord[] = [];\n const reviewsBase = `/v1/apps/${encodeURIComponent(appId)}/customerReviews`;\n let url: string | null =\n `${API_BASE}${reviewsBase}?limit=${PER_PAGE}&sort=-createdDate`;\n while (url !== null && reviews.length < limit) {\n if (signal?.aborted) {\n return reviews;\n }\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof reviewsResponseSchema>>(url, {\n resource: 'customer_reviews',\n headers,\n signal,\n });\n for (const review of res.body.data ?? []) {\n reviews.push(review);\n if (reviews.length >= limit) {\n break;\n }\n }\n const rawNext = res.body.links?.next ?? null;\n url = sanitizeAllowedUrl({\n url: rawNext,\n host: API_HOST,\n pathname: reviewsBase,\n });\n }\n return reviews;\n }\n\n private async writeApps(\n storage: StorageHandle,\n items: AppRecord[],\n ): Promise<void> {\n const nowMs = Date.now();\n for (const app of items) {\n const attrs = app.attributes ?? {};\n await storage.entity({\n type: APP_ENTITY,\n id: app.id,\n attributes: {\n name: attrs.name ?? null,\n bundleId: attrs.bundleId ?? null,\n sku: attrs.sku ?? null,\n primaryLocale: attrs.primaryLocale ?? null,\n },\n updated_at: nowMs,\n });\n }\n }\n\n private async syncSalesReports(\n storage: StorageHandle,\n metricName: typeof APP_INSTALLS_METRIC | typeof APP_REVENUE_METRIC,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<void> {\n if (!this.settings.vendorNumber) {\n this.logger.info('skipping sales report (no vendorNumber configured)', {\n resource: metricName,\n });\n await storage.metrics([], { names: [metricName] });\n return;\n }\n const dates = computeSalesReportDates(options, this.settings);\n const samples: MetricSample[] = [];\n for (const reportDate of dates) {\n if (signal?.aborted) {\n return;\n }\n let tsv: string | null;\n try {\n tsv = await this.fetchSalesReportTsv(reportDate, signal);\n } catch (err) {\n this.logger.warn('sales report fetch failed', {\n reportDate,\n resource: metricName,\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n if (tsv === null || tsv.length === 0) {\n continue;\n }\n for (const sample of parseSalesReportTsv(tsv, metricName)) {\n samples.push(sample);\n }\n }\n await storage.metrics(samples, { names: [metricName] });\n }\n\n private async syncAppRatings(\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<void> {\n const appIds = await this.listApps(signal);\n const limit = this.settings.reviewLimit ?? DEFAULT_REVIEW_LIMIT;\n const samples: MetricSample[] = [];\n for (const appId of appIds) {\n if (signal?.aborted) {\n return;\n }\n const reviews = await this.fetchReviewsForApp(appId, limit, signal);\n for (const review of reviews) {\n const attrs = review.attributes ?? {};\n if (typeof attrs.rating !== 'number') {\n continue;\n }\n const ts = isoToMs(attrs.createdDate);\n if (ts === null) {\n continue;\n }\n const attributes: Record<string, JSONValue> = {\n appId,\n reviewId: review.id,\n territory: attrs.territory ?? null,\n };\n samples.push({\n name: APP_RATINGS_METRIC,\n ts,\n value: attrs.rating,\n attributes,\n });\n }\n }\n await storage.metrics(samples, { names: [APP_RATINGS_METRIC] });\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n this.cachedAppIds = null;\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = selectActivePhases<\n AppStoreConnectResource,\n AppStoreConnectPhase\n >((r) => r, PHASE_ORDER, this.settings.resources);\n\n return paginateChunked<AppStoreConnectPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n if (phase === 'apps') {\n return this.fetchAppsPage(page, sig);\n }\n return { items: [{ phase }], next: null };\n },\n writeBatch: async (phase, items, page) => {\n if (phase === 'apps') {\n if (page === null && isFull) {\n await storage.entities([], { types: [APP_ENTITY] });\n }\n await this.writeApps(storage, items as AppRecord[]);\n return;\n }\n if (phase === 'app_installs') {\n await this.syncSalesReports(\n storage,\n APP_INSTALLS_METRIC,\n options,\n signal,\n );\n return;\n }\n if (phase === 'app_revenue') {\n await this.syncSalesReports(\n storage,\n APP_REVENUE_METRIC,\n options,\n signal,\n );\n return;\n }\n if (phase === 'app_ratings') {\n await this.syncAppRatings(storage, signal);\n return;\n }\n },\n });\n }\n}\n\nfunction isoToMs(value: string | null | undefined): number | null {\n if (!value) {\n return null;\n }\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\nfunction pad2(n: number): string {\n return n < 10 ? `0${n}` : String(n);\n}\n\nfunction toIsoDate(d: Date): string {\n return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(\n d.getUTCDate(),\n )}`;\n}\n\nfunction parseSalesDate(value: string): number | null {\n const m = /^(\\d{2})\\/(\\d{2})\\/(\\d{4})$/u.exec(value);\n if (m) {\n const month = Number(m[1]!);\n const day = Number(m[2]!);\n const year = Number(m[3]!);\n const ms = Date.UTC(year, month - 1, day);\n return Number.isFinite(ms) ? ms : null;\n }\n const direct = Date.parse(`${value}T00:00:00Z`);\n return Number.isFinite(direct) ? direct : null;\n}\n\nexport function computeSalesReportDates(\n options: SyncOptions,\n settings: AppStoreConnectSettings,\n): string[] {\n const now = Date.now();\n const endMs = now - SALES_REPORT_DELAY_HOURS * MS_PER_HOUR;\n let startMs: number;\n if (options.since) {\n const sinceMs = Date.parse(options.since);\n startMs = Number.isFinite(sinceMs) ? sinceMs : endMs - MS_PER_DAY;\n } else if (options.mode === 'latest') {\n startMs = endMs - 2 * MS_PER_DAY;\n } else {\n const days = settings.salesBackfillDays ?? DEFAULT_SALES_BACKFILL_DAYS;\n startMs = endMs - days * MS_PER_DAY;\n }\n if (startMs > endMs) {\n return [];\n }\n const dates: string[] = [];\n const start = new Date(Math.floor(startMs / MS_PER_DAY) * MS_PER_DAY);\n const end = new Date(Math.floor(endMs / MS_PER_DAY) * MS_PER_DAY);\n for (\n let d = new Date(start.getTime());\n d.getTime() <= end.getTime();\n d.setUTCDate(d.getUTCDate() + 1)\n ) {\n dates.push(toIsoDate(d));\n }\n return dates;\n}\n\nexport function parseSalesReportTsv(\n tsv: string,\n metricName: typeof APP_INSTALLS_METRIC | typeof APP_REVENUE_METRIC,\n): MetricSample[] {\n const lines = tsv.split(/\\r?\\n/u).filter((l) => l.length > 0);\n if (lines.length < 2) {\n return [];\n }\n const header = lines[0]!.split('\\t').map((h) => h.trim());\n const idx = (name: string): number => header.indexOf(name);\n\n const beginDateIdx = idx('Begin Date');\n const unitsIdx = idx('Units');\n const proceedsIdx = idx('Developer Proceeds');\n const countryIdx = idx('Country Code');\n const appleIdIdx = idx('Apple Identifier');\n const currencyIdx = idx('Currency of Proceeds');\n const productTypeIdx = idx('Product Type Identifier');\n\n if (\n beginDateIdx === -1 ||\n appleIdIdx === -1 ||\n countryIdx === -1 ||\n (metricName === APP_INSTALLS_METRIC && unitsIdx === -1) ||\n (metricName === APP_REVENUE_METRIC &&\n (proceedsIdx === -1 || currencyIdx === -1))\n ) {\n return [];\n }\n\n const samples: MetricSample[] = [];\n for (let i = 1; i < lines.length; i++) {\n const row = lines[i]!.split('\\t');\n const ts = parseSalesDate(row[beginDateIdx]?.trim() ?? '');\n if (ts === null) {\n continue;\n }\n const appId = row[appleIdIdx]?.trim() ?? '';\n if (appId === '') {\n continue;\n }\n const countryCode = row[countryIdx]?.trim() ?? '';\n const productType =\n productTypeIdx === -1 ? '' : (row[productTypeIdx]?.trim() ?? '');\n\n if (metricName === APP_INSTALLS_METRIC) {\n const raw = row[unitsIdx]?.trim() ?? '';\n const value = Number.parseFloat(raw);\n if (!Number.isFinite(value)) {\n continue;\n }\n const attributes: Record<string, JSONValue> = {\n appId,\n countryCode,\n productTypeIdentifier: productType,\n };\n samples.push({ name: metricName, ts, value, attributes });\n } else {\n const raw = row[proceedsIdx]?.trim() ?? '';\n const value = Number.parseFloat(raw);\n if (!Number.isFinite(value)) {\n continue;\n }\n const currency = row[currencyIdx]?.trim() ?? '';\n const attributes: Record<string, JSONValue> = {\n appId,\n countryCode,\n currency,\n productTypeIdentifier: productType,\n };\n samples.push({ name: metricName, ts, value, attributes });\n }\n }\n return samples;\n}\n\ninterface JwtHeader {\n alg: 'ES256';\n kid: string;\n typ: 'JWT';\n}\n\ninterface JwtPayload {\n iss: string;\n iat: number;\n exp: number;\n aud: string;\n}\n\nexport async function signES256Jwt({\n header,\n payload,\n privateKeyPem,\n}: {\n header: JwtHeader;\n payload: JwtPayload;\n privateKeyPem: string;\n}): Promise<string> {\n const encoder = new TextEncoder();\n const headerB64 = base64urlEncode(encoder.encode(JSON.stringify(header)));\n const payloadB64 = base64urlEncode(encoder.encode(JSON.stringify(payload)));\n const signingInput = `${headerB64}.${payloadB64}`;\n const key = await importEcPrivateKey(privateKeyPem);\n const signature = await globalThis.crypto.subtle.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n key,\n encoder.encode(signingInput),\n );\n return `${signingInput}.${base64urlEncode(new Uint8Array(signature))}`;\n}\n\nasync function importEcPrivateKey(pem: string): Promise<CryptoKey> {\n const trimmed = pem.trim();\n const body = trimmed\n .replace(/-----BEGIN PRIVATE KEY-----/u, '')\n .replace(/-----END PRIVATE KEY-----/u, '')\n .replace(/\\s+/gu, '');\n if (body.length === 0) {\n throw new AuthError(\n 'app-store-connect: privateKey is empty or not a PEM-encoded PKCS#8 key',\n );\n }\n const der = base64ToBytes(body);\n return globalThis.crypto.subtle.importKey(\n 'pkcs8',\n der,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n}\n\nfunction base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {\n return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nfunction base64urlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!);\n }\n return btoa(binary)\n .replace(/\\+/gu, '-')\n .replace(/\\//gu, '_')\n .replace(/=+$/u, '');\n}\n","import { AppStoreConnectConnector } from './app-store-connect';\n\nexport {\n AppStoreConnectConnector,\n appStoreConnectResources as resources,\n configFields,\n cost,\n doc,\n id,\n} from './app-store-connect';\nexport type {\n AppStoreConnectResource,\n AppStoreConnectSettings,\n} from './app-store-connect';\nexport default AppStoreConnectConnector;\n"],"mappings":";AASO,IAAe,kBAAf,cAAuC,MAAM;EAEzC;EAET,YAAY,SAAiB,UAAyB;AACpD,UAAM,OAAO;AACb,SAAK,OAAO,WAAW;AACvB,SAAK,WAAW;EAClB;AACF;AAgBO,IAAM,YAAN,cAAwB,gBAAgB;EACpC,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;AACb,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,cAAU,OAAO,aAAa,MAAM,CAAC,CAAE;AAAA,EACzC;AACA,SAAO,KAAK,MAAM,EACf,QAAQ,QAAQ,GAAG,EACnB,QAAQ,QAAQ,GAAG,EACnB,QAAQ,QAAQ,EAAE;AACvB;;;ACl7BA,IAAO,gBAAQ;","names":[]}
1
+ {"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/app-store-connect.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n AuthError,\n connectorUserAgent,\n sanitizeAllowedUrl,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorCost,\n type ConnectorDoc,\n type ConnectorLogger,\n type CredentialsSchema,\n type FetchPageResult,\n type JSONValue,\n type MetricSample,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n issuerId: z.string().min(1).meta({\n label: 'Issuer ID',\n description:\n 'App Store Connect API issuer ID (UUID). Found at Users and Access -> Integrations -> App Store Connect API.',\n placeholder: '69a6de7f-...',\n }),\n keyId: z.string().min(1).meta({\n label: 'Key ID',\n description:\n 'App Store Connect API key ID (10 characters). Shown next to the key in Users and Access -> Integrations -> App Store Connect API.',\n placeholder: 'ABC1234DEF',\n }),\n privateKey: z.object({ $secret: z.string() }).meta({\n label: 'Private key (.p8)',\n description:\n 'Contents of the App Store Connect API private key file (.p8). PKCS#8 PEM, starting with -----BEGIN PRIVATE KEY-----. Apple only lets you download the key once on creation.',\n placeholder: '-----BEGIN PRIVATE KEY-----\\n...',\n secret: true,\n }),\n vendorNumber: z\n .string()\n .regex(/^\\d{8,9}$/u, 'Vendor number must be an 8-9 digit numeric string')\n .optional()\n .meta({\n label: 'Vendor number',\n description:\n 'Apple vendor number (8-9 digit numeric). Required to sync sales reports (app_installs and app_revenue). Found in App Store Connect -> Payments and Financial Reports -> top-left dropdown.',\n placeholder: '85912345',\n }),\n resources: z\n .array(z.enum(['apps', 'app_installs', 'app_revenue', 'app_ratings']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which App Store Connect resources to sync. Omit to sync all resources. Sales-derived resources (app_installs, app_revenue) require vendorNumber and are silently skipped without it.',\n }),\n salesBackfillDays: z.number().int().positive().max(365).optional().meta({\n label: 'Sales backfill window (days)',\n description:\n 'How many days of daily sales reports to pull on a full sync. Defaults to 30. Apple keeps daily reports for the last 365 days.',\n placeholder: '30',\n }),\n reviewLimit: z.number().int().positive().max(2000).optional().meta({\n label: 'Review sample size',\n description:\n 'Most-recent customer reviews to fetch per app for the app_ratings metric. Defaults to 200 (one Apple page). Higher values smooth the rolling rating at the cost of more requests.',\n placeholder: '200',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'App Store Connect',\n category: 'mobile',\n brandColor: '#0D96F6',\n tagline:\n 'Sync your iOS / macOS apps, daily sales (downloads and proceeds), and customer review ratings from the App Store Connect API for mobile-team dashboards.',\n vendor: {\n name: 'Apple',\n domain: 'apple.com',\n apiDocs: 'https://developer.apple.com/documentation/appstoreconnectapi',\n website: 'https://appstoreconnect.apple.com',\n },\n auth: {\n summary:\n 'App Store Connect API uses an ES256-signed JWT minted per request from an issuer ID, key ID, and a PKCS#8 EC private key (.p8) downloaded from App Store Connect. The key only needs read access to Sales and Reports.',\n setup: [\n 'Open App Store Connect -> Users and Access -> Integrations -> App Store Connect API.',\n 'Generate a key with the \"Sales\" or \"Finance\" role (read-only is enough). Copy the key ID shown in the table; capture the issuer ID at the top of the page.',\n 'Download the .p8 file once on creation - Apple does not let you re-download it.',\n 'Store the .p8 contents as a secret (e.g. APPSTORECONNECT_P8) and reference it as `privateKey: secret(\"APPSTORECONNECT_P8\")`.',\n 'Set `vendorNumber` from App Store Connect -> Payments and Financial Reports (the top-left dropdown shows the 8-9 digit number). Only required for app_installs and app_revenue.',\n ],\n },\n rateLimit:\n 'App Store Connect enforces a 3,600 requests-per-hour quota per team. The shared HTTP client backs off on 429 using Retry-After. Sales report endpoints are billed in the same bucket and cost one request per (day, report) pair.',\n limitations: [\n 'app_crashes (per-build crash counts) is not implemented. Apple only exposes crash analytics via the asynchronous Analytics Reports flow (create report request -> poll for completion -> download gzipped CSV) which spans multiple syncs; a follow-up will add it.',\n 'app_ratings is sampled from the most recent N customer reviews per app (default 200, capped at 2,000). It is a rolling rating, not the lifetime average shown in the App Store, because Apple does not expose lifetime aggregates over the REST API.',\n 'Sales reports are pulled in DAILY frequency only; weekly, monthly, and yearly summaries are not synced.',\n 'Subscription, in-app-purchase, and refund line items in the SALES summary report are aggregated into `units` and `proceeds` rather than broken out by product type. Filter by `productTypeIdentifier` on the metric sample attributes if you need to separate them.',\n ],\n});\n\nexport const cost: ConnectorCost = {\n recommendedInterval: '6 hours',\n minInterval: '1 hour',\n warning:\n 'Daily sales reports are only finalized 24-48 hours after the day closes; syncing more often than the recommended interval will not bring fresher revenue data.',\n};\n\nexport interface AppStoreConnectSettings {\n resources?: readonly AppStoreConnectResource[];\n vendorNumber?: string;\n salesBackfillDays?: number;\n reviewLimit?: number;\n}\n\nconst appStoreConnectCredentials = {\n issuerId: {\n description: 'App Store Connect API issuer ID',\n auth: 'required' as const,\n },\n keyId: {\n description: 'App Store Connect API key ID',\n auth: 'required' as const,\n },\n privateKey: {\n description: 'App Store Connect API private key (.p8 PEM contents)',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype AppStoreConnectCredentials = typeof appStoreConnectCredentials;\n\nconst PHASE_ORDER = [\n 'apps',\n 'app_installs',\n 'app_revenue',\n 'app_ratings',\n] as const;\n\ntype AppStoreConnectPhase = (typeof PHASE_ORDER)[number];\n\nexport type AppStoreConnectResource = AppStoreConnectPhase;\n\nconst isAppStoreConnectCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\ntype AppStoreConnectCursor = ChunkedSyncCursor<AppStoreConnectPhase, string>;\n\nconst API_HOST = 'api.appstoreconnect.apple.com';\nconst API_BASE = `https://${API_HOST}`;\nconst APPS_PATH = '/v1/apps';\nconst SALES_REPORTS_PATH = '/v1/salesReports';\nconst PER_PAGE = 200;\nconst DEFAULT_SALES_BACKFILL_DAYS = 30;\nconst DEFAULT_REVIEW_LIMIT = 200;\nconst SALES_REPORT_DELAY_HOURS = 48;\nconst MS_PER_DAY = 86_400_000;\nconst MS_PER_HOUR = 3_600_000;\n\nconst APP_ENTITY = 'app_store_connect_app';\nconst APP_INSTALLS_METRIC = 'app_store_connect_app_installs';\nconst APP_REVENUE_METRIC = 'app_store_connect_app_revenue';\nconst APP_RATINGS_METRIC = 'app_store_connect_app_ratings';\n\ninterface AppRecord {\n id: string;\n attributes?: {\n name?: string | null;\n bundleId?: string | null;\n sku?: string | null;\n primaryLocale?: string | null;\n } | null;\n}\n\ninterface ReviewRecord {\n id: string;\n attributes?: {\n rating?: number | null;\n territory?: string | null;\n title?: string | null;\n reviewerNickname?: string | null;\n createdDate?: string | null;\n } | null;\n}\n\nconst appAttributesSchema = z.object({\n name: z.string().nullish(),\n bundleId: z.string().nullish(),\n sku: z.string().nullish(),\n primaryLocale: z.string().nullish(),\n});\n\nconst appSchema = z.object({\n id: z.string().min(1),\n type: z.string().optional(),\n attributes: appAttributesSchema.nullish(),\n});\n\nconst appsResponseSchema = z.object({\n data: z.array(appSchema),\n links: z\n .object({\n next: z.string().nullish(),\n })\n .nullish(),\n});\n\nconst reviewAttributesSchema = z.object({\n rating: z.number().int().min(1).max(5).nullish(),\n territory: z.string().nullish(),\n title: z.string().nullish(),\n reviewerNickname: z.string().nullish(),\n createdDate: z.string().nullish(),\n});\n\nconst reviewSchema = z.object({\n id: z.string().min(1),\n type: z.string().optional(),\n attributes: reviewAttributesSchema.nullish(),\n});\n\nconst reviewsResponseSchema = z.object({\n data: z.array(reviewSchema),\n links: z\n .object({\n next: z.string().nullish(),\n })\n .nullish(),\n});\n\nexport const appStoreConnectResources = defineResources({\n [APP_ENTITY]: {\n shape: 'entity',\n description:\n 'Apps registered in the team, with bundle id, SKU, and primary locale. Synced from /v1/apps.',\n endpoint: 'GET /v1/apps',\n filterable: [],\n fields: [\n { name: 'name', description: 'App display name.' },\n {\n name: 'bundleId',\n description: 'Bundle identifier, e.g. com.example.app.',\n },\n {\n name: 'sku',\n description: 'App SKU set when the app was registered.',\n },\n {\n name: 'primaryLocale',\n description: 'Primary App Store locale, e.g. en-US.',\n },\n ],\n responses: { apps: appsResponseSchema },\n },\n [APP_INSTALLS_METRIC]: {\n shape: 'metric',\n description:\n 'Daily units from the SALES SUMMARY report by (date, app, country code, product type). Counts units across ALL product types (paid and free downloads, app updates, redownloads, and in-app-purchase units; refunds appear as negative units), so this is not first-installs - filter by productTypeIdentifier for true installs. One sample per (day, app, country, productTypeIdentifier).',\n endpoint: 'GET /v1/salesReports',\n granularity: 'daily',\n notes:\n 'Requires a vendor number. Apple delays daily reports by ~24-48 hours; the connector backs off two days from today to avoid empty / partial reports. Reports are gzipped TSV under the hood.',\n dimensions: [\n {\n name: 'appId',\n description:\n 'App Store Connect app id (Apple Identifier from the report).',\n },\n {\n name: 'countryCode',\n description: 'Two-letter ISO country code from the sale.',\n },\n {\n name: 'productTypeIdentifier',\n description:\n 'Apple product type, e.g. 1 (paid app), 1F (universal app), IA1 (in-app purchase).',\n },\n ],\n responses: { sales_installs_report: z.string() },\n },\n [APP_REVENUE_METRIC]: {\n shape: 'metric',\n description:\n \"Daily developer proceeds from the SALES SUMMARY report by (date, app, country code, product type). Each sample's value is total proceeds for the row (Apple's per-unit Developer Proceeds multiplied by Units), so multi-unit rows are fully counted and refund rows (negative units) subtract. Values stay in the row's native currency and are NOT FX-normalised; one sample per currency.\",\n endpoint: 'GET /v1/salesReports',\n unit: 'native currency (see currency attribute)',\n granularity: 'daily',\n notes:\n 'Proceeds are NOT FX-normalised; each sample carries its native currency in the `currency` attribute. Filter or convert downstream.',\n dimensions: [\n {\n name: 'appId',\n description: 'App Store Connect app id.',\n },\n {\n name: 'countryCode',\n description: 'Two-letter ISO country code from the sale.',\n },\n {\n name: 'currency',\n description:\n 'ISO 4217 currency of the proceeds, e.g. USD, EUR, JPY (matches Apple \"Currency of Proceeds\").',\n },\n {\n name: 'productTypeIdentifier',\n description: 'Apple product type code (same as app_installs).',\n },\n ],\n responses: { sales_revenue_report: z.string() },\n },\n [APP_RATINGS_METRIC]: {\n shape: 'metric',\n description:\n 'Rolling per-review ratings sampled from the most-recent N customer reviews per app (default 200). Each sample carries one review with the rating (1-5) as the value and the territory on the attribute.',\n endpoint: 'GET /v1/apps/{id}/customerReviews',\n notes:\n 'Apple does NOT expose the lifetime average rating over the REST API. Average over a time window downstream to get a rolling rating.',\n dimensions: [\n {\n name: 'appId',\n description: 'App Store Connect app id.',\n },\n {\n name: 'territory',\n description: 'Two-letter ISO country code where the review was filed.',\n },\n ],\n responses: { customer_reviews: reviewsResponseSchema },\n },\n});\n\nexport const id = 'app-store-connect';\n\nexport class AppStoreConnectConnector extends BaseConnector<\n AppStoreConnectSettings,\n AppStoreConnectCredentials\n> {\n static readonly id = id;\n\n static readonly resources = appStoreConnectResources;\n\n static readonly schemas = schemasFromResources(appStoreConnectResources);\n\n static readonly cost = cost;\n\n static create(\n input: unknown,\n ctx?: ConnectorContext,\n ): AppStoreConnectConnector {\n const parsed = configFields.parse(input);\n return new AppStoreConnectConnector(\n {\n resources: parsed.resources,\n vendorNumber: parsed.vendorNumber,\n salesBackfillDays: parsed.salesBackfillDays,\n reviewLimit: parsed.reviewLimit,\n },\n {\n issuerId: parsed.issuerId,\n keyId: parsed.keyId,\n privateKey: parsed.privateKey,\n },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = appStoreConnectCredentials;\n\n private cachedJwt: { token: string; expiresAt: number } | null = null;\n private cachedAppIds: string[] | null = null;\n\n private async buildAuthHeader(): Promise<string> {\n const now = Math.floor(Date.now() / 1000);\n if (this.cachedJwt && this.cachedJwt.expiresAt > now + 60) {\n return `Bearer ${this.cachedJwt.token}`;\n }\n const { issuerId, keyId, privateKey } = this.creds;\n if (!issuerId || !keyId || !privateKey) {\n throw new AuthError(`${this.id}: missing App Store Connect credentials`);\n }\n const exp = now + 900;\n const jwt = await signES256Jwt({\n header: { alg: 'ES256', kid: keyId, typ: 'JWT' },\n payload: {\n iss: issuerId,\n iat: now,\n exp,\n aud: 'appstoreconnect-v1',\n },\n privateKeyPem: privateKey,\n });\n this.cachedJwt = { token: jwt, expiresAt: exp };\n return `Bearer ${jwt}`;\n }\n\n private async authHeaders(): Promise<Record<string, string>> {\n return {\n Authorization: await this.buildAuthHeader(),\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent(this.id),\n };\n }\n\n private sanitizeListUrl(\n phase: AppStoreConnectPhase,\n pageUrl: string | null,\n ): string | null {\n const allowedPath = phase === 'apps' ? APPS_PATH : null;\n if (allowedPath === null) {\n return null;\n }\n return sanitizeAllowedUrl({\n url: pageUrl,\n host: API_HOST,\n pathname: allowedPath,\n });\n }\n\n private resolveCursor(cursor: unknown): AppStoreConnectCursor | undefined {\n if (!isAppStoreConnectCursor(cursor)) {\n return undefined;\n }\n if (cursor.phase === 'apps') {\n return {\n phase: cursor.phase,\n page: this.sanitizeListUrl(cursor.phase, cursor.page),\n };\n }\n return { phase: cursor.phase, page: null };\n }\n\n private async listApps(signal?: AbortSignal): Promise<string[]> {\n if (this.cachedAppIds !== null) {\n return this.cachedAppIds;\n }\n const ids: string[] = [];\n let url: string | null = `${API_BASE}${APPS_PATH}?limit=${PER_PAGE}`;\n while (url !== null) {\n if (signal?.aborted) {\n return ids;\n }\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof appsResponseSchema>>(url, {\n resource: 'apps',\n headers,\n signal,\n });\n for (const app of res.body.data ?? []) {\n ids.push(app.id);\n }\n const next = res.body.links?.next ?? null;\n url = this.sanitizeListUrl('apps', next);\n }\n this.cachedAppIds = ids;\n return ids;\n }\n\n private async fetchAppsPage(\n page: string | null,\n signal?: AbortSignal,\n ): Promise<FetchPageResult<string>> {\n const url = page ?? `${API_BASE}${APPS_PATH}?limit=${PER_PAGE}`;\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof appsResponseSchema>>(url, {\n resource: 'apps',\n headers,\n signal,\n });\n const items = res.body.data ?? [];\n if (this.cachedAppIds === null) {\n this.cachedAppIds = [];\n }\n for (const app of items) {\n if (!this.cachedAppIds.includes(app.id)) {\n this.cachedAppIds.push(app.id);\n }\n }\n const rawNext = res.body.links?.next ?? null;\n const next = this.sanitizeListUrl('apps', rawNext);\n return { items, next };\n }\n\n private buildSalesReportUrl(reportDate: string): string {\n const vendor = this.settings.vendorNumber;\n if (!vendor) {\n throw new Error(\n 'vendorNumber is required for app_installs / app_revenue resources',\n );\n }\n const params = new URLSearchParams();\n params.set('filter[frequency]', 'DAILY');\n params.set('filter[reportType]', 'SALES');\n params.set('filter[reportSubType]', 'SUMMARY');\n params.set('filter[vendorNumber]', vendor);\n params.set('filter[reportDate]', reportDate);\n return `${API_BASE}${SALES_REPORTS_PATH}?${params.toString()}`;\n }\n\n private async fetchSalesReportTsv(\n reportDate: string,\n signal?: AbortSignal,\n ): Promise<string | null> {\n const url = this.buildSalesReportUrl(reportDate);\n\n const res = await this.withRetry<Response>(\n async (sig) => {\n const headers = await this.authHeaders();\n headers['Accept'] = 'application/a-gzip';\n const response = await globalThis.fetch(url, {\n method: 'GET',\n headers,\n signal: sig,\n });\n if (response.status === 429) {\n const retryAfter = Number(response.headers.get('retry-after') ?? '');\n if (Number.isFinite(retryAfter) && retryAfter > 0) {\n await this.sleep(retryAfter * 1000, sig);\n }\n return { status: 'retry' };\n }\n return { status: 'done', value: response };\n },\n { signal },\n );\n if (res === null) {\n throw new Error(\n `App Store Connect sales report ${reportDate} failed: exhausted retries on HTTP 429`,\n );\n }\n if (res.status === 404) {\n return null;\n }\n if (!res.ok) {\n throw new Error(\n `App Store Connect sales report ${reportDate} failed: HTTP ${res.status}`,\n );\n }\n const body = res.body;\n if (!body) {\n return null;\n }\n const decompressed = body.pipeThrough(new DecompressionStream('gzip'));\n return await new Response(decompressed).text();\n }\n\n private async fetchReviewsForApp(\n appId: string,\n limit: number,\n signal?: AbortSignal,\n ): Promise<ReviewRecord[]> {\n const reviews: ReviewRecord[] = [];\n const reviewsBase = `/v1/apps/${encodeURIComponent(appId)}/customerReviews`;\n let url: string | null =\n `${API_BASE}${reviewsBase}?limit=${PER_PAGE}&sort=-createdDate`;\n while (url !== null && reviews.length < limit) {\n if (signal?.aborted) {\n return reviews;\n }\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof reviewsResponseSchema>>(url, {\n resource: 'customer_reviews',\n headers,\n signal,\n });\n for (const review of res.body.data ?? []) {\n reviews.push(review);\n if (reviews.length >= limit) {\n break;\n }\n }\n const rawNext = res.body.links?.next ?? null;\n url = sanitizeAllowedUrl({\n url: rawNext,\n host: API_HOST,\n pathname: reviewsBase,\n });\n }\n return reviews;\n }\n\n private async writeApps(\n storage: StorageHandle,\n items: AppRecord[],\n ): Promise<void> {\n const nowMs = Date.now();\n for (const app of items) {\n const attrs = app.attributes ?? {};\n await storage.entity({\n type: APP_ENTITY,\n id: app.id,\n attributes: {\n name: attrs.name ?? null,\n bundleId: attrs.bundleId ?? null,\n sku: attrs.sku ?? null,\n primaryLocale: attrs.primaryLocale ?? null,\n },\n updated_at: nowMs,\n });\n }\n }\n\n private async syncSalesReports(\n storage: StorageHandle,\n metricName: typeof APP_INSTALLS_METRIC | typeof APP_REVENUE_METRIC,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<void> {\n if (!this.settings.vendorNumber) {\n this.logger.info('skipping sales report (no vendorNumber configured)', {\n resource: metricName,\n });\n await storage.metrics([], { names: [metricName] });\n return;\n }\n const dates = computeSalesReportDates(options, this.settings);\n const samples: MetricSample[] = [];\n for (const reportDate of dates) {\n if (signal?.aborted) {\n return;\n }\n let tsv: string | null;\n try {\n tsv = await this.fetchSalesReportTsv(reportDate, signal);\n } catch (err) {\n this.logger.warn('sales report fetch failed', {\n reportDate,\n resource: metricName,\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n if (tsv === null || tsv.length === 0) {\n continue;\n }\n for (const sample of parseSalesReportTsv(tsv, metricName, this.logger)) {\n samples.push(sample);\n }\n }\n await storage.metrics(samples, { names: [metricName] });\n }\n\n private async syncAppRatings(\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<void> {\n const appIds = await this.listApps(signal);\n const limit = this.settings.reviewLimit ?? DEFAULT_REVIEW_LIMIT;\n const samples: MetricSample[] = [];\n for (const appId of appIds) {\n if (signal?.aborted) {\n return;\n }\n const reviews = await this.fetchReviewsForApp(appId, limit, signal);\n for (const review of reviews) {\n const attrs = review.attributes ?? {};\n if (typeof attrs.rating !== 'number') {\n continue;\n }\n const ts = isoToMs(attrs.createdDate);\n if (ts === null) {\n continue;\n }\n const attributes: Record<string, JSONValue> = {\n appId,\n reviewId: review.id,\n territory: attrs.territory ?? null,\n };\n samples.push({\n name: APP_RATINGS_METRIC,\n ts,\n value: attrs.rating,\n attributes,\n });\n }\n }\n await storage.metrics(samples, { names: [APP_RATINGS_METRIC] });\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n this.cachedAppIds = null;\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = selectActivePhases<\n AppStoreConnectResource,\n AppStoreConnectPhase\n >((r) => r, PHASE_ORDER, this.settings.resources);\n\n return paginateChunked<AppStoreConnectPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n if (phase === 'apps') {\n return this.fetchAppsPage(page, sig);\n }\n return { items: [{ phase }], next: null };\n },\n writeBatch: async (phase, items, page) => {\n if (phase === 'apps') {\n if (page === null && isFull) {\n await storage.entities([], { types: [APP_ENTITY] });\n }\n await this.writeApps(storage, items as AppRecord[]);\n return;\n }\n if (phase === 'app_installs') {\n await this.syncSalesReports(\n storage,\n APP_INSTALLS_METRIC,\n options,\n signal,\n );\n return;\n }\n if (phase === 'app_revenue') {\n await this.syncSalesReports(\n storage,\n APP_REVENUE_METRIC,\n options,\n signal,\n );\n return;\n }\n if (phase === 'app_ratings') {\n await this.syncAppRatings(storage, signal);\n return;\n }\n },\n });\n }\n}\n\nfunction isoToMs(value: string | null | undefined): number | null {\n if (!value) {\n return null;\n }\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\nfunction pad2(n: number): string {\n return n < 10 ? `0${n}` : String(n);\n}\n\nfunction toIsoDate(d: Date): string {\n return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(\n d.getUTCDate(),\n )}`;\n}\n\nfunction parseSalesDate(value: string): number | null {\n const m = /^(\\d{2})\\/(\\d{2})\\/(\\d{4})$/u.exec(value);\n if (m) {\n const month = Number(m[1]!);\n const day = Number(m[2]!);\n const year = Number(m[3]!);\n const ms = Date.UTC(year, month - 1, day);\n return Number.isFinite(ms) ? ms : null;\n }\n const direct = Date.parse(`${value}T00:00:00Z`);\n return Number.isFinite(direct) ? direct : null;\n}\n\nexport function computeSalesReportDates(\n options: SyncOptions,\n settings: AppStoreConnectSettings,\n): string[] {\n const now = Date.now();\n const endMs = now - SALES_REPORT_DELAY_HOURS * MS_PER_HOUR;\n let startMs: number;\n if (options.since) {\n const sinceMs = Date.parse(options.since);\n startMs = Number.isFinite(sinceMs) ? sinceMs : endMs - MS_PER_DAY;\n } else if (options.mode === 'latest') {\n startMs = endMs - 2 * MS_PER_DAY;\n } else {\n const days = settings.salesBackfillDays ?? DEFAULT_SALES_BACKFILL_DAYS;\n startMs = endMs - days * MS_PER_DAY;\n }\n if (startMs > endMs) {\n return [];\n }\n const dates: string[] = [];\n const start = new Date(Math.floor(startMs / MS_PER_DAY) * MS_PER_DAY);\n const end = new Date(Math.floor(endMs / MS_PER_DAY) * MS_PER_DAY);\n for (\n let d = new Date(start.getTime());\n d.getTime() <= end.getTime();\n d.setUTCDate(d.getUTCDate() + 1)\n ) {\n dates.push(toIsoDate(d));\n }\n return dates;\n}\n\nexport function parseSalesReportTsv(\n tsv: string,\n metricName: typeof APP_INSTALLS_METRIC | typeof APP_REVENUE_METRIC,\n logger?: ConnectorLogger,\n): MetricSample[] {\n const lines = tsv.split(/\\r?\\n/u).filter((l) => l.length > 0);\n if (lines.length < 2) {\n return [];\n }\n const header = lines[0]!.split('\\t').map((h) => h.trim());\n const idx = (name: string): number => header.indexOf(name);\n\n const beginDateIdx = idx('Begin Date');\n const unitsIdx = idx('Units');\n const proceedsIdx = idx('Developer Proceeds');\n const countryIdx = idx('Country Code');\n const appleIdIdx = idx('Apple Identifier');\n const currencyIdx = idx('Currency of Proceeds');\n const productTypeIdx = idx('Product Type Identifier');\n\n const required: Array<[string, number]> = [\n ['Begin Date', beginDateIdx],\n ['Apple Identifier', appleIdIdx],\n ['Country Code', countryIdx],\n ['Units', unitsIdx],\n ];\n if (metricName === APP_REVENUE_METRIC) {\n required.push(\n ['Developer Proceeds', proceedsIdx],\n ['Currency of Proceeds', currencyIdx],\n );\n }\n const missing = required.filter(([, i]) => i === -1).map(([name]) => name);\n if (missing.length > 0) {\n logger?.warn('sales report missing required column(s)', {\n metric: metricName,\n missing: missing.join(', '),\n header: lines[0],\n });\n return [];\n }\n\n const samples: MetricSample[] = [];\n for (let i = 1; i < lines.length; i++) {\n const row = lines[i]!.split('\\t');\n const ts = parseSalesDate(row[beginDateIdx]?.trim() ?? '');\n if (ts === null) {\n continue;\n }\n const appId = row[appleIdIdx]?.trim() ?? '';\n if (appId === '') {\n continue;\n }\n const countryCode = row[countryIdx]?.trim() ?? '';\n const productType =\n productTypeIdx === -1 ? '' : (row[productTypeIdx]?.trim() ?? '');\n\n if (metricName === APP_INSTALLS_METRIC) {\n const raw = row[unitsIdx]?.trim() ?? '';\n const value = Number.parseFloat(raw);\n if (!Number.isFinite(value)) {\n continue;\n }\n const attributes: Record<string, JSONValue> = {\n appId,\n countryCode,\n productTypeIdentifier: productType,\n };\n samples.push({ name: metricName, ts, value, attributes });\n } else {\n const proceedsPerUnit = Number.parseFloat(row[proceedsIdx]?.trim() ?? '');\n const units = Number.parseFloat(row[unitsIdx]?.trim() ?? '');\n if (!Number.isFinite(proceedsPerUnit) || !Number.isFinite(units)) {\n continue;\n }\n const value = proceedsPerUnit * units;\n const currency = row[currencyIdx]?.trim() ?? '';\n const attributes: Record<string, JSONValue> = {\n appId,\n countryCode,\n currency,\n productTypeIdentifier: productType,\n };\n samples.push({ name: metricName, ts, value, attributes });\n }\n }\n return samples;\n}\n\ninterface JwtHeader {\n alg: 'ES256';\n kid: string;\n typ: 'JWT';\n}\n\ninterface JwtPayload {\n iss: string;\n iat: number;\n exp: number;\n aud: string;\n}\n\nexport async function signES256Jwt({\n header,\n payload,\n privateKeyPem,\n}: {\n header: JwtHeader;\n payload: JwtPayload;\n privateKeyPem: string;\n}): Promise<string> {\n const encoder = new TextEncoder();\n const headerB64 = base64urlEncode(encoder.encode(JSON.stringify(header)));\n const payloadB64 = base64urlEncode(encoder.encode(JSON.stringify(payload)));\n const signingInput = `${headerB64}.${payloadB64}`;\n const key = await importEcPrivateKey(privateKeyPem);\n const signature = await globalThis.crypto.subtle.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n key,\n encoder.encode(signingInput),\n );\n return `${signingInput}.${base64urlEncode(new Uint8Array(signature))}`;\n}\n\nasync function importEcPrivateKey(pem: string): Promise<CryptoKey> {\n const trimmed = pem.trim();\n const body = trimmed\n .replace(/-----BEGIN PRIVATE KEY-----/u, '')\n .replace(/-----END PRIVATE KEY-----/u, '')\n .replace(/\\s+/gu, '');\n if (body.length === 0) {\n throw new AuthError(\n 'app-store-connect: privateKey is empty or not a PEM-encoded PKCS#8 key',\n );\n }\n const der = base64ToBytes(body);\n return globalThis.crypto.subtle.importKey(\n 'pkcs8',\n der,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n}\n\nfunction base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {\n return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nfunction base64urlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!);\n }\n return btoa(binary)\n .replace(/\\+/gu, '-')\n .replace(/\\//gu, '_')\n .replace(/=+$/u, '');\n}\n","import { AppStoreConnectConnector } from './app-store-connect';\n\nexport {\n AppStoreConnectConnector,\n appStoreConnectResources as resources,\n configFields,\n cost,\n doc,\n id,\n} from './app-store-connect';\nexport type {\n AppStoreConnectResource,\n AppStoreConnectSettings,\n} from './app-store-connect';\nexport default AppStoreConnectConnector;\n"],"mappings":";AASO,IAAe,kBAAf,cAAuC,MAAM;EAEzC;EAET,YAAY,SAAiB,UAAyB;AACpD,UAAM,OAAO;AACb,SAAK,OAAO,WAAW;AACvB,SAAK,WAAW;EAClB;AACF;AAgBO,IAAM,YAAN,cAAwB,gBAAgB;EACpC,OAAO;AAClB;AEpCO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AICO,SAAS,mBACd,SACe;AACf,QAAM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AAW,GAAG;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,QAAM,MAAM,cAAc,IAAI;AAC9B,SAAO,WAAW,OAAO,OAAO;AAAA,IAC9B;AAAA,IACA;AAAA,IACA,EAAE,MAAM,SAAS,YAAY,QAAQ;AAAA,IACrC;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AACF;AAEA,SAAS,cAAc,KAAsC;AAC3D,SAAO,WAAW,KAAK,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AAC1D;AAEA,SAAS,gBAAgB,OAA2B;AAClD,MAAI,SAAS;AACb,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,cAAU,OAAO,aAAa,MAAM,CAAC,CAAE;AAAA,EACzC;AACA,SAAO,KAAK,MAAM,EACf,QAAQ,QAAQ,GAAG,EACnB,QAAQ,QAAQ,GAAG,EACnB,QAAQ,QAAQ,EAAE;AACvB;;;ACh8BA,IAAO,gBAAQ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rawdash/connector-app-store-connect",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "Rawdash connector for App Store Connect — syncs apps, sales (units and proceeds), and customer review ratings from the App Store Connect API into the six-shape storage model",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "zod": "^4.4.3",
27
- "@rawdash/core": "0.24.0"
27
+ "@rawdash/core": "0.25.0"
28
28
  },
29
29
  "devDependencies": {
30
30
  "fast-check": "^4.8.0",