@oxyhq/core 19.1.2 → 20.1.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.
Files changed (72) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +16 -0
  3. package/dist/cjs/.tsbuildinfo +1 -1
  4. package/dist/cjs/HttpService.js +23 -18
  5. package/dist/cjs/i18n/accountCategoryLabels.js +44 -0
  6. package/dist/cjs/i18n/accountRoleLabels.js +27 -0
  7. package/dist/cjs/i18n/reputationCategoryLabels.js +20 -0
  8. package/dist/cjs/i18n/trustTierLabels.js +19 -0
  9. package/dist/cjs/index.js +19 -9
  10. package/dist/cjs/mixins/OxyServices.chains.js +73 -0
  11. package/dist/cjs/mixins/OxyServices.followGraph.js +17 -0
  12. package/dist/cjs/mixins/OxyServices.store.js +266 -0
  13. package/dist/cjs/mixins/OxyServices.utility.js +159 -104
  14. package/dist/cjs/mixins/index.js +7 -0
  15. package/dist/cjs/server/rateLimit.js +15 -6
  16. package/dist/cjs/session/accountProjection.js +31 -6
  17. package/dist/cjs/utils/errorUtils.js +65 -1
  18. package/dist/esm/.tsbuildinfo +1 -1
  19. package/dist/esm/HttpService.js +24 -19
  20. package/dist/esm/i18n/accountCategoryLabels.js +37 -0
  21. package/dist/esm/i18n/accountRoleLabels.js +20 -0
  22. package/dist/esm/i18n/reputationCategoryLabels.js +13 -0
  23. package/dist/esm/i18n/trustTierLabels.js +12 -0
  24. package/dist/esm/index.js +11 -8
  25. package/dist/esm/mixins/OxyServices.chains.js +70 -0
  26. package/dist/esm/mixins/OxyServices.followGraph.js +17 -0
  27. package/dist/esm/mixins/OxyServices.store.js +263 -0
  28. package/dist/esm/mixins/OxyServices.utility.js +159 -104
  29. package/dist/esm/mixins/index.js +7 -0
  30. package/dist/esm/server/rateLimit.js +15 -6
  31. package/dist/esm/session/accountProjection.js +30 -6
  32. package/dist/esm/utils/errorUtils.js +63 -1
  33. package/dist/types/.tsbuildinfo +1 -1
  34. package/dist/types/i18n/accountCategoryLabels.d.ts +34 -0
  35. package/dist/types/i18n/accountRoleLabels.d.ts +10 -0
  36. package/dist/types/i18n/reputationCategoryLabels.d.ts +10 -0
  37. package/dist/types/i18n/trustTierLabels.d.ts +9 -0
  38. package/dist/types/index.d.ts +14 -2
  39. package/dist/types/mixins/OxyServices.chains.d.ts +156 -0
  40. package/dist/types/mixins/OxyServices.followGraph.d.ts +13 -0
  41. package/dist/types/mixins/OxyServices.store.d.ts +334 -0
  42. package/dist/types/mixins/OxyServices.utility.d.ts +31 -8
  43. package/dist/types/mixins/index.d.ts +3 -1
  44. package/dist/types/session/accountProjection.d.ts +20 -4
  45. package/dist/types/utils/errorUtils.d.ts +67 -0
  46. package/package.json +7 -6
  47. package/src/HttpService.ts +29 -22
  48. package/src/__tests__/parseHttpErrorBody.test.ts +116 -0
  49. package/src/__tests__/serverValueImportsDeclared.test.ts +7 -0
  50. package/src/i18n/__tests__/accountCategoryLabels.test.ts +62 -0
  51. package/src/i18n/__tests__/accountRoleLabels.test.ts +54 -0
  52. package/src/i18n/__tests__/reputationCategoryLabels.test.ts +56 -0
  53. package/src/i18n/__tests__/trustTierLabels.test.ts +47 -0
  54. package/src/i18n/accountCategoryLabels.ts +44 -0
  55. package/src/i18n/accountRoleLabels.ts +26 -0
  56. package/src/i18n/reputationCategoryLabels.ts +20 -0
  57. package/src/i18n/trustTierLabels.ts +18 -0
  58. package/src/index.ts +43 -6
  59. package/src/mixins/OxyServices.chains.ts +134 -0
  60. package/src/mixins/OxyServices.followGraph.ts +24 -0
  61. package/src/mixins/OxyServices.store.ts +585 -0
  62. package/src/mixins/OxyServices.utility.ts +161 -108
  63. package/src/mixins/__tests__/chains.test.ts +113 -0
  64. package/src/mixins/__tests__/followGraph.test.ts +19 -0
  65. package/src/mixins/__tests__/store.test.ts +304 -0
  66. package/src/mixins/__tests__/userTokenAuth.test.ts +746 -0
  67. package/src/mixins/index.ts +9 -0
  68. package/src/server/__tests__/rateLimit.test.ts +47 -0
  69. package/src/server/rateLimit.ts +18 -8
  70. package/src/session/__tests__/accountProjection.test.ts +98 -0
  71. package/src/session/accountProjection.ts +37 -6
  72. package/src/utils/errorUtils.ts +116 -5
