ExpoClient.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. var desc = Object.getOwnPropertyDescriptor(m, k);
  5. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6. desc = { enumerable: true, get: function() { return m[k]; } };
  7. }
  8. Object.defineProperty(o, k2, desc);
  9. }) : (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. o[k2] = m[k];
  12. }));
  13. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15. }) : function(o, v) {
  16. o["default"] = v;
  17. });
  18. var __importStar = (this && this.__importStar) || function (mod) {
  19. if (mod && mod.__esModule) return mod;
  20. var result = {};
  21. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  22. __setModuleDefault(result, mod);
  23. return result;
  24. };
  25. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  26. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  27. return new (P || (P = Promise))(function (resolve, reject) {
  28. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  29. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  30. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  31. step((generator = generator.apply(thisArg, _arguments || [])).next());
  32. });
  33. };
  34. var __importDefault = (this && this.__importDefault) || function (mod) {
  35. return (mod && mod.__esModule) ? mod : { "default": mod };
  36. };
  37. Object.defineProperty(exports, "__esModule", { value: true });
  38. exports.Expo = void 0;
  39. /**
  40. * expo-server-sdk
  41. *
  42. * Use this if you are running Node on your server backend when you are working with Expo
  43. * Application Services
  44. * https://expo.dev
  45. */
  46. const assert_1 = __importDefault(require("assert"));
  47. const node_fetch_1 = __importStar(require("node-fetch"));
  48. const promise_limit_1 = __importDefault(require("promise-limit"));
  49. const promise_retry_1 = __importDefault(require("promise-retry"));
  50. const zlib_1 = __importDefault(require("zlib"));
  51. const ExpoClientValues_1 = require("./ExpoClientValues");
  52. const BASE_URL = 'https://exp.host';
  53. const BASE_API_URL = `${BASE_URL}/--/api/v2`;
  54. /**
  55. * The max number of push notifications to be sent at once. Since we can't automatically upgrade
  56. * everyone using this library, we should strongly try not to decrease it.
  57. */
  58. const PUSH_NOTIFICATION_CHUNK_LIMIT = 100;
  59. /**
  60. * The max number of push notification receipts to request at once.
  61. */
  62. const PUSH_NOTIFICATION_RECEIPT_CHUNK_LIMIT = 300;
  63. /**
  64. * The default max number of concurrent HTTP requests to send at once and spread out the load,
  65. * increasing the reliability of notification delivery.
  66. */
  67. const DEFAULT_CONCURRENT_REQUEST_LIMIT = 6;
  68. class Expo {
  69. constructor(options = {}) {
  70. this.httpAgent = options.httpAgent;
  71. this.limitConcurrentRequests = (0, promise_limit_1.default)(options.maxConcurrentRequests != null
  72. ? options.maxConcurrentRequests
  73. : DEFAULT_CONCURRENT_REQUEST_LIMIT);
  74. this.accessToken = options.accessToken;
  75. this.useFcmV1 = options.useFcmV1;
  76. }
  77. /**
  78. * Returns `true` if the token is an Expo push token
  79. */
  80. static isExpoPushToken(token) {
  81. return (typeof token === 'string' &&
  82. (((token.startsWith('ExponentPushToken[') || token.startsWith('ExpoPushToken[')) &&
  83. token.endsWith(']')) ||
  84. /^[a-z\d]{8}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{12}$/i.test(token)));
  85. }
  86. /**
  87. * Sends the given messages to their recipients via push notifications and returns an array of
  88. * push tickets. Each ticket corresponds to the message at its respective index (the nth receipt
  89. * is for the nth message) and contains a receipt ID. Later, after Expo attempts to deliver the
  90. * messages to the underlying push notification services, the receipts with those IDs will be
  91. * available for a period of time (approximately a day).
  92. *
  93. * There is a limit on the number of push notifications you can send at once. Use
  94. * `chunkPushNotifications` to divide an array of push notification messages into appropriately
  95. * sized chunks.
  96. */
  97. sendPushNotificationsAsync(messages) {
  98. return __awaiter(this, void 0, void 0, function* () {
  99. const url = new URL(`${BASE_API_URL}/push/send`);
  100. if (typeof this.useFcmV1 === 'boolean') {
  101. url.searchParams.append('useFcmV1', String(this.useFcmV1));
  102. }
  103. const actualMessagesCount = Expo._getActualMessageCount(messages);
  104. const data = yield this.limitConcurrentRequests(() => __awaiter(this, void 0, void 0, function* () {
  105. return yield (0, promise_retry_1.default)((retry) => __awaiter(this, void 0, void 0, function* () {
  106. try {
  107. return yield this.requestAsync(url.toString(), {
  108. httpMethod: 'post',
  109. body: messages,
  110. shouldCompress(body) {
  111. return body.length > 1024;
  112. },
  113. });
  114. }
  115. catch (e) {
  116. // if Expo servers rate limit, retry with exponential backoff
  117. if (e.statusCode === 429) {
  118. return retry(e);
  119. }
  120. throw e;
  121. }
  122. }), {
  123. retries: 2,
  124. factor: 2,
  125. minTimeout: ExpoClientValues_1.requestRetryMinTimeout,
  126. });
  127. }));
  128. if (!Array.isArray(data) || data.length !== actualMessagesCount) {
  129. const apiError = new Error(`Expected Expo to respond with ${actualMessagesCount} ${actualMessagesCount === 1 ? 'ticket' : 'tickets'} but got ${data.length}`);
  130. apiError.data = data;
  131. throw apiError;
  132. }
  133. return data;
  134. });
  135. }
  136. getPushNotificationReceiptsAsync(receiptIds) {
  137. return __awaiter(this, void 0, void 0, function* () {
  138. const data = yield this.requestAsync(`${BASE_API_URL}/push/getReceipts`, {
  139. httpMethod: 'post',
  140. body: { ids: receiptIds },
  141. shouldCompress(body) {
  142. return body.length > 1024;
  143. },
  144. });
  145. if (!data || typeof data !== 'object' || Array.isArray(data)) {
  146. const apiError = new Error(`Expected Expo to respond with a map from receipt IDs to receipts but received data of another type`);
  147. apiError.data = data;
  148. throw apiError;
  149. }
  150. return data;
  151. });
  152. }
  153. chunkPushNotifications(messages) {
  154. const chunks = [];
  155. let chunk = [];
  156. let chunkMessagesCount = 0;
  157. for (const message of messages) {
  158. if (Array.isArray(message.to)) {
  159. let partialTo = [];
  160. for (const recipient of message.to) {
  161. partialTo.push(recipient);
  162. chunkMessagesCount++;
  163. if (chunkMessagesCount >= PUSH_NOTIFICATION_CHUNK_LIMIT) {
  164. // Cap this chunk here if it already exceeds PUSH_NOTIFICATION_CHUNK_LIMIT.
  165. // Then create a new chunk to continue on the remaining recipients for this message.
  166. chunk.push(Object.assign(Object.assign({}, message), { to: partialTo }));
  167. chunks.push(chunk);
  168. chunk = [];
  169. chunkMessagesCount = 0;
  170. partialTo = [];
  171. }
  172. }
  173. if (partialTo.length) {
  174. // Add remaining `partialTo` to the chunk.
  175. chunk.push(Object.assign(Object.assign({}, message), { to: partialTo }));
  176. }
  177. }
  178. else {
  179. chunk.push(message);
  180. chunkMessagesCount++;
  181. }
  182. if (chunkMessagesCount >= PUSH_NOTIFICATION_CHUNK_LIMIT) {
  183. // Cap this chunk if it exceeds PUSH_NOTIFICATION_CHUNK_LIMIT.
  184. // Then create a new chunk to continue on the remaining messages.
  185. chunks.push(chunk);
  186. chunk = [];
  187. chunkMessagesCount = 0;
  188. }
  189. }
  190. if (chunkMessagesCount) {
  191. // Add the remaining chunk to the chunks.
  192. chunks.push(chunk);
  193. }
  194. return chunks;
  195. }
  196. chunkPushNotificationReceiptIds(receiptIds) {
  197. return this.chunkItems(receiptIds, PUSH_NOTIFICATION_RECEIPT_CHUNK_LIMIT);
  198. }
  199. chunkItems(items, chunkSize) {
  200. const chunks = [];
  201. let chunk = [];
  202. for (const item of items) {
  203. chunk.push(item);
  204. if (chunk.length >= chunkSize) {
  205. chunks.push(chunk);
  206. chunk = [];
  207. }
  208. }
  209. if (chunk.length) {
  210. chunks.push(chunk);
  211. }
  212. return chunks;
  213. }
  214. requestAsync(url, options) {
  215. return __awaiter(this, void 0, void 0, function* () {
  216. let requestBody;
  217. const sdkVersion = require('../package.json').version;
  218. const requestHeaders = new node_fetch_1.Headers({
  219. Accept: 'application/json',
  220. 'Accept-Encoding': 'gzip, deflate',
  221. 'User-Agent': `expo-server-sdk-node/${sdkVersion}`,
  222. });
  223. if (this.accessToken) {
  224. requestHeaders.set('Authorization', `Bearer ${this.accessToken}`);
  225. }
  226. if (options.body != null) {
  227. const json = JSON.stringify(options.body);
  228. (0, assert_1.default)(json != null, `JSON request body must not be null`);
  229. if (options.shouldCompress(json)) {
  230. requestBody = yield gzipAsync(Buffer.from(json));
  231. requestHeaders.set('Content-Encoding', 'gzip');
  232. }
  233. else {
  234. requestBody = json;
  235. }
  236. requestHeaders.set('Content-Type', 'application/json');
  237. }
  238. const response = yield (0, node_fetch_1.default)(url, {
  239. method: options.httpMethod,
  240. body: requestBody,
  241. headers: requestHeaders,
  242. agent: this.httpAgent,
  243. });
  244. if (response.status !== 200) {
  245. const apiError = yield this.parseErrorResponseAsync(response);
  246. throw apiError;
  247. }
  248. const textBody = yield response.text();
  249. // We expect the API response body to be JSON
  250. let result;
  251. try {
  252. result = JSON.parse(textBody);
  253. }
  254. catch (_a) {
  255. const apiError = yield this.getTextResponseErrorAsync(response, textBody);
  256. throw apiError;
  257. }
  258. if (result.errors) {
  259. const apiError = this.getErrorFromResult(response, result);
  260. throw apiError;
  261. }
  262. return result.data;
  263. });
  264. }
  265. parseErrorResponseAsync(response) {
  266. return __awaiter(this, void 0, void 0, function* () {
  267. const textBody = yield response.text();
  268. let result;
  269. try {
  270. result = JSON.parse(textBody);
  271. }
  272. catch (_a) {
  273. return yield this.getTextResponseErrorAsync(response, textBody);
  274. }
  275. if (!result.errors || !Array.isArray(result.errors) || !result.errors.length) {
  276. const apiError = yield this.getTextResponseErrorAsync(response, textBody);
  277. apiError.errorData = result;
  278. return apiError;
  279. }
  280. return this.getErrorFromResult(response, result);
  281. });
  282. }
  283. getTextResponseErrorAsync(response, text) {
  284. return __awaiter(this, void 0, void 0, function* () {
  285. const apiError = new Error(`Expo responded with an error with status code ${response.status}: ` + text);
  286. apiError.statusCode = response.status;
  287. apiError.errorText = text;
  288. return apiError;
  289. });
  290. }
  291. /**
  292. * Returns an error for the first API error in the result, with an optional `others` field that
  293. * contains any other errors.
  294. */
  295. getErrorFromResult(response, result) {
  296. (0, assert_1.default)(result.errors && result.errors.length > 0, `Expected at least one error from Expo`);
  297. const [errorData, ...otherErrorData] = result.errors;
  298. const error = this.getErrorFromResultError(errorData);
  299. if (otherErrorData.length) {
  300. error.others = otherErrorData.map((data) => this.getErrorFromResultError(data));
  301. }
  302. error.statusCode = response.status;
  303. return error;
  304. }
  305. /**
  306. * Returns an error for a single API error
  307. */
  308. getErrorFromResultError(errorData) {
  309. const error = new Error(errorData.message);
  310. error.code = errorData.code;
  311. if (errorData.details != null) {
  312. error.details = errorData.details;
  313. }
  314. if (errorData.stack != null) {
  315. error.serverStack = errorData.stack;
  316. }
  317. return error;
  318. }
  319. static _getActualMessageCount(messages) {
  320. return messages.reduce((total, message) => {
  321. if (Array.isArray(message.to)) {
  322. total += message.to.length;
  323. }
  324. else {
  325. total++;
  326. }
  327. return total;
  328. }, 0);
  329. }
  330. }
  331. exports.Expo = Expo;
  332. Expo.pushNotificationChunkSizeLimit = PUSH_NOTIFICATION_CHUNK_LIMIT;
  333. Expo.pushNotificationReceiptChunkSizeLimit = PUSH_NOTIFICATION_RECEIPT_CHUNK_LIMIT;
  334. exports.default = Expo;
  335. function gzipAsync(data) {
  336. return new Promise((resolve, reject) => {
  337. zlib_1.default.gzip(data, (error, result) => {
  338. if (error) {
  339. reject(error);
  340. }
  341. else {
  342. resolve(result);
  343. }
  344. });
  345. });
  346. }
  347. class ExtensibleError extends Error {
  348. }
  349. //# sourceMappingURL=ExpoClient.js.map