@oxyhq/core 19.1.2 → 20.0.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 (49) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +15 -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.followGraph.js +17 -0
  11. package/dist/cjs/session/accountProjection.js +31 -6
  12. package/dist/cjs/utils/errorUtils.js +65 -1
  13. package/dist/esm/.tsbuildinfo +1 -1
  14. package/dist/esm/HttpService.js +24 -19
  15. package/dist/esm/i18n/accountCategoryLabels.js +37 -0
  16. package/dist/esm/i18n/accountRoleLabels.js +20 -0
  17. package/dist/esm/i18n/reputationCategoryLabels.js +13 -0
  18. package/dist/esm/i18n/trustTierLabels.js +12 -0
  19. package/dist/esm/index.js +11 -8
  20. package/dist/esm/mixins/OxyServices.followGraph.js +17 -0
  21. package/dist/esm/session/accountProjection.js +30 -6
  22. package/dist/esm/utils/errorUtils.js +63 -1
  23. package/dist/types/.tsbuildinfo +1 -1
  24. package/dist/types/i18n/accountCategoryLabels.d.ts +34 -0
  25. package/dist/types/i18n/accountRoleLabels.d.ts +10 -0
  26. package/dist/types/i18n/reputationCategoryLabels.d.ts +10 -0
  27. package/dist/types/i18n/trustTierLabels.d.ts +9 -0
  28. package/dist/types/index.d.ts +7 -2
  29. package/dist/types/mixins/OxyServices.followGraph.d.ts +13 -0
  30. package/dist/types/session/accountProjection.d.ts +20 -4
  31. package/dist/types/utils/errorUtils.d.ts +67 -0
  32. package/package.json +7 -6
  33. package/src/HttpService.ts +29 -22
  34. package/src/__tests__/parseHttpErrorBody.test.ts +116 -0
  35. package/src/__tests__/serverValueImportsDeclared.test.ts +7 -0
  36. package/src/i18n/__tests__/accountCategoryLabels.test.ts +62 -0
  37. package/src/i18n/__tests__/accountRoleLabels.test.ts +54 -0
  38. package/src/i18n/__tests__/reputationCategoryLabels.test.ts +56 -0
  39. package/src/i18n/__tests__/trustTierLabels.test.ts +47 -0
  40. package/src/i18n/accountCategoryLabels.ts +44 -0
  41. package/src/i18n/accountRoleLabels.ts +26 -0
  42. package/src/i18n/reputationCategoryLabels.ts +20 -0
  43. package/src/i18n/trustTierLabels.ts +18 -0
  44. package/src/index.ts +13 -6
  45. package/src/mixins/OxyServices.followGraph.ts +24 -0
  46. package/src/mixins/__tests__/followGraph.test.ts +19 -0
  47. package/src/session/__tests__/accountProjection.test.ts +98 -0
  48. package/src/session/accountProjection.ts +37 -6
  49. package/src/utils/errorUtils.ts +116 -5
@@ -450,32 +450,37 @@ class HttpService {
450
450
  // Failed to parse error body — not a CSRF error
451
451
  }
452
452
  }
453
- // Try to parse error response (handle empty/malformed JSON)
454
- let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
455
- const contentType = response.headers.get('content-type');
456
- if (contentType && contentType.includes('application/json')) {
453
+ // Read the error body (may be absent, non-JSON, empty or malformed).
454
+ // Anything unreadable leaves `errorBody` undefined and degrades to the
455
+ // status-based message — an error path that throws its own error is
456
+ // worse than the error it was reporting.
457
+ let errorBody;
458
+ const errorContentType = response.headers.get('content-type');
459
+ if (errorContentType?.includes('application/json')) {
457
460
  try {
458
- const errorData = await response.json();
459
- // Accept either structured error field from API responses.
460
- if (errorData?.message) {
461
- errorMessage = errorData.message;
462
- }
463
- else if (errorData?.error_description) {
464
- // RFC 6749 §5.2 / RFC 6750 §3 — OAuth endpoints surface human text here.
465
- errorMessage = errorData.error_description;
466
- }
467
- else if (errorData?.error) {
468
- errorMessage = errorData.error;
469
- }
461
+ errorBody = await response.json();
470
462
  }
471
463
  catch (parseError) {
472
464
  // Malformed JSON or empty response - use status text
473
465
  this.logger.warn('Failed to parse error response JSON:', parseError);
474
466
  }
475
467
  }
476
- const error = new Error(errorMessage);
468
+ // `parseHttpErrorBody` handles every envelope in use, including the
469
+ // nested `{ error: { code, message } }` shape — assigning that nested
470
+ // OBJECT as the message is what produced `"[object Object]"`.
471
+ const parsed = (0, errorUtils_1.parseHttpErrorBody)(errorBody);
472
+ const error = new Error(parsed.message ?? `HTTP ${response.status}: ${response.statusText}`);
477
473
  error.status = response.status;
478
- error.response = { status: response.status, statusText: response.statusText };
474
+ error.response = { status: response.status, statusText: response.statusText, data: errorBody };
475
+ // Only set `code`/`details` when the server actually sent them.
476
+ // Assigning `undefined` would still create the property, which changes
477
+ // how `handleHttpError` classifies the error downstream.
478
+ if (parsed.code !== undefined) {
479
+ error.code = parsed.code;
480
+ }
481
+ if (parsed.details !== undefined) {
482
+ error.details = parsed.details;
483
+ }
479
484
  throw error;
480
485
  }