@@ -15,7 +15,7 @@
15
15
  import { TTLCache, registerCacheForCleanup } from './utils/cache.js';
16
16
  import { RequestDeduplicator, RequestQueue, SimpleLogger } from './utils/requestUtils.js';
17
17
  import { retryAsync } from './utils/asyncUtils.js';
18
- import { handleHttpError } from './utils/errorUtils.js';
18
+ import { handleHttpError, parseHttpErrorBody } from './utils/errorUtils.js';
19
19
  import { jwtDecode } from 'jwt-decode';
20
20
  import { isNative, getPlatformOS } from './utils/platform.js';
21
21
  import { isReactNative } from '@oxyhq/protocol';
@@ -447,32 +447,37 @@ export class HttpService {
447
447
  // Failed to parse error body — not a CSRF error
448
448
  }
449
449
  }
450
- // Try to parse error response (handle empty/malformed JSON)
451
- let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
452
- const contentType = response.headers.get('content-type');
453
- if (contentType && contentType.includes('application/json')) {
450
+ // Read the error body (may be absent, non-JSON, empty or malformed).
451
+ // Anything unreadable leaves `errorBody` undefined and degrades to the
452
+ // status-based message — an error path that throws its own error is
453
+ // worse than the error it was reporting.
454
+ let errorBody;
455
+ const errorContentType = response.headers.get('content-type');
456
+ if (errorContentType?.includes('application/json')) {
454
457
  try {
455
- const errorData = await response.json();
456
- // Accept either structured error field from API responses.
457
- if (errorData?.message) {
458
- errorMessage = errorData.message;
459
- }
460
- else if (errorData?.error_description) {
461
- // RFC 6749 §5.2 / RFC 6750 §3 — OAuth endpoints surface human text here.
462
- errorMessage = errorData.error_description;
463
- }
464
- else if (errorData?.error) {
465
- errorMessage = errorData.error;
466
- }
458
+ errorBody = await response.json();
467
459
  }
468
460
  catch (parseError) {
469
461
  // Malformed JSON or empty response - use status text
470
462
  this.logger.warn('Failed to parse error response JSON:', parseError);
471
463
  }
472
464
  }
473
- const error = new Error(errorMessage);
465
+ // `parseHttpErrorBody` handles every envelope in use, including the
466
+ // nested `{ error: { code, message } }` shape — assigning that nested
467
+ // OBJECT as the message is what produced `"[object Object]"`.
468
+ const parsed = parseHttpErrorBody(errorBody);
469
+ const error = new Error(parsed.message ?? `HTTP ${response.status}: ${response.statusText}`);
474
470
  error.status = response.status;
475
- error.response = { status: response.status, statusText: response.statusText };
471
+ error.response = { status: response.status, statusText: response.statusText, data: errorBody };
472
+ // Only set `code`/`details` when the server actually sent them.
473
+ // Assigning `undefined` would still create the property, which changes
474
+ // how `handleHttpError` classifies the error downstream.
475
+ if (parsed.code !== undefined) {
476
+ error.code = parsed.code;
477
+ }
478
+ if (parsed.details !== undefined) {
479
+ error.details = parsed.details;
480
+ }
476
481
  throw error;
477
482
  }
