@rawdash/connector-app-store-connect 0.21.1
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 +135 -0
- package/dist/index.d.ts +345 -0
- package/dist/index.js +790 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
// ../../connector-shared/dist/index.js
|
|
2
|
+
var HttpClientError = class extends Error {
|
|
3
|
+
response;
|
|
4
|
+
constructor(message, response) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = new.target.name;
|
|
7
|
+
this.response = response;
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var AuthError = class extends HttpClientError {
|
|
11
|
+
kind = "auth";
|
|
12
|
+
};
|
|
13
|
+
var HTTP_CLIENT_VERSION = "0.0.0";
|
|
14
|
+
var DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
|
|
15
|
+
function connectorUserAgent(connectorId) {
|
|
16
|
+
return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
|
|
17
|
+
}
|
|
18
|
+
function sanitizeAllowedUrl(options) {
|
|
19
|
+
const { url, host, pathname, protocol = "https:" } = options;
|
|
20
|
+
if (url === null) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
try {
|
|
24
|
+
const u = new URL(url);
|
|
25
|
+
if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
return u.toString();
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// src/app-store-connect.ts
|
|
35
|
+
import {
|
|
36
|
+
BaseConnector,
|
|
37
|
+
defineConfigFields,
|
|
38
|
+
defineConnectorDoc,
|
|
39
|
+
defineResources,
|
|
40
|
+
makeChunkedCursorGuard,
|
|
41
|
+
paginateChunked,
|
|
42
|
+
schemasFromResources,
|
|
43
|
+
selectActivePhases
|
|
44
|
+
} from "@rawdash/core";
|
|
45
|
+
import { z } from "zod";
|
|
46
|
+
var configFields = defineConfigFields(
|
|
47
|
+
z.object({
|
|
48
|
+
issuerId: z.string().min(1).meta({
|
|
49
|
+
label: "Issuer ID",
|
|
50
|
+
description: "App Store Connect API issuer ID (UUID). Found at Users and Access -> Integrations -> App Store Connect API.",
|
|
51
|
+
placeholder: "69a6de7f-..."
|
|
52
|
+
}),
|
|
53
|
+
keyId: z.string().min(1).meta({
|
|
54
|
+
label: "Key ID",
|
|
55
|
+
description: "App Store Connect API key ID (10 characters). Shown next to the key in Users and Access -> Integrations -> App Store Connect API.",
|
|
56
|
+
placeholder: "ABC1234DEF"
|
|
57
|
+
}),
|
|
58
|
+
privateKey: z.object({ $secret: z.string() }).meta({
|
|
59
|
+
label: "Private key (.p8)",
|
|
60
|
+
description: "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.",
|
|
61
|
+
placeholder: "-----BEGIN PRIVATE KEY-----\n...",
|
|
62
|
+
secret: true
|
|
63
|
+
}),
|
|
64
|
+
vendorNumber: z.string().regex(/^\d{8,9}$/u, "Vendor number must be an 8-9 digit numeric string").optional().meta({
|
|
65
|
+
label: "Vendor number",
|
|
66
|
+
description: "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.",
|
|
67
|
+
placeholder: "85912345"
|
|
68
|
+
}),
|
|
69
|
+
resources: z.array(z.enum(["apps", "app_installs", "app_revenue", "app_ratings"])).nonempty().optional().meta({
|
|
70
|
+
label: "Resources",
|
|
71
|
+
description: "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."
|
|
72
|
+
}),
|
|
73
|
+
salesBackfillDays: z.number().int().positive().max(365).optional().meta({
|
|
74
|
+
label: "Sales backfill window (days)",
|
|
75
|
+
description: "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.",
|
|
76
|
+
placeholder: "30"
|
|
77
|
+
}),
|
|
78
|
+
reviewLimit: z.number().int().positive().max(2e3).optional().meta({
|
|
79
|
+
label: "Review sample size",
|
|
80
|
+
description: "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.",
|
|
81
|
+
placeholder: "200"
|
|
82
|
+
})
|
|
83
|
+
})
|
|
84
|
+
);
|
|
85
|
+
var doc = defineConnectorDoc({
|
|
86
|
+
displayName: "App Store Connect",
|
|
87
|
+
category: "mobile",
|
|
88
|
+
brandColor: "#0D96F6",
|
|
89
|
+
tagline: "Sync your iOS / macOS apps, daily sales (downloads and proceeds), and customer review ratings from the App Store Connect API for mobile-team dashboards.",
|
|
90
|
+
vendor: {
|
|
91
|
+
name: "Apple",
|
|
92
|
+
domain: "apple.com",
|
|
93
|
+
apiDocs: "https://developer.apple.com/documentation/appstoreconnectapi",
|
|
94
|
+
website: "https://appstoreconnect.apple.com"
|
|
95
|
+
},
|
|
96
|
+
auth: {
|
|
97
|
+
summary: "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.",
|
|
98
|
+
setup: [
|
|
99
|
+
"Open App Store Connect -> Users and Access -> Integrations -> App Store Connect API.",
|
|
100
|
+
'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.',
|
|
101
|
+
"Download the .p8 file once on creation - Apple does not let you re-download it.",
|
|
102
|
+
'Store the .p8 contents as a secret (e.g. APPSTORECONNECT_P8) and reference it as `privateKey: secret("APPSTORECONNECT_P8")`.',
|
|
103
|
+
"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."
|
|
104
|
+
]
|
|
105
|
+
},
|
|
106
|
+
rateLimit: "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.",
|
|
107
|
+
limitations: [
|
|
108
|
+
"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.",
|
|
109
|
+
"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.",
|
|
110
|
+
"Sales reports are pulled in DAILY frequency only; weekly, monthly, and yearly summaries are not synced.",
|
|
111
|
+
"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."
|
|
112
|
+
]
|
|
113
|
+
});
|
|
114
|
+
var cost = {
|
|
115
|
+
recommendedInterval: "6 hours",
|
|
116
|
+
minInterval: "1 hour",
|
|
117
|
+
warning: "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."
|
|
118
|
+
};
|
|
119
|
+
var appStoreConnectCredentials = {
|
|
120
|
+
issuerId: {
|
|
121
|
+
description: "App Store Connect API issuer ID",
|
|
122
|
+
auth: "required"
|
|
123
|
+
},
|
|
124
|
+
keyId: {
|
|
125
|
+
description: "App Store Connect API key ID",
|
|
126
|
+
auth: "required"
|
|
127
|
+
},
|
|
128
|
+
privateKey: {
|
|
129
|
+
description: "App Store Connect API private key (.p8 PEM contents)",
|
|
130
|
+
auth: "required"
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
var PHASE_ORDER = [
|
|
134
|
+
"apps",
|
|
135
|
+
"app_installs",
|
|
136
|
+
"app_revenue",
|
|
137
|
+
"app_ratings"
|
|
138
|
+
];
|
|
139
|
+
var isAppStoreConnectCursor = makeChunkedCursorGuard(PHASE_ORDER);
|
|
140
|
+
var API_HOST = "api.appstoreconnect.apple.com";
|
|
141
|
+
var API_BASE = `https://${API_HOST}`;
|
|
142
|
+
var APPS_PATH = "/v1/apps";
|
|
143
|
+
var SALES_REPORTS_PATH = "/v1/salesReports";
|
|
144
|
+
var PER_PAGE = 200;
|
|
145
|
+
var DEFAULT_SALES_BACKFILL_DAYS = 30;
|
|
146
|
+
var DEFAULT_REVIEW_LIMIT = 200;
|
|
147
|
+
var SALES_REPORT_DELAY_HOURS = 48;
|
|
148
|
+
var MS_PER_DAY = 864e5;
|
|
149
|
+
var MS_PER_HOUR = 36e5;
|
|
150
|
+
var APP_ENTITY = "app_store_connect_app";
|
|
151
|
+
var APP_INSTALLS_METRIC = "app_store_connect_app_installs";
|
|
152
|
+
var APP_REVENUE_METRIC = "app_store_connect_app_revenue";
|
|
153
|
+
var APP_RATINGS_METRIC = "app_store_connect_app_ratings";
|
|
154
|
+
var appAttributesSchema = z.object({
|
|
155
|
+
name: z.string().nullish(),
|
|
156
|
+
bundleId: z.string().nullish(),
|
|
157
|
+
sku: z.string().nullish(),
|
|
158
|
+
primaryLocale: z.string().nullish()
|
|
159
|
+
});
|
|
160
|
+
var appSchema = z.object({
|
|
161
|
+
id: z.string().min(1),
|
|
162
|
+
type: z.string().optional(),
|
|
163
|
+
attributes: appAttributesSchema.nullish()
|
|
164
|
+
});
|
|
165
|
+
var appsResponseSchema = z.object({
|
|
166
|
+
data: z.array(appSchema),
|
|
167
|
+
links: z.object({
|
|
168
|
+
next: z.string().nullish()
|
|
169
|
+
}).nullish()
|
|
170
|
+
});
|
|
171
|
+
var reviewAttributesSchema = z.object({
|
|
172
|
+
rating: z.number().int().min(1).max(5).nullish(),
|
|
173
|
+
territory: z.string().nullish(),
|
|
174
|
+
title: z.string().nullish(),
|
|
175
|
+
reviewerNickname: z.string().nullish(),
|
|
176
|
+
createdDate: z.string().nullish()
|
|
177
|
+
});
|
|
178
|
+
var reviewSchema = z.object({
|
|
179
|
+
id: z.string().min(1),
|
|
180
|
+
type: z.string().optional(),
|
|
181
|
+
attributes: reviewAttributesSchema.nullish()
|
|
182
|
+
});
|
|
183
|
+
var reviewsResponseSchema = z.object({
|
|
184
|
+
data: z.array(reviewSchema),
|
|
185
|
+
links: z.object({
|
|
186
|
+
next: z.string().nullish()
|
|
187
|
+
}).nullish()
|
|
188
|
+
});
|
|
189
|
+
var appStoreConnectResources = defineResources({
|
|
190
|
+
[APP_ENTITY]: {
|
|
191
|
+
shape: "entity",
|
|
192
|
+
description: "Apps registered in the team, with bundle id, SKU, and primary locale. Synced from /v1/apps.",
|
|
193
|
+
endpoint: "GET /v1/apps",
|
|
194
|
+
fields: [
|
|
195
|
+
{ name: "name", description: "App display name." },
|
|
196
|
+
{
|
|
197
|
+
name: "bundleId",
|
|
198
|
+
description: "Bundle identifier, e.g. com.example.app."
|
|
199
|
+
},
|
|
200
|
+
{
|
|
201
|
+
name: "sku",
|
|
202
|
+
description: "App SKU set when the app was registered."
|
|
203
|
+
},
|
|
204
|
+
{
|
|
205
|
+
name: "primaryLocale",
|
|
206
|
+
description: "Primary App Store locale, e.g. en-US."
|
|
207
|
+
}
|
|
208
|
+
],
|
|
209
|
+
responses: { apps: appsResponseSchema }
|
|
210
|
+
},
|
|
211
|
+
[APP_INSTALLS_METRIC]: {
|
|
212
|
+
shape: "metric",
|
|
213
|
+
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
|
+
endpoint: "GET /v1/salesReports",
|
|
215
|
+
granularity: "daily",
|
|
216
|
+
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.",
|
|
217
|
+
dimensions: [
|
|
218
|
+
{
|
|
219
|
+
name: "appId",
|
|
220
|
+
description: "App Store Connect app id (Apple Identifier from the report)."
|
|
221
|
+
},
|
|
222
|
+
{
|
|
223
|
+
name: "countryCode",
|
|
224
|
+
description: "Two-letter ISO country code from the sale."
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
name: "productTypeIdentifier",
|
|
228
|
+
description: "Apple product type, e.g. 1 (paid app), 1F (universal app), IA1 (in-app purchase)."
|
|
229
|
+
}
|
|
230
|
+
],
|
|
231
|
+
responses: { sales_installs_report: z.string() }
|
|
232
|
+
},
|
|
233
|
+
[APP_REVENUE_METRIC]: {
|
|
234
|
+
shape: "metric",
|
|
235
|
+
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
|
+
endpoint: "GET /v1/salesReports",
|
|
237
|
+
unit: "native currency (see currency attribute)",
|
|
238
|
+
granularity: "daily",
|
|
239
|
+
notes: "Proceeds are NOT FX-normalised; each sample carries its native currency in the `currency` attribute. Filter or convert downstream.",
|
|
240
|
+
dimensions: [
|
|
241
|
+
{
|
|
242
|
+
name: "appId",
|
|
243
|
+
description: "App Store Connect app id."
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
name: "countryCode",
|
|
247
|
+
description: "Two-letter ISO country code from the sale."
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
name: "currency",
|
|
251
|
+
description: 'ISO 4217 currency of the proceeds, e.g. USD, EUR, JPY (matches Apple "Currency of Proceeds").'
|
|
252
|
+
},
|
|
253
|
+
{
|
|
254
|
+
name: "productTypeIdentifier",
|
|
255
|
+
description: "Apple product type code (same as app_installs)."
|
|
256
|
+
}
|
|
257
|
+
],
|
|
258
|
+
responses: { sales_revenue_report: z.string() }
|
|
259
|
+
},
|
|
260
|
+
[APP_RATINGS_METRIC]: {
|
|
261
|
+
shape: "metric",
|
|
262
|
+
description: "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.",
|
|
263
|
+
endpoint: "GET /v1/apps/{id}/customerReviews",
|
|
264
|
+
notes: "Apple does NOT expose the lifetime average rating over the REST API. Average over a time window downstream to get a rolling rating.",
|
|
265
|
+
dimensions: [
|
|
266
|
+
{
|
|
267
|
+
name: "appId",
|
|
268
|
+
description: "App Store Connect app id."
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
name: "territory",
|
|
272
|
+
description: "Two-letter ISO country code where the review was filed."
|
|
273
|
+
}
|
|
274
|
+
],
|
|
275
|
+
responses: { customer_reviews: reviewsResponseSchema }
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
var id = "app-store-connect";
|
|
279
|
+
var AppStoreConnectConnector = class _AppStoreConnectConnector extends BaseConnector {
|
|
280
|
+
static id = id;
|
|
281
|
+
static resources = appStoreConnectResources;
|
|
282
|
+
static schemas = schemasFromResources(appStoreConnectResources);
|
|
283
|
+
static cost = cost;
|
|
284
|
+
static create(input, ctx) {
|
|
285
|
+
const parsed = configFields.parse(input);
|
|
286
|
+
return new _AppStoreConnectConnector(
|
|
287
|
+
{
|
|
288
|
+
resources: parsed.resources,
|
|
289
|
+
vendorNumber: parsed.vendorNumber,
|
|
290
|
+
salesBackfillDays: parsed.salesBackfillDays,
|
|
291
|
+
reviewLimit: parsed.reviewLimit
|
|
292
|
+
},
|
|
293
|
+
{
|
|
294
|
+
issuerId: parsed.issuerId,
|
|
295
|
+
keyId: parsed.keyId,
|
|
296
|
+
privateKey: parsed.privateKey
|
|
297
|
+
},
|
|
298
|
+
ctx
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
id = id;
|
|
302
|
+
credentials = appStoreConnectCredentials;
|
|
303
|
+
cachedJwt = null;
|
|
304
|
+
cachedAppIds = null;
|
|
305
|
+
async buildAuthHeader() {
|
|
306
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
307
|
+
if (this.cachedJwt && this.cachedJwt.expiresAt > now + 60) {
|
|
308
|
+
return `Bearer ${this.cachedJwt.token}`;
|
|
309
|
+
}
|
|
310
|
+
const { issuerId, keyId, privateKey } = this.creds;
|
|
311
|
+
if (!issuerId || !keyId || !privateKey) {
|
|
312
|
+
throw new AuthError(`${this.id}: missing App Store Connect credentials`);
|
|
313
|
+
}
|
|
314
|
+
const exp = now + 900;
|
|
315
|
+
const jwt = await signES256Jwt({
|
|
316
|
+
header: { alg: "ES256", kid: keyId, typ: "JWT" },
|
|
317
|
+
payload: {
|
|
318
|
+
iss: issuerId,
|
|
319
|
+
iat: now,
|
|
320
|
+
exp,
|
|
321
|
+
aud: "appstoreconnect-v1"
|
|
322
|
+
},
|
|
323
|
+
privateKeyPem: privateKey
|
|
324
|
+
});
|
|
325
|
+
this.cachedJwt = { token: jwt, expiresAt: exp };
|
|
326
|
+
return `Bearer ${jwt}`;
|
|
327
|
+
}
|
|
328
|
+
async authHeaders() {
|
|
329
|
+
return {
|
|
330
|
+
Authorization: await this.buildAuthHeader(),
|
|
331
|
+
Accept: "application/json",
|
|
332
|
+
"User-Agent": connectorUserAgent(this.id)
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
sanitizeListUrl(phase, pageUrl) {
|
|
336
|
+
const allowedPath = phase === "apps" ? APPS_PATH : null;
|
|
337
|
+
if (allowedPath === null) {
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
return sanitizeAllowedUrl({
|
|
341
|
+
url: pageUrl,
|
|
342
|
+
host: API_HOST,
|
|
343
|
+
pathname: allowedPath
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
resolveCursor(cursor) {
|
|
347
|
+
if (!isAppStoreConnectCursor(cursor)) {
|
|
348
|
+
return void 0;
|
|
349
|
+
}
|
|
350
|
+
if (cursor.phase === "apps") {
|
|
351
|
+
return {
|
|
352
|
+
phase: cursor.phase,
|
|
353
|
+
page: this.sanitizeListUrl(cursor.phase, cursor.page)
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
return { phase: cursor.phase, page: null };
|
|
357
|
+
}
|
|
358
|
+
async listApps(signal) {
|
|
359
|
+
if (this.cachedAppIds !== null) {
|
|
360
|
+
return this.cachedAppIds;
|
|
361
|
+
}
|
|
362
|
+
const ids = [];
|
|
363
|
+
let url = `${API_BASE}${APPS_PATH}?limit=${PER_PAGE}`;
|
|
364
|
+
while (url !== null) {
|
|
365
|
+
if (signal?.aborted) {
|
|
366
|
+
return ids;
|
|
367
|
+
}
|
|
368
|
+
const headers = await this.authHeaders();
|
|
369
|
+
const res = await this.get(url, {
|
|
370
|
+
resource: "apps",
|
|
371
|
+
headers,
|
|
372
|
+
signal
|
|
373
|
+
});
|
|
374
|
+
for (const app of res.body.data ?? []) {
|
|
375
|
+
ids.push(app.id);
|
|
376
|
+
}
|
|
377
|
+
const next = res.body.links?.next ?? null;
|
|
378
|
+
url = this.sanitizeListUrl("apps", next);
|
|
379
|
+
}
|
|
380
|
+
this.cachedAppIds = ids;
|
|
381
|
+
return ids;
|
|
382
|
+
}
|
|
383
|
+
async fetchAppsPage(page, signal) {
|
|
384
|
+
const url = page ?? `${API_BASE}${APPS_PATH}?limit=${PER_PAGE}`;
|
|
385
|
+
const headers = await this.authHeaders();
|
|
386
|
+
const res = await this.get(url, {
|
|
387
|
+
resource: "apps",
|
|
388
|
+
headers,
|
|
389
|
+
signal
|
|
390
|
+
});
|
|
391
|
+
const items = res.body.data ?? [];
|
|
392
|
+
if (this.cachedAppIds === null) {
|
|
393
|
+
this.cachedAppIds = [];
|
|
394
|
+
}
|
|
395
|
+
for (const app of items) {
|
|
396
|
+
if (!this.cachedAppIds.includes(app.id)) {
|
|
397
|
+
this.cachedAppIds.push(app.id);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
const rawNext = res.body.links?.next ?? null;
|
|
401
|
+
const next = this.sanitizeListUrl("apps", rawNext);
|
|
402
|
+
return { items, next };
|
|
403
|
+
}
|
|
404
|
+
buildSalesReportUrl(reportDate) {
|
|
405
|
+
const vendor = this.settings.vendorNumber;
|
|
406
|
+
if (!vendor) {
|
|
407
|
+
throw new Error(
|
|
408
|
+
"vendorNumber is required for app_installs / app_revenue resources"
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
const params = new URLSearchParams();
|
|
412
|
+
params.set("filter[frequency]", "DAILY");
|
|
413
|
+
params.set("filter[reportType]", "SALES");
|
|
414
|
+
params.set("filter[reportSubType]", "SUMMARY");
|
|
415
|
+
params.set("filter[vendorNumber]", vendor);
|
|
416
|
+
params.set("filter[reportDate]", reportDate);
|
|
417
|
+
return `${API_BASE}${SALES_REPORTS_PATH}?${params.toString()}`;
|
|
418
|
+
}
|
|
419
|
+
async fetchSalesReportTsv(reportDate, signal) {
|
|
420
|
+
const url = this.buildSalesReportUrl(reportDate);
|
|
421
|
+
const res = await this.withRetry(
|
|
422
|
+
async (sig) => {
|
|
423
|
+
const headers = await this.authHeaders();
|
|
424
|
+
headers["Accept"] = "application/a-gzip";
|
|
425
|
+
const response = await globalThis.fetch(url, {
|
|
426
|
+
method: "GET",
|
|
427
|
+
headers,
|
|
428
|
+
signal: sig
|
|
429
|
+
});
|
|
430
|
+
if (response.status === 429) {
|
|
431
|
+
const retryAfter = Number(response.headers.get("retry-after") ?? "");
|
|
432
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0) {
|
|
433
|
+
await this.sleep(retryAfter * 1e3, sig);
|
|
434
|
+
}
|
|
435
|
+
return { status: "retry" };
|
|
436
|
+
}
|
|
437
|
+
return { status: "done", value: response };
|
|
438
|
+
},
|
|
439
|
+
{ signal }
|
|
440
|
+
);
|
|
441
|
+
if (res === null) {
|
|
442
|
+
throw new Error(
|
|
443
|
+
`App Store Connect sales report ${reportDate} failed: exhausted retries on HTTP 429`
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
if (res.status === 404) {
|
|
447
|
+
return null;
|
|
448
|
+
}
|
|
449
|
+
if (!res.ok) {
|
|
450
|
+
throw new Error(
|
|
451
|
+
`App Store Connect sales report ${reportDate} failed: HTTP ${res.status}`
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
const body = res.body;
|
|
455
|
+
if (!body) {
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
const decompressed = body.pipeThrough(new DecompressionStream("gzip"));
|
|
459
|
+
return await new Response(decompressed).text();
|
|
460
|
+
}
|
|
461
|
+
async fetchReviewsForApp(appId, limit, signal) {
|
|
462
|
+
const reviews = [];
|
|
463
|
+
const reviewsBase = `/v1/apps/${encodeURIComponent(appId)}/customerReviews`;
|
|
464
|
+
let url = `${API_BASE}${reviewsBase}?limit=${PER_PAGE}&sort=-createdDate`;
|
|
465
|
+
while (url !== null && reviews.length < limit) {
|
|
466
|
+
if (signal?.aborted) {
|
|
467
|
+
return reviews;
|
|
468
|
+
}
|
|
469
|
+
const headers = await this.authHeaders();
|
|
470
|
+
const res = await this.get(url, {
|
|
471
|
+
resource: "customer_reviews",
|
|
472
|
+
headers,
|
|
473
|
+
signal
|
|
474
|
+
});
|
|
475
|
+
for (const review of res.body.data ?? []) {
|
|
476
|
+
reviews.push(review);
|
|
477
|
+
if (reviews.length >= limit) {
|
|
478
|
+
break;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const rawNext = res.body.links?.next ?? null;
|
|
482
|
+
url = sanitizeAllowedUrl({
|
|
483
|
+
url: rawNext,
|
|
484
|
+
host: API_HOST,
|
|
485
|
+
pathname: reviewsBase
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
return reviews;
|
|
489
|
+
}
|
|
490
|
+
async writeApps(storage, items) {
|
|
491
|
+
const nowMs = Date.now();
|
|
492
|
+
for (const app of items) {
|
|
493
|
+
const attrs = app.attributes ?? {};
|
|
494
|
+
await storage.entity({
|
|
495
|
+
type: APP_ENTITY,
|
|
496
|
+
id: app.id,
|
|
497
|
+
attributes: {
|
|
498
|
+
name: attrs.name ?? null,
|
|
499
|
+
bundleId: attrs.bundleId ?? null,
|
|
500
|
+
sku: attrs.sku ?? null,
|
|
501
|
+
primaryLocale: attrs.primaryLocale ?? null
|
|
502
|
+
},
|
|
503
|
+
updated_at: nowMs
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
async syncSalesReports(storage, metricName, options, signal) {
|
|
508
|
+
if (!this.settings.vendorNumber) {
|
|
509
|
+
this.logger.info("skipping sales report (no vendorNumber configured)", {
|
|
510
|
+
resource: metricName
|
|
511
|
+
});
|
|
512
|
+
await storage.metrics([], { names: [metricName] });
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
const dates = computeSalesReportDates(options, this.settings);
|
|
516
|
+
const samples = [];
|
|
517
|
+
for (const reportDate of dates) {
|
|
518
|
+
if (signal?.aborted) {
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
let tsv;
|
|
522
|
+
try {
|
|
523
|
+
tsv = await this.fetchSalesReportTsv(reportDate, signal);
|
|
524
|
+
} catch (err) {
|
|
525
|
+
this.logger.warn("sales report fetch failed", {
|
|
526
|
+
reportDate,
|
|
527
|
+
resource: metricName,
|
|
528
|
+
error: err instanceof Error ? err.message : String(err)
|
|
529
|
+
});
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
if (tsv === null || tsv.length === 0) {
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
for (const sample of parseSalesReportTsv(tsv, metricName)) {
|
|
536
|
+
samples.push(sample);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
await storage.metrics(samples, { names: [metricName] });
|
|
540
|
+
}
|
|
541
|
+
async syncAppRatings(storage, signal) {
|
|
542
|
+
const appIds = await this.listApps(signal);
|
|
543
|
+
const limit = this.settings.reviewLimit ?? DEFAULT_REVIEW_LIMIT;
|
|
544
|
+
const samples = [];
|
|
545
|
+
for (const appId of appIds) {
|
|
546
|
+
if (signal?.aborted) {
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
const reviews = await this.fetchReviewsForApp(appId, limit, signal);
|
|
550
|
+
for (const review of reviews) {
|
|
551
|
+
const attrs = review.attributes ?? {};
|
|
552
|
+
if (typeof attrs.rating !== "number") {
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
const ts = isoToMs(attrs.createdDate);
|
|
556
|
+
if (ts === null) {
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
const attributes = {
|
|
560
|
+
appId,
|
|
561
|
+
reviewId: review.id,
|
|
562
|
+
territory: attrs.territory ?? null
|
|
563
|
+
};
|
|
564
|
+
samples.push({
|
|
565
|
+
name: APP_RATINGS_METRIC,
|
|
566
|
+
ts,
|
|
567
|
+
value: attrs.rating,
|
|
568
|
+
attributes
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
await storage.metrics(samples, { names: [APP_RATINGS_METRIC] });
|
|
573
|
+
}
|
|
574
|
+
async sync(options, storage, signal) {
|
|
575
|
+
const cursor = this.resolveCursor(options.cursor);
|
|
576
|
+
const isFull = options.mode === "full";
|
|
577
|
+
const phases = selectActivePhases((r) => r, PHASE_ORDER, this.settings.resources);
|
|
578
|
+
return paginateChunked({
|
|
579
|
+
phases,
|
|
580
|
+
cursor,
|
|
581
|
+
signal,
|
|
582
|
+
logger: this.logger,
|
|
583
|
+
fetchPage: async (phase, page, sig) => {
|
|
584
|
+
if (phase === "apps") {
|
|
585
|
+
return this.fetchAppsPage(page, sig);
|
|
586
|
+
}
|
|
587
|
+
return { items: [{ phase }], next: null };
|
|
588
|
+
},
|
|
589
|
+
writeBatch: async (phase, items, page) => {
|
|
590
|
+
if (phase === "apps") {
|
|
591
|
+
if (page === null && isFull) {
|
|
592
|
+
await storage.entities([], { types: [APP_ENTITY] });
|
|
593
|
+
}
|
|
594
|
+
await this.writeApps(storage, items);
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
if (phase === "app_installs") {
|
|
598
|
+
await this.syncSalesReports(
|
|
599
|
+
storage,
|
|
600
|
+
APP_INSTALLS_METRIC,
|
|
601
|
+
options,
|
|
602
|
+
signal
|
|
603
|
+
);
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
if (phase === "app_revenue") {
|
|
607
|
+
await this.syncSalesReports(
|
|
608
|
+
storage,
|
|
609
|
+
APP_REVENUE_METRIC,
|
|
610
|
+
options,
|
|
611
|
+
signal
|
|
612
|
+
);
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
if (phase === "app_ratings") {
|
|
616
|
+
await this.syncAppRatings(storage, signal);
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
};
|
|
623
|
+
function isoToMs(value) {
|
|
624
|
+
if (!value) {
|
|
625
|
+
return null;
|
|
626
|
+
}
|
|
627
|
+
const ms = Date.parse(value);
|
|
628
|
+
return Number.isFinite(ms) ? ms : null;
|
|
629
|
+
}
|
|
630
|
+
function pad2(n) {
|
|
631
|
+
return n < 10 ? `0${n}` : String(n);
|
|
632
|
+
}
|
|
633
|
+
function toIsoDate(d) {
|
|
634
|
+
return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(
|
|
635
|
+
d.getUTCDate()
|
|
636
|
+
)}`;
|
|
637
|
+
}
|
|
638
|
+
function parseSalesDate(value) {
|
|
639
|
+
const m = /^(\d{2})\/(\d{2})\/(\d{4})$/u.exec(value);
|
|
640
|
+
if (m) {
|
|
641
|
+
const month = Number(m[1]);
|
|
642
|
+
const day = Number(m[2]);
|
|
643
|
+
const year = Number(m[3]);
|
|
644
|
+
const ms = Date.UTC(year, month - 1, day);
|
|
645
|
+
return Number.isFinite(ms) ? ms : null;
|
|
646
|
+
}
|
|
647
|
+
const direct = Date.parse(`${value}T00:00:00Z`);
|
|
648
|
+
return Number.isFinite(direct) ? direct : null;
|
|
649
|
+
}
|
|
650
|
+
function computeSalesReportDates(options, settings) {
|
|
651
|
+
const now = Date.now();
|
|
652
|
+
const endMs = now - SALES_REPORT_DELAY_HOURS * MS_PER_HOUR;
|
|
653
|
+
let startMs;
|
|
654
|
+
if (options.since) {
|
|
655
|
+
const sinceMs = Date.parse(options.since);
|
|
656
|
+
startMs = Number.isFinite(sinceMs) ? sinceMs : endMs - MS_PER_DAY;
|
|
657
|
+
} else if (options.mode === "latest") {
|
|
658
|
+
startMs = endMs - 2 * MS_PER_DAY;
|
|
659
|
+
} else {
|
|
660
|
+
const days = settings.salesBackfillDays ?? DEFAULT_SALES_BACKFILL_DAYS;
|
|
661
|
+
startMs = endMs - days * MS_PER_DAY;
|
|
662
|
+
}
|
|
663
|
+
if (startMs > endMs) {
|
|
664
|
+
return [];
|
|
665
|
+
}
|
|
666
|
+
const dates = [];
|
|
667
|
+
const start = new Date(Math.floor(startMs / MS_PER_DAY) * MS_PER_DAY);
|
|
668
|
+
const end = new Date(Math.floor(endMs / MS_PER_DAY) * MS_PER_DAY);
|
|
669
|
+
for (let d = new Date(start.getTime()); d.getTime() <= end.getTime(); d.setUTCDate(d.getUTCDate() + 1)) {
|
|
670
|
+
dates.push(toIsoDate(d));
|
|
671
|
+
}
|
|
672
|
+
return dates;
|
|
673
|
+
}
|
|
674
|
+
function parseSalesReportTsv(tsv, metricName) {
|
|
675
|
+
const lines = tsv.split(/\r?\n/u).filter((l) => l.length > 0);
|
|
676
|
+
if (lines.length < 2) {
|
|
677
|
+
return [];
|
|
678
|
+
}
|
|
679
|
+
const header = lines[0].split(" ").map((h) => h.trim());
|
|
680
|
+
const idx = (name) => header.indexOf(name);
|
|
681
|
+
const beginDateIdx = idx("Begin Date");
|
|
682
|
+
const unitsIdx = idx("Units");
|
|
683
|
+
const proceedsIdx = idx("Developer Proceeds");
|
|
684
|
+
const countryIdx = idx("Country Code");
|
|
685
|
+
const appleIdIdx = idx("Apple Identifier");
|
|
686
|
+
const currencyIdx = idx("Currency of Proceeds");
|
|
687
|
+
const productTypeIdx = idx("Product Type Identifier");
|
|
688
|
+
if (beginDateIdx === -1 || appleIdIdx === -1 || countryIdx === -1 || metricName === APP_INSTALLS_METRIC && unitsIdx === -1 || metricName === APP_REVENUE_METRIC && (proceedsIdx === -1 || currencyIdx === -1)) {
|
|
689
|
+
return [];
|
|
690
|
+
}
|
|
691
|
+
const samples = [];
|
|
692
|
+
for (let i = 1; i < lines.length; i++) {
|
|
693
|
+
const row = lines[i].split(" ");
|
|
694
|
+
const ts = parseSalesDate(row[beginDateIdx]?.trim() ?? "");
|
|
695
|
+
if (ts === null) {
|
|
696
|
+
continue;
|
|
697
|
+
}
|
|
698
|
+
const appId = row[appleIdIdx]?.trim() ?? "";
|
|
699
|
+
if (appId === "") {
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
const countryCode = row[countryIdx]?.trim() ?? "";
|
|
703
|
+
const productType = productTypeIdx === -1 ? "" : row[productTypeIdx]?.trim() ?? "";
|
|
704
|
+
if (metricName === APP_INSTALLS_METRIC) {
|
|
705
|
+
const raw = row[unitsIdx]?.trim() ?? "";
|
|
706
|
+
const value = Number.parseFloat(raw);
|
|
707
|
+
if (!Number.isFinite(value)) {
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
const attributes = {
|
|
711
|
+
appId,
|
|
712
|
+
countryCode,
|
|
713
|
+
productTypeIdentifier: productType
|
|
714
|
+
};
|
|
715
|
+
samples.push({ name: metricName, ts, value, attributes });
|
|
716
|
+
} else {
|
|
717
|
+
const raw = row[proceedsIdx]?.trim() ?? "";
|
|
718
|
+
const value = Number.parseFloat(raw);
|
|
719
|
+
if (!Number.isFinite(value)) {
|
|
720
|
+
continue;
|
|
721
|
+
}
|
|
722
|
+
const currency = row[currencyIdx]?.trim() ?? "";
|
|
723
|
+
const attributes = {
|
|
724
|
+
appId,
|
|
725
|
+
countryCode,
|
|
726
|
+
currency,
|
|
727
|
+
productTypeIdentifier: productType
|
|
728
|
+
};
|
|
729
|
+
samples.push({ name: metricName, ts, value, attributes });
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
return samples;
|
|
733
|
+
}
|
|
734
|
+
async function signES256Jwt({
|
|
735
|
+
header,
|
|
736
|
+
payload,
|
|
737
|
+
privateKeyPem
|
|
738
|
+
}) {
|
|
739
|
+
const encoder = new TextEncoder();
|
|
740
|
+
const headerB64 = base64urlEncode(encoder.encode(JSON.stringify(header)));
|
|
741
|
+
const payloadB64 = base64urlEncode(encoder.encode(JSON.stringify(payload)));
|
|
742
|
+
const signingInput = `${headerB64}.${payloadB64}`;
|
|
743
|
+
const key = await importEcPrivateKey(privateKeyPem);
|
|
744
|
+
const signature = await globalThis.crypto.subtle.sign(
|
|
745
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
746
|
+
key,
|
|
747
|
+
encoder.encode(signingInput)
|
|
748
|
+
);
|
|
749
|
+
return `${signingInput}.${base64urlEncode(new Uint8Array(signature))}`;
|
|
750
|
+
}
|
|
751
|
+
async function importEcPrivateKey(pem) {
|
|
752
|
+
const trimmed = pem.trim();
|
|
753
|
+
const body = trimmed.replace(/-----BEGIN PRIVATE KEY-----/u, "").replace(/-----END PRIVATE KEY-----/u, "").replace(/\s+/gu, "");
|
|
754
|
+
if (body.length === 0) {
|
|
755
|
+
throw new AuthError(
|
|
756
|
+
"app-store-connect: privateKey is empty or not a PEM-encoded PKCS#8 key"
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
const der = base64ToBytes(body);
|
|
760
|
+
return globalThis.crypto.subtle.importKey(
|
|
761
|
+
"pkcs8",
|
|
762
|
+
der,
|
|
763
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
764
|
+
false,
|
|
765
|
+
["sign"]
|
|
766
|
+
);
|
|
767
|
+
}
|
|
768
|
+
function base64ToBytes(b64) {
|
|
769
|
+
return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
|
|
770
|
+
}
|
|
771
|
+
function base64urlEncode(bytes) {
|
|
772
|
+
let binary = "";
|
|
773
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
774
|
+
binary += String.fromCharCode(bytes[i]);
|
|
775
|
+
}
|
|
776
|
+
return btoa(binary).replace(/\+/gu, "-").replace(/\//gu, "_").replace(/=+$/u, "");
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// src/index.ts
|
|
780
|
+
var index_default = AppStoreConnectConnector;
|
|
781
|
+
export {
|
|
782
|
+
AppStoreConnectConnector,
|
|
783
|
+
configFields,
|
|
784
|
+
cost,
|
|
785
|
+
index_default as default,
|
|
786
|
+
doc,
|
|
787
|
+
id,
|
|
788
|
+
appStoreConnectResources as resources
|
|
789
|
+
};
|
|
790
|
+
//# sourceMappingURL=index.js.map
|