481
486
  // Handle different response types (optimized - read response once)
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.EN_ACCOUNT_CATEGORY_LABELS = void 0;
7
+ exports.accountCategoryLabel = accountCategoryLabel;
8
+ const en_US_json_1 = __importDefault(require("./locales/en-US.json"));
9
+ const index_1 = require("./index");
10
+ /**
11
+ * Every account category's English name, keyed by its stable id.
12
+ *
13
+ * **The annotation is the point.** The vocabulary lives in `@oxyhq/contracts`
14
+ * and the names live in `locales/en-US.json`, so they are two lists that must
15
+ * agree and nothing but a type can make them. Declaring the JSON node as a
16
+ * TOTAL `Record<AccountCategoryId, string>` turns "somebody added a category at
17
+ * Oxy and nobody wrote its English" into a `TS2741` naming the missing id, at
18
+ * build time, instead of a picker row that paints `accounts.accountCategory.<id>`
19
+ * at a user trying to choose one.
20
+ *
21
+ * That failure is not hypothetical. The screen previously wrote `t(key) || id`,
22
+ * whose author believed an unnamed id would degrade to its raw slug. It cannot:
23
+ * {@link translate} echoes the KEY when it resolves nothing, and a non-empty
24
+ * string is never falsy, so the `|| id` arm was unreachable and the output was
25
+ * the dotted key. A runtime fallback that cannot run is worse than none,
26
+ * because it reads as protection.
27
+ *
28
+ * Totality is over `ACCOUNT_CATEGORY_IDS`, which RETAINS withdrawn ids, so an
29
+ * account still carrying a retired category keeps rendering its name while no
30
+ * picker offers it again. Retired and unknown are different cases: only an id
31
+ * outside the union is unnameable, which is why this is keyed by
32
+ * `AccountCategoryId` and not by `string`.
33
+ */
34
+ /**
35
+ * Module-scoped, NOT re-exported from the package index: the annotation is the
36
+ * whole job, and it does that job without being public API. It carries no
37
+ * `Object.freeze` and no `Readonly<>` for the same reason — those existed only
38
+ * to make an exported reference safe from a consumer's stray write, and there
39
+ * is no such consumer. Exported from the MODULE so its own test can name it.
40
+ */
41
+ exports.EN_ACCOUNT_CATEGORY_LABELS = en_US_json_1.default.accounts.accountCategory;
42
+ function accountCategoryLabel(locale, id) {
43
+ return (0, index_1.translate)(locale, `accounts.accountCategory.${id}`);
44
+ }
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.EN_ACCOUNT_ROLE_LABELS = void 0;
7
+ exports.accountRoleLabel = accountRoleLabel;
8
+ const en_US_json_1 = __importDefault(require("./locales/en-US.json"));
9
+ const index_1 = require("./index");
10
+ /**
11
+ * Every account member role's English name, keyed by its stable id.
12
+ *
13
+ * Totality is over the closed `AccountRole` union so a new role without an
14
+ * English label is a build error, not a members row that paints
15
+ * `accounts.roles.<role>.label`.
16
+ */
17
+ exports.EN_ACCOUNT_ROLE_LABELS = {
18
+ owner: en_US_json_1.default.accounts.roles.owner.label,
19
+ admin: en_US_json_1.default.accounts.roles.admin.label,
20
+ editor: en_US_json_1.default.accounts.roles.editor.label,
21
+ developer: en_US_json_1.default.accounts.roles.developer.label,
22
+ billing: en_US_json_1.default.accounts.roles.billing.label,
23
+ viewer: en_US_json_1.default.accounts.roles.viewer.label,
24
+ };
25
+ function accountRoleLabel(locale, role) {
26
+ return (0, index_1.translate)(locale, `accounts.roles.${role}.label`);
27
+ }
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.EN_REPUTATION_CATEGORY_LABELS = void 0;
7
+ exports.reputationCategoryLabel = reputationCategoryLabel;
8
+ const en_US_json_1 = __importDefault(require("./locales/en-US.json"));
9
+ const index_1 = require("./index");
10
+ /**
11
+ * Every reputation rule category's English name, keyed by its stable id.
12
+ *
13
+ * Totality is over `REPUTATION_CATEGORIES` from `@oxyhq/contracts` so a new
14
+ * category added server-side without an English label is a build error, not a
15
+ * Trust Rules section title that paints `trust.rules.categories.<id>`.
16
+ */
17
+ exports.EN_REPUTATION_CATEGORY_LABELS = en_US_json_1.default.trust.rules.categories;
18
+ function reputationCategoryLabel(locale, id) {
19
+ return (0, index_1.translate)(locale, `trust.rules.categories.${id}`);
20
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.EN_TRUST_TIER_LABELS = void 0;
7
+ exports.trustTierLabel = trustTierLabel;
8
+ const en_US_json_1 = __importDefault(require("./locales/en-US.json"));
9
+ const index_1 = require("./index");
10
+ /**
11
+ * Every trust tier's English name, keyed by its stable id.
12
+ *
13
+ * Totality is over `TRUST_TIERS` from `@oxyhq/contracts` so a new tier without
14
+ * an English label is a build error, not a chip that paints `trust.tiers.<id>`.
15
+ */
16
+ exports.EN_TRUST_TIER_LABELS = en_US_json_1.default.trust.tiers;
17
+ function trustTierLabel(locale, tier) {
18
+ return (0, index_1.translate)(locale, `trust.tiers.${tier}`);
19
+ }
package/dist/cjs/index.js CHANGED
@@ -20,9 +20,9 @@
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
21
  exports.AEAD_KEY_LENGTH = exports.decryptAead = exports.encryptAead = exports.hkdfSha256 = exports.RecoveryPhraseService = exports.SignatureService = exports.updateIdentityMarker = exports.readIdentityMarker = exports.IdentityUnavailableError = exports.IdentityPersistError = exports.IdentityAlreadyExistsError = exports.KeyManager = exports.sessionsArraysEqual = exports.normalizeAndSortSessions = exports.mergeSessions = exports.authenticatedApiCall = exports.withAuthErrorHandling = exports.isAuthenticationError = exports.ensureValidToken = exports.AuthenticationFailedError = exports.SessionSyncRequiredError = exports.verifyPublicCardAttestation = exports.parseAttestPayload = exports.parseIdPayload = exports.buildUserDid = exports.kindAcceptsAccountCategories = exports.isSelectableAccountCategoryId = exports.SELECTABLE_ACCOUNT_CATEGORY_IDS = exports.MAX_ACCOUNT_CATEGORIES = exports.ACCOUNT_CATEGORY_IDS = exports.normalizeProfileLinks = exports.getNormalizedUserHandle = exports.getCanonicalUserHandle = exports.normalizeUserIdentityOrNull = exports.normalizeUserIdentity = exports.getNormalizedUserId = exports.OxyAppDataIdentifierError = exports.commonsDeliveryPlatform = exports.pushTargetsFromDelivery = exports.selectCommonsDelivery = exports.parseCommonsApprovalExpiresAt = exports.getCommonsApprovalBlockingReason = exports.ServiceCredentialMismatchError = exports.oxyClient = exports.OXY_CLOUD_URL = exports.ServiceAssetMetadataError = exports.OxyAuthenticationTimeoutError = exports.OxyAuthenticationError = exports.AssetUrlResolutionError = exports.OxyServices = void 0;
22
22
  exports.calculateBackoffInterval = exports.createCircuitBreakerState = exports.DEFAULT_CIRCUIT_BREAKER_CONFIG = exports.isRetryableError = exports.isNetworkError = exports.isServerError = exports.isRateLimitError = exports.isNotFoundError = exports.isForbiddenError = exports.isUnauthorizedError = exports.isAlreadyRegisteredError = exports.getErrorMessage = exports.getErrorStatus = exports.HttpStatus = exports.getSystemColorScheme = exports.systemPrefersDarkMode = exports.getOppositeTheme = exports.normalizeColorScheme = exports.normalizeTheme = exports.getContrastTextColor = exports.isLightColor = exports.withOpacity = exports.rgbToHex = exports.hexToRgb = exports.lightenColor = exports.darkenColor = exports.isWebBrowser = exports.isAndroid = exports.isIOS = exports.isNative = exports.isWeb = exports.setPlatformOS = exports.getPlatformOS = exports.getPrimaryLanguage = exports.getUserLanguages = exports.isRTLLocale = exports.getNativeLanguageName = exports.getLanguageName = exports.getLanguageMetadata = exports.isSupportedLocale = exports.normalizeLocale = exports.getBaseLanguage = exports.FALLBACK_LOCALE = exports.SUPPORTED_LANGUAGES = exports.TopicSource = exports.TopicType = exports.SECURITY_EVENT_SEVERITY_MAP = exports.DeviceManager = exports.deriveSharedSecret = exports.AEAD_NONCE_LENGTH = void 0;
23
- exports.resetLoggerConfig = exports.getLoggerConfig = exports.configureLogger = exports.createLogger = exports.logger = exports.normalizeMultilineText = exports.normalizeInlineText = exports.validateAndSanitizeUserInput = exports.isValidObjectId = exports.sanitizeHTML = exports.sanitizeString = exports.isValidFileType = exports.isValidFileSize = exports.isValidDate = exports.isValidURL = exports.isValidUUID = exports.isValidObject = exports.isValidArray = exports.isRequiredBoolean = exports.isRequiredNumber = exports.isRequiredString = exports.DISPLAY_NAME_UNFLANKED_SEPARATOR_SOURCE = exports.DISPLAY_NAME_ORPHANED_MARK_SOURCE = exports.DISPLAY_NAME_DISALLOWED_SOURCE = exports.DISPLAY_NAME_ALLOWED_SCRIPTS = exports.isValidDisplayName = exports.isValidPassword = exports.isValidUsername = exports.isValidEmail = exports.DISPLAY_NAME_INVALID_MESSAGE = exports.MAX_DISPLAY_NAME_LENGTH = exports.PASSWORD_REGEX = exports.USERNAME_REGEX = exports.EMAIL_REGEX = exports.retryAsync = exports.validateRequiredFields = exports.handleHttpError = exports.createApiError = exports.ErrorCodes = exports.safeJsonParse = exports.buildPaginationParams = exports.buildUrl = exports.buildSearchParams = exports.buildQueryParams = exports.translate = exports.withRetry = exports.delay = exports.shouldAllowRequest = exports.recordSuccess = exports.recordFailure = void 0;
24
- exports.createWebIdentityPinStore = exports.AUTH_STATE_STORAGE_KEY = exports.createMemoryAuthStateStore = exports.createNativeAuthStateStore = exports.createWebAuthStateStore = exports.createAccountDialogController = exports.AccountDialogController = exports.switchableAccountIds = exports.projectSwitchableAccounts = exports.isSwitchTargetAccount = exports.accountIdsOf = exports.activeUserOf = exports.activeSessionIdOf = exports.deviceStateToClientSessions = exports.createSessionClient = exports.createSessionClientHost = exports.SessionClient = exports.isAllowedDeviceJoinOrigin = exports.isOfficialWebOrigin = exports.isLoopbackOrigin = exports.consumeOAuthReturnPath = exports.persistOAuthReturnPath = exports.clearOAuthHandshake = exports.readOAuthHandshake = exports.persistOAuthHandshake = exports.canonicalizeOAuthRedirectUri = exports.normalizeOAuthRedirectUri = exports.OXY_OAUTH_RETURN_PATH_STORAGE_KEY = exports.OXY_OAUTH_REDIRECT_URI_STORAGE_KEY = exports.OXY_OAUTH_CODE_VERIFIER_STORAGE_KEY = exports.OXY_OAUTH_STATE_STORAGE_KEY = exports.OXY_AUTHORIZE_URL = exports.DEFAULT_OAUTH_SCOPE = exports.generatePkcePair = exports.generateOAuthState = exports.computeCodeChallenge = exports.buildOAuthAuthorizeUrl = exports.runColdBoot = exports.isOxyRpOrigin = exports.CENTRAL_IDP_APEX = exports.registrableApex = exports.getAccountColor = exports.formatPublicKeyHandle = exports.getAccountFallbackHandle = exports.getAccountDisplayName = exports.createQuickAccount = exports.buildAccountsArray = exports.updateAvatarVisibility = exports.isDev = exports.consoleSink = void 0;
25
- exports.packageInfo = exports.runSessionColdBoot = exports.TOKEN_REFRESH_LEAD_MS = exports.startTokenRefreshScheduler = exports.installAuthRefreshHandler = exports.createAuthRefreshHandler = exports.refreshDeviceSecretArm = exports.refreshPersistedSession = exports.AccountNotOnDeviceError = exports.establishIdentitySession = exports.resolveIdentityPin = exports.IDENTITY_PIN_STORAGE_KEY = exports.identityPinMatches = exports.createMemoryIdentityPinStore = exports.createNativeIdentityPinStore = void 0;
23
+ exports.normalizeInlineText = exports.validateAndSanitizeUserInput = exports.isValidObjectId = exports.sanitizeHTML = exports.sanitizeString = exports.isValidFileType = exports.isValidFileSize = exports.isValidDate = exports.isValidURL = exports.isValidUUID = exports.isValidObject = exports.isValidArray = exports.isRequiredBoolean = exports.isRequiredNumber = exports.isRequiredString = exports.DISPLAY_NAME_UNFLANKED_SEPARATOR_SOURCE = exports.DISPLAY_NAME_ORPHANED_MARK_SOURCE = exports.DISPLAY_NAME_DISALLOWED_SOURCE = exports.DISPLAY_NAME_ALLOWED_SCRIPTS = exports.isValidDisplayName = exports.isValidPassword = exports.isValidUsername = exports.isValidEmail = exports.DISPLAY_NAME_INVALID_MESSAGE = exports.MAX_DISPLAY_NAME_LENGTH = exports.PASSWORD_REGEX = exports.USERNAME_REGEX = exports.EMAIL_REGEX = exports.retryAsync = exports.validateRequiredFields = exports.parseHttpErrorBody = exports.isHttpRequestError = exports.handleHttpError = exports.createApiError = exports.ErrorCodes = exports.safeJsonParse = exports.buildPaginationParams = exports.buildUrl = exports.buildSearchParams = exports.buildQueryParams = exports.trustTierLabel = exports.reputationCategoryLabel = exports.accountRoleLabel = exports.accountCategoryLabel = exports.translate = exports.withRetry = exports.delay = exports.shouldAllowRequest = exports.recordSuccess = exports.recordFailure = void 0;
24
+ exports.switchableAccountIds = exports.projectSwitchableAccounts = exports.canSwitchIntoAccount = exports.isSwitchTargetAccount = exports.accountIdsOf = exports.activeUserOf = exports.activeSessionIdOf = exports.deviceStateToClientSessions = exports.createSessionClient = exports.createSessionClientHost = exports.SessionClient = exports.isAllowedDeviceJoinOrigin = exports.isOfficialWebOrigin = exports.isLoopbackOrigin = exports.consumeOAuthReturnPath = exports.persistOAuthReturnPath = exports.clearOAuthHandshake = exports.readOAuthHandshake = exports.persistOAuthHandshake = exports.canonicalizeOAuthRedirectUri = exports.normalizeOAuthRedirectUri = exports.OXY_OAUTH_RETURN_PATH_STORAGE_KEY = exports.OXY_OAUTH_REDIRECT_URI_STORAGE_KEY = exports.OXY_OAUTH_CODE_VERIFIER_STORAGE_KEY = exports.OXY_OAUTH_STATE_STORAGE_KEY = exports.OXY_AUTHORIZE_URL = exports.DEFAULT_OAUTH_SCOPE = exports.generatePkcePair = exports.generateOAuthState = exports.computeCodeChallenge = exports.buildOAuthAuthorizeUrl = exports.runColdBoot = exports.isOxyRpOrigin = exports.CENTRAL_IDP_APEX = exports.registrableApex = exports.getAccountColor = exports.formatPublicKeyHandle = exports.getAccountFallbackHandle = exports.getAccountDisplayName = exports.createQuickAccount = exports.buildAccountsArray = exports.updateAvatarVisibility = exports.isDev = exports.consoleSink = exports.resetLoggerConfig = exports.getLoggerConfig = exports.configureLogger = exports.createLogger = exports.logger = exports.normalizeMultilineText = void 0;
25
+ exports.packageInfo = exports.runSessionColdBoot = exports.TOKEN_REFRESH_LEAD_MS = exports.startTokenRefreshScheduler = exports.installAuthRefreshHandler = exports.createAuthRefreshHandler = exports.refreshDeviceSecretArm = exports.refreshPersistedSession = exports.AccountNotOnDeviceError = exports.establishIdentitySession = exports.resolveIdentityPin = exports.IDENTITY_PIN_STORAGE_KEY = exports.identityPinMatches = exports.createMemoryIdentityPinStore = exports.createNativeIdentityPinStore = exports.createWebIdentityPinStore = exports.AUTH_STATE_STORAGE_KEY = exports.createMemoryAuthStateStore = exports.createNativeAuthStateStore = exports.createWebAuthStateStore = exports.createAccountDialogController = exports.AccountDialogController = void 0;
26
26
  // Ensure crypto polyfills are loaded before anything else
27
27
  require("./crypto/polyfill");
28
28
  // ---------------------------------------------------------------------------
@@ -223,6 +223,14 @@ Object.defineProperty(exports, "withRetry", { enumerable: true, get: function ()
223
223
  // ---------------------------------------------------------------------------
224
224
  var i18n_1 = require("./i18n");
225
225
  Object.defineProperty(exports, "translate", { enumerable: true, get: function () { return i18n_1.translate; } });
226
+ var accountCategoryLabels_1 = require("./i18n/accountCategoryLabels");
227
+ Object.defineProperty(exports, "accountCategoryLabel", { enumerable: true, get: function () { return accountCategoryLabels_1.accountCategoryLabel; } });
228
+ var accountRoleLabels_1 = require("./i18n/accountRoleLabels");
229
+ Object.defineProperty(exports, "accountRoleLabel", { enumerable: true, get: function () { return accountRoleLabels_1.accountRoleLabel; } });
230
+ var reputationCategoryLabels_1 = require("./i18n/reputationCategoryLabels");
231
+ Object.defineProperty(exports, "reputationCategoryLabel", { enumerable: true, get: function () { return reputationCategoryLabels_1.reputationCategoryLabel; } });
232
+ var trustTierLabels_1 = require("./i18n/trustTierLabels");
233
+ Object.defineProperty(exports, "trustTierLabel", { enumerable: true, get: function () { return trustTierLabels_1.trustTierLabel; } });
226
234
  // ---------------------------------------------------------------------------
227
235
  // API request / URL helpers
228
236
  // ---------------------------------------------------------------------------
@@ -236,6 +244,8 @@ var errorUtils_2 = require("./utils/errorUtils");
236
244
  Object.defineProperty(exports, "ErrorCodes", { enumerable: true, get: function () { return errorUtils_2.ErrorCodes; } });
237
245
  Object.defineProperty(exports, "createApiError", { enumerable: true, get: function () { return errorUtils_2.createApiError; } });
238
246
  Object.defineProperty(exports, "handleHttpError", { enumerable: true, get: function () { return errorUtils_2.handleHttpError; } });
247
+ Object.defineProperty(exports, "isHttpRequestError", { enumerable: true, get: function () { return errorUtils_2.isHttpRequestError; } });
248
+ Object.defineProperty(exports, "parseHttpErrorBody", { enumerable: true, get: function () { return errorUtils_2.parseHttpErrorBody; } });
239
249
  Object.defineProperty(exports, "validateRequiredFields", { enumerable: true, get: function () { return errorUtils_2.validateRequiredFields; } });
240
250
  var asyncUtils_1 = require("./utils/asyncUtils");
241
251
  Object.defineProperty(exports, "retryAsync", { enumerable: true, get: function () { return asyncUtils_1.retryAsync; } });
@@ -370,14 +380,14 @@ Object.defineProperty(exports, "accountIdsOf", { enumerable: true, get: function
370
380
  // chooser: device sign-ins ∪ account graph, deduped by accountId). Pure +
371
381
  // I/O-free — the caller hydrates profiles via `getUsersByIds`. Shared by
372
382
  // `@oxyhq/services` and auth.oxy.so so the list can't diverge.
373
- // `isSwitchTargetAccount` is the switcher's own question ("can I become this
374
- // account?"), exported so a surface that renders `AccountNode`s rather than the
375
- // projection the Console's workspace switcher, the accounts app's
376
- // managed-accounts rows asks the SAME question instead of testing a kind
377
- // literal. It is NOT `isActAsEligibleKind`: that one is false for `personal`
378
- // too, so gating a switcher on it alone empties the list.
383
+ // `isSwitchTargetAccount` is the structural half ("is this kind switchable at
384
+ // all?"); `canSwitchIntoAccount` adds the caller's `account:act_as` permission.
385
+ // Both are exported so surfaces that render `AccountNode`s rather than the
386
+ // projection — the Console workspace switcher, managed-accounts rows ask the
387
+ // SAME questions instead of testing a kind literal.
379
388
  var accountProjection_1 = require("./session/accountProjection");
380
389
  Object.defineProperty(exports, "isSwitchTargetAccount", { enumerable: true, get: function () { return accountProjection_1.isSwitchTargetAccount; } });
390
+ Object.defineProperty(exports, "canSwitchIntoAccount", { enumerable: true, get: function () { return accountProjection_1.canSwitchIntoAccount; } });
381
391
  Object.defineProperty(exports, "projectSwitchableAccounts", { enumerable: true, get: function () { return accountProjection_1.projectSwitchableAccounts; } });
382
392
  Object.defineProperty(exports, "switchableAccountIds", { enumerable: true, get: function () { return accountProjection_1.switchableAccountIds; } });
383
393
  // Headless controller for the unified account dialog. Framework-agnostic
@@ -159,6 +159,23 @@ function OxyServicesFollowGraphMixin(Base) {
159
159
  throw this.handleError(error);
160
160
  }
161
161
  }
162
+ /**
163
+ * Release a namespace the calling application holds, when nothing is
164
+ registered inside it yet.
165
+ *
166
+ * Idempotent when the namespace is already unowned (`released: false`).
167
+ * Exists because claims are first-come and registration runs on boot — a
168
+ * development build with the wrong client id can bind a name permanently
169
+ * unless the holder can give it back.
170
+ */
171
+ async releaseFollowNamespace(namespace) {
172
+ try {
173
+ return await this.makeRequest('DELETE', `/v2/follow-targets/namespaces/${encodeURIComponent(namespace)}`, undefined, { cache: false });
174
+ }
175
+ catch (error) {
176
+ throw this.handleError(error);
177
+ }
178
+ }
162
179
  /**
163
180
  * Declare what following a kind of thing MEANS: the verb clients render,
164
181
  * whether reverse lookups are public, whether it federates.
@@ -19,6 +19,7 @@
19
19
  */
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
21
  exports.isSwitchTargetAccount = isSwitchTargetAccount;
22
+ exports.canSwitchIntoAccount = canSwitchIntoAccount;
22
23
  exports.projectSwitchableAccounts = projectSwitchableAccounts;
23
24
  exports.switchableAccountIds = switchableAccountIds;
24
25
  const contracts_1 = require("@oxyhq/contracts");
@@ -53,6 +54,30 @@ const userHandle_1 = require("../utils/userHandle");
53
54
  function isSwitchTargetAccount(node) {
54
55
  return node.relationship === 'self' || (0, contracts_1.isActAsEligibleKind)(node.kind);
55
56
  }
57
+ /**
58
+ * Whether the caller may switch INTO this account — the server-side
59
+ * `account:act_as` gate plus the structural {@link isSwitchTargetAccount} rule.
60
+ *
61
+ * `relationship: 'self'` always passes (returning to the caller's own personal
62
+ * account). Every other ground requires a switch-eligible kind AND
63
+ * `account:act_as` in the resolved membership permissions. When permissions are
64
+ * absent but the relationship is `owner`, the owner baseline is assumed — the
65
+ * API always resolves effective permissions for owned accounts, but test
66
+ * fixtures and stale rows may omit the membership blob.
67
+ */
68
+ function canSwitchIntoAccount(node) {
69
+ if (node.relationship === 'self') {
70
+ return true;
71
+ }
72
+ if (!isSwitchTargetAccount(node)) {
73
+ return false;
74
+ }
75
+ const permissions = node.callerMembership?.permissions;
76
+ if (permissions) {
77
+ return permissions.includes('account:act_as');
78
+ }
79
+ return node.relationship === 'owner';
80
+ }
56
81
  /**
57
82
  * Pure union of device sign-ins and account-graph nodes into the flat
58
83
  * {@link SwitchableAccount}[] every switcher renders.
@@ -62,9 +87,9 @@ function isSwitchTargetAccount(node) {
62
87
  * and a graph node is deduped into ONE device row enriched with the graph
63
88
  * metadata (relationship / kind / parent / membership).
64
89
  *
65
- * Graph nodes that are not switch targets — a `channel`, which nobody may act
66
- * as — are omitted. {@link isSwitchTargetAccount} is the rule; see the filter
67
- * below.
90
+ * Graph nodes the caller cannot switch into — a `channel`, or a managed account
91
+ * whose membership lacks `account:act_as` — are omitted.
92
+ * {@link canSwitchIntoAccount} is the rule; see the filter below.
68
93
  */
69
94
  function projectSwitchableAccounts(input) {
70
95
  const { state, graph, profilesById, activeUser, locale, resolveAvatarUrl } = input;
@@ -144,7 +169,7 @@ function projectSwitchableAccounts(input) {
144
169
  // An account already on the device skipped this check via the branch above,
145
170
  // and correctly: whatever its kind, the caller is signed into it, so
146
171
  // switching is a local activation that asks the server for nothing.
147
- if (!isSwitchTargetAccount(node)) {
172
+ if (!canSwitchIntoAccount(node)) {
148
173
  continue;
149
174
  }
150
175
  remember(toRow(node.account, {
@@ -166,7 +191,7 @@ function projectSwitchableAccounts(input) {
166
191
  * document, but including their ids lets the caller pass one id set and lets the
167
192
  * projection prefer freshly-fetched profiles uniformly.
168
193
  *
169
- * Applies the SAME {@link isSwitchTargetAccount} filter as
194
+ * Applies the SAME {@link canSwitchIntoAccount} filter as
170
195
  * {@link projectSwitchableAccounts} to graph nodes, so this never fetches a
171
196
  * profile for a row the projection will drop — and, just as importantly, never
172
197
  * SKIPS one the projection will keep, which would leave that row unrendered
@@ -180,7 +205,7 @@ function switchableAccountIds(state, graph) {
180
205
  }
181
206
  }
182
207
  for (const node of graph) {
183
- if (node.accountId && isSwitchTargetAccount(node)) {
208
+ if (node.accountId && canSwitchIntoAccount(node)) {
184
209
  ids.add(node.accountId);
185
210
  }
186
211
  }
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ErrorCodes = void 0;
4
+ exports.isHttpRequestError = isHttpRequestError;
5
+ exports.parseHttpErrorBody = parseHttpErrorBody;
4
6
  exports.createApiError = createApiError;
5
7
  exports.handleHttpError = handleHttpError;
6
8
  exports.getErrorCodeFromStatus = getErrorCodeFromStatus;
@@ -37,6 +39,63 @@ exports.ErrorCodes = {
37
39
  NETWORK_ERROR: 'NETWORK_ERROR',
38
40
  CONNECTION_FAILED: 'CONNECTION_FAILED'
39
41
  };
42
+ /**
43
+ * Narrow a caught value to {@link HttpRequestError}.
44
+ *
45
+ * Returns `false` for a plain {@link ApiError} object (those are objects, not
46
+ * `Error`s) — run an arbitrary thrown value through {@link handleHttpError}
47
+ * first if you need one normalized.
48
+ */
49
+ function isHttpRequestError(value) {
50
+ if (!(value instanceof Error)) {
51
+ return false;
52
+ }
53
+ return typeof value.status === 'number';
54
+ }
55
+ const isPlainRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
56
+ const nonEmptyString = (value) => typeof value === 'string' && value.trim().length > 0 ? value : undefined;
57
+ /**
58
+ * Extract `message` / `code` / `details` from a parsed HTTP error response body.
59
+ *
60
+ * Handles every error envelope in use across the Oxy ecosystem:
61
+ *
62
+ * - `{ error: { code, message, details? } }` — nested envelope (CrowdSource and
63
+ * other Oxy services). Never stringify the nested object: `new Error(obj)`
64
+ * yields the literal message `"[object Object]"`.
65
+ * - `{ error: '<CODE>', message, details? }` — oxy-api's canonical shape
66
+ * (`ApiError.toJSON`), where the top-level `error` field IS the code.
67
+ * - `{ error: '<CODE>', error_description }` — RFC 6749 §5.2 / RFC 6750 §3, the
68
+ * OAuth token and userinfo endpoints. `error_description` is the human text
69
+ * and `error` is the machine code, so both survive.
70
+ * - `{ message, code }` — e.g. the API's CSRF rejections.
71
+ * - `{ error: '<human message>' }` — legacy hand-rolled routes. With no sibling
72
+ * `message`/`error_description` the string is the message, not a code: a bare
73
+ * `error` string is not machine-readable enough to promote to `code`.
74
+ *
75
+ * Anything else — a non-object body (`null`, `[]`, `"str"`, `42`), or an object
76
+ * carrying none of these fields — yields an empty result, leaving the caller on
77
+ * its status-based fallback message. Total function: never throws.
78
+ */
79
+ function parseHttpErrorBody(body) {
80
+ if (!isPlainRecord(body)) {
81
+ return {};
82
+ }
83
+ const nested = isPlainRecord(body.error) ? body.error : undefined;
84
+ const errorString = nonEmptyString(body.error);
85
+ // A sibling that proves the top-level `error` is a CODE rather than prose.
86
+ const siblingMessage = nonEmptyString(body.message) ?? nonEmptyString(body.error_description);
87
+ return {
88
+ message: siblingMessage ?? (nested ? nonEmptyString(nested.message) : errorString),
89
+ code: (nested ? nonEmptyString(nested.code) : undefined) ??
90
+ nonEmptyString(body.code) ??
91
+ (siblingMessage ? errorString : undefined),
92
+ details: isPlainRecord(body.details)
93
+ ? body.details
94
+ : nested && isPlainRecord(nested.details)
95
+ ? nested.details
96
+ : undefined,
97
+ };
98
+ }
40
99
  /**
41
100
  * Create a standardized API error
42
101
  */
@@ -81,7 +140,12 @@ function handleHttpError(error) {
81
140
  const fetchError = error;
82
141
  const status = fetchError.response?.status || fetchError.status;
83
142
  if (status) {
84
- return createApiError(fetchError.message || `HTTP ${status} error`, getErrorCodeFromStatus(status), status);
143
+ // `details` is carried through when present: a body may ship structured
144
+ // detail without a machine-readable `code` (which is what routes the
145
+ // error to the already-an-ApiError branch above), and dropping it here
146
+ // would make it unreachable to every caller that rethrows via
147
+ // `OxyServices.handleError`.
148
+ return createApiError(fetchError.message || `HTTP ${status} error`, getErrorCodeFromStatus(status), status, isPlainRecord(fetchError.details) ? fetchError.details : undefined);
85
149
  }
86
150
  }
87
151
  // Handle standard errors