478
483
  // Handle different response types (optimized - read response once)
@@ -0,0 +1,37 @@
1
+ import enUS from './locales/en-US.json' with { type: "json" };
2
+ import { translate } from './index.js';
3
+ /**
4
+ * Every account category's English name, keyed by its stable id.
5
+ *
6
+ * **The annotation is the point.** The vocabulary lives in `@oxyhq/contracts`
7
+ * and the names live in `locales/en-US.json`, so they are two lists that must
8
+ * agree and nothing but a type can make them. Declaring the JSON node as a
9
+ * TOTAL `Record<AccountCategoryId, string>` turns "somebody added a category at
10
+ * Oxy and nobody wrote its English" into a `TS2741` naming the missing id, at
11
+ * build time, instead of a picker row that paints `accounts.accountCategory.<id>`
12
+ * at a user trying to choose one.
13
+ *
14
+ * That failure is not hypothetical. The screen previously wrote `t(key) || id`,
15
+ * whose author believed an unnamed id would degrade to its raw slug. It cannot:
16
+ * {@link translate} echoes the KEY when it resolves nothing, and a non-empty
17
+ * string is never falsy, so the `|| id` arm was unreachable and the output was
18
+ * the dotted key. A runtime fallback that cannot run is worse than none,
19
+ * because it reads as protection.
20
+ *
21
+ * Totality is over `ACCOUNT_CATEGORY_IDS`, which RETAINS withdrawn ids, so an
22
+ * account still carrying a retired category keeps rendering its name while no
23
+ * picker offers it again. Retired and unknown are different cases: only an id
24
+ * outside the union is unnameable, which is why this is keyed by
25
+ * `AccountCategoryId` and not by `string`.
26
+ */
27
+ /**
28
+ * Module-scoped, NOT re-exported from the package index: the annotation is the
29
+ * whole job, and it does that job without being public API. It carries no
30
+ * `Object.freeze` and no `Readonly<>` for the same reason — those existed only
31
+ * to make an exported reference safe from a consumer's stray write, and there
32
+ * is no such consumer. Exported from the MODULE so its own test can name it.
33
+ */
34
+ export const EN_ACCOUNT_CATEGORY_LABELS = enUS.accounts.accountCategory;
35
+ export function accountCategoryLabel(locale, id) {
36
+ return translate(locale, `accounts.accountCategory.${id}`);
37
+ }
@@ -0,0 +1,20 @@
1
+ import enUS from './locales/en-US.json' with { type: "json" };
2
+ import { translate } from './index.js';
3
+ /**
4
+ * Every account member role's English name, keyed by its stable id.
5
+ *
6
+ * Totality is over the closed `AccountRole` union so a new role without an
7
+ * English label is a build error, not a members row that paints
8
+ * `accounts.roles.<role>.label`.
9
+ */
10
+ export const EN_ACCOUNT_ROLE_LABELS = {
11
+ owner: enUS.accounts.roles.owner.label,
12
+ admin: enUS.accounts.roles.admin.label,
13
+ editor: enUS.accounts.roles.editor.label,
14
+ developer: enUS.accounts.roles.developer.label,
15
+ billing: enUS.accounts.roles.billing.label,
16
+ viewer: enUS.accounts.roles.viewer.label,
17
+ };
18
+ export function accountRoleLabel(locale, role) {
19
+ return translate(locale, `accounts.roles.${role}.label`);
20
+ }
@@ -0,0 +1,13 @@
1
+ import enUS from './locales/en-US.json' with { type: "json" };
2
+ import { translate } from './index.js';
3
+ /**
4
+ * Every reputation rule category's English name, keyed by its stable id.
5
+ *
6
+ * Totality is over `REPUTATION_CATEGORIES` from `@oxyhq/contracts` so a new
7
+ * category added server-side without an English label is a build error, not a
8
+ * Trust Rules section title that paints `trust.rules.categories.<id>`.
9
+ */
10
+ export const EN_REPUTATION_CATEGORY_LABELS = enUS.trust.rules.categories;
11
+ export function reputationCategoryLabel(locale, id) {
12
+ return translate(locale, `trust.rules.categories.${id}`);
13
+ }
@@ -0,0 +1,12 @@
1
+ import enUS from './locales/en-US.json' with { type: "json" };
2
+ import { translate } from './index.js';
3
+ /**
4
+ * Every trust tier's English name, keyed by its stable id.
5
+ *
6
+ * Totality is over `TRUST_TIERS` from `@oxyhq/contracts` so a new tier without
7
+ * an English label is a build error, not a chip that paints `trust.tiers.<id>`.
8
+ */
9
+ export const EN_TRUST_TIER_LABELS = enUS.trust.tiers;
10
+ export function trustTierLabel(locale, tier) {
11
+ return translate(locale, `trust.tiers.${tier}`);
12
+ }
package/dist/esm/index.js CHANGED
@@ -110,11 +110,15 @@ export { DEFAULT_CIRCUIT_BREAKER_CONFIG, createCircuitBreakerState, calculateBac
110
110
  // i18n
111
111
  // ---------------------------------------------------------------------------
112
112
  export { translate } from './i18n/index.js';
113
+ export { accountCategoryLabel } from './i18n/accountCategoryLabels.js';
114
+ export { accountRoleLabel } from './i18n/accountRoleLabels.js';
115
+ export { reputationCategoryLabel } from './i18n/reputationCategoryLabels.js';
116
+ export { trustTierLabel } from './i18n/trustTierLabels.js';
113
117
  // ---------------------------------------------------------------------------
114
118
  // API request / URL helpers
115
119
  // ---------------------------------------------------------------------------
116
120
  export { buildQueryParams, buildSearchParams, buildUrl, buildPaginationParams, safeJsonParse, } from './utils/apiUtils.js';
117
- export { ErrorCodes, createApiError, handleHttpError, validateRequiredFields, } from './utils/errorUtils.js';
121
+ export { ErrorCodes, createApiError, handleHttpError, isHttpRequestError, parseHttpErrorBody, validateRequiredFields, } from './utils/errorUtils.js';
118
122
  export { retryAsync } from './utils/asyncUtils.js';
119
123
  // ---------------------------------------------------------------------------
120
124
  // Validation
@@ -173,13 +177,12 @@ export { deviceStateToClientSessions, activeSessionIdOf, activeUserOf, accountId
173
177
  // chooser: device sign-ins ∪ account graph, deduped by accountId). Pure +
174
178
  // I/O-free — the caller hydrates profiles via `getUsersByIds`. Shared by
175
179
  // `@oxyhq/services` and auth.oxy.so so the list can't diverge.
176
- // `isSwitchTargetAccount` is the switcher's own question ("can I become this
177
- // account?"), exported so a surface that renders `AccountNode`s rather than the
178
- // projection the Console's workspace switcher, the accounts app's
179
- // managed-accounts rows asks the SAME question instead of testing a kind
180
- // literal. It is NOT `isActAsEligibleKind`: that one is false for `personal`
181
- // too, so gating a switcher on it alone empties the list.
182
- export { isSwitchTargetAccount, projectSwitchableAccounts, switchableAccountIds, } from './session/accountProjection.js';
180
+ // `isSwitchTargetAccount` is the structural half ("is this kind switchable at
181
+ // all?"); `canSwitchIntoAccount` adds the caller's `account:act_as` permission.
182
+ // Both are exported so surfaces that render `AccountNode`s rather than the
183
+ // projection — the Console workspace switcher, managed-accounts rows ask the
184
+ // SAME questions instead of testing a kind literal.
185
+ export { isSwitchTargetAccount, canSwitchIntoAccount, projectSwitchableAccounts, switchableAccountIds, } from './session/accountProjection.js';
183
186
  // Headless controller for the unified account dialog. Framework-agnostic
184
187
  // state machine + subscribe/getSnapshot store (bind via `useSyncExternalStore`)
185
188
  // — sign-in is passkey (WebAuthn) or the Commons QR / shared-keychain handoff;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Chains — the shared record log every Oxy app reads and writes.
3
+ *
4
+ * A person has ONE chain. An app appends its own records to it and projects its
5
+ * feeds from what it reads back, instead of keeping a private copy of the same
6
+ * person's activity. This mixin is the client half of `/chains` in oxy-api, and
7
+ * it exists so that adopting the chain costs an app no HTTP of its own — the
8
+ * whole point of the shared substrate is that the second app writes less code
9
+ * than the first, not the same amount in a different file.
10
+ *
11
+ * ## Both calls are SERVICE-authenticated
12
+ *
13
+ * They go through `makeServiceRequest`, so they only work on a backend that has
14
+ * called `configureServiceAuth()`. That is not an accident of implementation: an
15
+ * append writes to someone else's chain and a read spans many subjects, so
16
+ * neither belongs in a browser holding a user session. A frontend that needs
17
+ * this asks its own backend.
18
+ *
19
+ * The authority is checked server-side and cannot be talked out of from here:
20
+ * `chains:write` plus the application's own `chainNamespaces` for an append,
21
+ * `chains:read` plus the public-collection policy for a read. A call that
22
+ * violates either gets a 403 or an empty page — this client adds no
23
+ * pre-validation that could drift from the server's answer.
24
+ */
25
+ export function OxyServicesChainsMixin(Base) {
26
+ return class extends Base {
27
+ constructor(...args) {
28
+ super(...args);
29
+ }
30
+ /**
31
+ * Append a record to `oxyUserId`'s chain under `collection`/`rkey`.
32
+ *
33
+ * Oxy issues and signs it; the calling app never holds a chain signing key.
34
+ * `rkey` is the app's own id for the thing — reusing it later supersedes the
35
+ * earlier record for that key, which is how an edit works.
36
+ *
37
+ * Requires the `chains:write` scope AND `collection` falling under one of
38
+ * this application's granted `chainNamespaces`. Both are enforced by the
39
+ * server; a violation throws with a 403.
40
+ */
41
+ async appendChainRecord(params) {
42
+ return this.makeServiceRequest('POST', '/chains/records', params);
43
+ }
44
+ /**
45
+ * Records published by any of `oxyUserIds` under any of `collections`,
46
+ * oldest first — the read a cross-app feed is projected from.
47
+ *
48
+ * Only collections Oxy declares PUBLIC come back, whatever is asked for; a
49
+ * private one yields nothing rather than an error.
50
+ *
51
+ * **Re-poll from slightly BEFORE your last cursor and dedupe by
52
+ * `recordId`.** The chain's pagination axis is a transaction-start
53
+ * timestamp, so a record can commit behind a cursor that already passed it.
54
+ * Re-delivering one costs bytes; skipping one costs a record that never
55
+ * appears. Projections are expected to be idempotent for exactly this
56
+ * reason.
57
+ */
58
+ async readChainRecords(params) {
59
+ const query = new URLSearchParams({
60
+ authors: params.oxyUserIds.join(','),
61
+ collections: params.collections.join(','),
62
+ });
63
+ if (params.since)
64
+ query.set('since', params.since);
65
+ if (params.limit !== undefined)
66
+ query.set('limit', String(params.limit));
67
+ return this.makeServiceRequest('GET', `/chains/records?${query.toString()}`);
68
+ }
69
+ };
70
+ }
@@ -156,6 +156,23 @@ export function OxyServicesFollowGraphMixin(Base) {
156
156
  throw this.handleError(error);
157
157
  }
158
158
  }
159
+ /**
160
+ * Release a namespace the calling application holds, when nothing is
161
+ registered inside it yet.
162
+ *
163
+ * Idempotent when the namespace is already unowned (`released: false`).
164
+ * Exists because claims are first-come and registration runs on boot — a
165
+ * development build with the wrong client id can bind a name permanently
166
+ * unless the holder can give it back.
167
+ */
168
+ async releaseFollowNamespace(namespace) {
169
+ try {
170
+ return await this.makeRequest('DELETE', `/v2/follow-targets/namespaces/${encodeURIComponent(namespace)}`, undefined, { cache: false });
171
+ }
172
+ catch (error) {
173
+ throw this.handleError(error);
174
+ }
175
+ }
159
176
  /**
160
177
  * Declare what following a kind of thing MEANS: the verb clients render,
161
178
  * whether reverse lookups are public, whether it federates.
@@ -0,0 +1,263 @@
1
+ import { CACHE_TIMES } from './mixinHelpers.js';
2
+ /** Read one page out of that envelope. */
3
+ function pageOf(res) {
4
+ return {
5
+ items: res.data ?? [],
6
+ total: res.pagination?.total ?? 0,
7
+ hasMore: res.pagination?.hasMore ?? false,
8
+ };
9
+ }
10
+ /**
11
+ * Build a query string from the options that were actually supplied.
12
+ *
13
+ * Generic over the options object rather than taking a `Record`: an interface
14
+ * has no implicit index signature in TypeScript, so `StoreReviewsOptions` would
15
+ * not be assignable to one and every call site would need a cast.
16
+ */
17
+ function queryOf(params) {
18
+ const search = new URLSearchParams();
19
+ for (const [key, value] of Object.entries(params)) {
20
+ if (value !== undefined)
21
+ search.set(key, String(value));
22
+ }
23
+ const rendered = search.toString();
24
+ return rendered ? `?${rendered}` : '';
25
+ }
26
+ export function OxyServicesStoreMixin(Base) {
27
+ return class extends Base {
28
+ constructor(...args) {
29
+ super(...args);
30
+ }
31
+ // =========================================================================
32
+ // The storefront — /store. No authentication: everything served is public.
33
+ // =========================================================================
34
+ /** The shelves, in the order the store curates them. */
35
+ async listStoreCategories() {
36
+ try {
37
+ const res = await this.makeRequest('GET', '/store/categories', undefined, { cache: true, cacheTTL: CACHE_TIMES.MEDIUM });
38
+ return res.data ?? [];
39
+ }
40
+ catch (error) {
41
+ throw this.handleError(error);
42
+ }
43
+ }
44
+ /**
45
+ * Published listings, newest first, optionally one shelf.
46
+ *
47
+ * An unknown category slug is an EMPTY shelf, not every app on the store —
48
+ * so a typo shows nothing rather than showing everything.
49
+ *
50
+ * @param options - `category` is a category slug; `limit` defaults to 24.
51
+ */
52
+ async listStoreApps(options = {}) {
53
+ try {
54
+ const res = await this.makeRequest('GET', `/store/apps${queryOf(options)}`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
55
+ return pageOf(res);
56
+ }
57
+ catch (error) {
58
+ throw this.handleError(error);
59
+ }
60
+ }
61
+ /**
62
+ * One store page.
63
+ *
64
+ * A draft answers 404 exactly as an unknown slug does: whether an
65
+ * unpublished page exists under a name is not something a visitor learns.
66
+ *
67
+ * @param slug - The listing's public slug, not an application id.
68
+ */
69
+ async getStoreApp(slug) {
70
+ try {
71
+ const res = await this.makeRequest('GET', `/store/apps/${encodeURIComponent(slug)}`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
72
+ return res.data;
73
+ }
74
+ catch (error) {
75
+ throw this.handleError(error);
76
+ }
77
+ }
78
+ /** Visible reviews for a published app, each with the publisher's reply. */
79
+ async listStoreReviews(slug, options = {}) {
80
+ try {
81
+ const res = await this.makeRequest('GET', `/store/apps/${encodeURIComponent(slug)}/reviews${queryOf(options)}`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
82
+ return pageOf(res);
83
+ }
84
+ catch (error) {
85
+ throw this.handleError(error);
86
+ }
87
+ }
88
+ // =========================================================================
89
+ // Reviewing — any signed-in Oxy account
90
+ // =========================================================================
91
+ /** The caller's own review of an app, or `null` if they have not written one. */
92
+ async getMyStoreReview(slug) {
93
+ try {
94
+ const res = await this.makeRequest('GET', `/store/apps/${encodeURIComponent(slug)}/review`, undefined, { cache: false });
95
+ return res.data ?? null;
96
+ }
97
+ catch (error) {
98
+ throw this.handleError(error);
99
+ }
100
+ }
101
+ /**
102
+ * Write the caller's review, or replace what they said before.
103
+ *
104
+ * A person has one review per app, so this sets it rather than adding one.
105
+ * Rewriting does not clear a moderator's decision: a hidden review stays
106
+ * hidden when its author edits it.
107
+ */
108
+ async writeStoreReview(slug, input) {
109
+ try {
110
+ const res = await this.makeRequest('PUT', `/store/apps/${encodeURIComponent(slug)}/review`, input, { cache: false });
111
+ return res.data;
112
+ }
113
+ catch (error) {
114
+ throw this.handleError(error);
115
+ }
116
+ }
117
+ /** Withdraw the caller's own review. A real delete — the words were theirs. */
118
+ async deleteMyStoreReview(slug) {
119
+ try {
120
+ await this.makeRequest('DELETE', `/store/apps/${encodeURIComponent(slug)}/review`, undefined, { cache: false });
121
+ }
122
+ catch (error) {
123
+ throw this.handleError(error);
124
+ }
125
+ }
126
+ /**
127
+ * Answer a review on the publisher's behalf.
128
+ *
129
+ * Requires `app:update` over the application's owning account — the same
130
+ * permission that guards every other write to that application. Addressed
131
+ * by review id because the reply belongs to the review, and a listing can be
132
+ * renamed or withdrawn out from under it.
133
+ */
134
+ async replyToStoreReview(reviewId, body) {
135
+ try {
136
+ const res = await this.makeRequest('PUT', `/store/reviews/${encodeURIComponent(reviewId)}/reply`, { body }, { cache: false });
137
+ return res.data;
138
+ }
139
+ catch (error) {
140
+ throw this.handleError(error);
141
+ }
142
+ }
143
+ /** Withdraw the publisher's answer. Same permission that wrote it. */
144
+ async deleteStoreReviewReply(reviewId) {
145
+ try {
146
+ await this.makeRequest('DELETE', `/store/reviews/${encodeURIComponent(reviewId)}/reply`, undefined, { cache: false });
147
+ }
148
+ catch (error) {
149
+ throw this.handleError(error);
150
+ }
151
+ }
152
+ // =========================================================================
153
+ // The publisher's listing — /applications/:appId/listing
154
+ // =========================================================================
155
+ /** The application's store page in whatever state, or `null` if it has none. */
156
+ async getAppListing(applicationId) {
157
+ try {
158
+ return await this.makeRequest('GET', `/applications/${encodeURIComponent(applicationId)}/listing`, undefined, { cache: false });
159
+ }
160
+ catch (error) {
161
+ throw this.handleError(error);
162
+ }
163
+ }
164
+ /**
165
+ * Create the page or replace its content. Never its status.
166
+ *
167
+ * Editing does not move a page: correcting a typo on a live listing leaves
168
+ * it live, and fixing a rejected one does not re-submit it.
169
+ */
170
+ async writeAppListing(applicationId, input) {
171
+ try {
172
+ return await this.makeRequest('PUT', `/applications/${encodeURIComponent(applicationId)}/listing`, input, { cache: false });
173
+ }
174
+ catch (error) {
175
+ throw this.handleError(error);
176
+ }
177
+ }
178
+ /** Hand the page to the store for review. From a draft, or a rejected page once fixed. */
179
+ async submitAppListing(applicationId) {
180
+ try {
181
+ return await this.makeRequest('POST', `/applications/${encodeURIComponent(applicationId)}/listing/submit`, undefined, { cache: false });
182
+ }
183
+ catch (error) {
184
+ throw this.handleError(error);
185
+ }
186
+ }
187
+ /**
188
+ * Take the page down, or withdraw it from the queue.
189
+ *
190
+ * Back to a draft, never deleted: the slug, the words and the screenshots
191
+ * are the publisher's work, and the reviews were never the listing's to take
192
+ * with them.
193
+ */
194
+ async unpublishAppListing(applicationId) {
195
+ try {
196
+ return await this.makeRequest('POST', `/applications/${encodeURIComponent(applicationId)}/listing/unpublish`, undefined, { cache: false });
197
+ }
198
+ catch (error) {
199
+ throw this.handleError(error);
200
+ }
201
+ }
202
+ // =========================================================================
203
+ // Screenshots
204
+ // =========================================================================
205
+ /** Every picture on the listing, in the author's order. */
206
+ async listAppListingScreenshots(applicationId) {
207
+ try {
208
+ return await this.makeRequest('GET', `/applications/${encodeURIComponent(applicationId)}/listing/screenshots`, undefined, { cache: false });
209
+ }
210
+ catch (error) {
211
+ throw this.handleError(error);
212
+ }
213
+ }
214
+ /**
215
+ * Attach an already-uploaded image, appended to the end.
216
+ *
217
+ * Upload through the assets surface first; the store keeps a reference
218
+ * rather than a second copy of the asset pipeline. The file must be live, an
219
+ * image, and one the caller is entitled to.
220
+ */
221
+ async addAppListingScreenshot(applicationId, input) {
222
+ try {
223
+ return await this.makeRequest('POST', `/applications/${encodeURIComponent(applicationId)}/listing/screenshots`, input, { cache: false });
224
+ }
225
+ catch (error) {
226
+ throw this.handleError(error);
227
+ }
228
+ }
229
+ /** Edit a picture's caption or the frame it was taken in. Order is {@link reorderAppListingScreenshots}. */
230
+ async updateAppListingScreenshot(applicationId, screenshotId, input) {
231
+ try {
232
+ return await this.makeRequest('PATCH', `/applications/${encodeURIComponent(applicationId)}/listing/screenshots/${encodeURIComponent(screenshotId)}`, input, { cache: false });
233
+ }
234
+ catch (error) {
235
+ throw this.handleError(error);
236
+ }
237
+ }
238
+ /** Remove a picture. The uploaded file stays — it may be in use elsewhere. */
239
+ async deleteAppListingScreenshot(applicationId, screenshotId) {
240
+ try {
241
+ await this.makeRequest('DELETE', `/applications/${encodeURIComponent(applicationId)}/listing/screenshots/${encodeURIComponent(screenshotId)}`, undefined, { cache: false });
242
+ }
243
+ catch (error) {
244
+ throw this.handleError(error);
245
+ }
246
+ }
247
+ /**
248
+ * Set the order of every picture at once.
249
+ *
250
+ * Send EVERY id on the listing, exactly once, in the order they should
251
+ * appear. A partial list is rejected rather than applied: it would leave the
252
+ * pictures it omits at their old positions, interleaved with the new ones.
253
+ */
254
+ async reorderAppListingScreenshots(applicationId, screenshotIds) {
255
+ try {
256
+ return await this.makeRequest('PUT', `/applications/${encodeURIComponent(applicationId)}/listing/screenshots/order`, { screenshotIds }, { cache: false });
257
+ }
258
+ catch (error) {
259
+ throw this.handleError(error);
260
+ }
261
+ }
262
+ };
263
+ }