UNPKG

@teipublisher/pb-components

Version:
1,203 lines (1,171 loc) 121 kB
require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ "use strict"; // istanbul ignore file var AbortController; var browserGlobal = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : null; // self is the global in web workers if (!browserGlobal) { AbortController = require('abort-controller'); } else if ('signal' in new Request('https://airtable.com')) { AbortController = browserGlobal.AbortController; } else { /* eslint-disable @typescript-eslint/no-var-requires */ var polyfill = require('abortcontroller-polyfill/dist/cjs-ponyfill'); /* eslint-enable @typescript-eslint/no-var-requires */ AbortController = polyfill.AbortController; } module.exports = AbortController; },{"abort-controller":20,"abortcontroller-polyfill/dist/cjs-ponyfill":19}],2:[function(require,module,exports){ "use strict"; var AirtableError = /** @class */ (function () { function AirtableError(error, message, statusCode) { this.error = error; this.message = message; this.statusCode = statusCode; } AirtableError.prototype.toString = function () { return [ this.message, '(', this.error, ')', this.statusCode ? "[Http code " + this.statusCode + "]" : '', ].join(''); }; return AirtableError; }()); module.exports = AirtableError; },{}],3:[function(require,module,exports){ "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var get_1 = __importDefault(require("lodash/get")); var isPlainObject_1 = __importDefault(require("lodash/isPlainObject")); var keys_1 = __importDefault(require("lodash/keys")); var fetch_1 = __importDefault(require("./fetch")); var abort_controller_1 = __importDefault(require("./abort-controller")); var object_to_query_param_string_1 = __importDefault(require("./object_to_query_param_string")); var airtable_error_1 = __importDefault(require("./airtable_error")); var table_1 = __importDefault(require("./table")); var http_headers_1 = __importDefault(require("./http_headers")); var run_action_1 = __importDefault(require("./run_action")); var package_version_1 = __importDefault(require("./package_version")); var exponential_backoff_with_jitter_1 = __importDefault(require("./exponential_backoff_with_jitter")); var userAgent = "Airtable.js/" + package_version_1.default; var Base = /** @class */ (function () { function Base(airtable, baseId) { this._airtable = airtable; this._id = baseId; } Base.prototype.table = function (tableName) { return new table_1.default(this, null, tableName); }; Base.prototype.makeRequest = function (options) { var _this = this; var _a; if (options === void 0) { options = {}; } var method = get_1.default(options, 'method', 'GET').toUpperCase(); var url = this._airtable._endpointUrl + "/v" + this._airtable._apiVersionMajor + "/" + this._id + get_1.default(options, 'path', '/') + "?" + object_to_query_param_string_1.default(get_1.default(options, 'qs', {})); var controller = new abort_controller_1.default(); var headers = this._getRequestHeaders(Object.assign({}, this._airtable._customHeaders, (_a = options.headers) !== null && _a !== void 0 ? _a : {})); var requestOptions = { method: method, headers: headers, signal: controller.signal, }; if ('body' in options && _canRequestMethodIncludeBody(method)) { requestOptions.body = JSON.stringify(options.body); } var timeout = setTimeout(function () { controller.abort(); }, this._airtable._requestTimeout); return new Promise(function (resolve, reject) { fetch_1.default(url, requestOptions) .then(function (resp) { clearTimeout(timeout); if (resp.status === 429 && !_this._airtable._noRetryIfRateLimited) { var numAttempts_1 = get_1.default(options, '_numAttempts', 0); var backoffDelayMs = exponential_backoff_with_jitter_1.default(numAttempts_1); setTimeout(function () { var newOptions = __assign(__assign({}, options), { _numAttempts: numAttempts_1 + 1 }); _this.makeRequest(newOptions) .then(resolve) .catch(reject); }, backoffDelayMs); } else { resp.json() .then(function (body) { var err = _this._checkStatusForError(resp.status, body) || _getErrorForNonObjectBody(resp.status, body); if (err) { reject(err); } else { resolve({ statusCode: resp.status, headers: resp.headers, body: body, }); } }) .catch(function () { var err = _getErrorForNonObjectBody(resp.status); reject(err); }); } }) .catch(function (err) { clearTimeout(timeout); err = new airtable_error_1.default('CONNECTION_ERROR', err.message, null); reject(err); }); }); }; /** * @deprecated This method is deprecated. */ Base.prototype.runAction = function (method, path, queryParams, bodyData, callback) { run_action_1.default(this, method, path, queryParams, bodyData, callback, 0); }; Base.prototype._getRequestHeaders = function (headers) { var result = new http_headers_1.default(); result.set('Authorization', "Bearer " + this._airtable._apiKey); result.set('User-Agent', userAgent); result.set('Content-Type', 'application/json'); for (var _i = 0, _a = keys_1.default(headers); _i < _a.length; _i++) { var headerKey = _a[_i]; result.set(headerKey, headers[headerKey]); } return result.toJSON(); }; Base.prototype._checkStatusForError = function (statusCode, body) { var _a = (body !== null && body !== void 0 ? body : { error: {} }).error, error = _a === void 0 ? {} : _a; var type = error.type, message = error.message; if (statusCode === 401) { return new airtable_error_1.default('AUTHENTICATION_REQUIRED', 'You should provide valid api key to perform this operation', statusCode); } else if (statusCode === 403) { return new airtable_error_1.default('NOT_AUTHORIZED', 'You are not authorized to perform this operation', statusCode); } else if (statusCode === 404) { return new airtable_error_1.default('NOT_FOUND', message !== null && message !== void 0 ? message : 'Could not find what you are looking for', statusCode); } else if (statusCode === 413) { return new airtable_error_1.default('REQUEST_TOO_LARGE', 'Request body is too large', statusCode); } else if (statusCode === 422) { return new airtable_error_1.default(type !== null && type !== void 0 ? type : 'UNPROCESSABLE_ENTITY', message !== null && message !== void 0 ? message : 'The operation cannot be processed', statusCode); } else if (statusCode === 429) { return new airtable_error_1.default('TOO_MANY_REQUESTS', 'You have made too many requests in a short period of time. Please retry your request later', statusCode); } else if (statusCode === 500) { return new airtable_error_1.default('SERVER_ERROR', 'Try again. If the problem persists, contact support.', statusCode); } else if (statusCode === 503) { return new airtable_error_1.default('SERVICE_UNAVAILABLE', 'The service is temporarily unavailable. Please retry shortly.', statusCode); } else if (statusCode >= 400) { return new airtable_error_1.default(type !== null && type !== void 0 ? type : 'UNEXPECTED_ERROR', message !== null && message !== void 0 ? message : 'An unexpected error occurred', statusCode); } else { return null; } }; Base.prototype.doCall = function (tableName) { return this.table(tableName); }; Base.prototype.getId = function () { return this._id; }; Base.createFunctor = function (airtable, baseId) { var base = new Base(airtable, baseId); var baseFn = function (tableName) { return base.doCall(tableName); }; baseFn._base = base; baseFn.table = base.table.bind(base); baseFn.makeRequest = base.makeRequest.bind(base); baseFn.runAction = base.runAction.bind(base); baseFn.getId = base.getId.bind(base); return baseFn; }; return Base; }()); function _canRequestMethodIncludeBody(method) { return method !== 'GET' && method !== 'DELETE'; } function _getErrorForNonObjectBody(statusCode, body) { if (isPlainObject_1.default(body)) { return null; } else { return new airtable_error_1.default('UNEXPECTED_ERROR', 'The response from Airtable was invalid JSON. Please try again soon.', statusCode); } } module.exports = Base; },{"./abort-controller":1,"./airtable_error":2,"./exponential_backoff_with_jitter":6,"./fetch":7,"./http_headers":9,"./object_to_query_param_string":11,"./package_version":12,"./run_action":16,"./table":17,"lodash/get":77,"lodash/isPlainObject":89,"lodash/keys":93}],4:[function(require,module,exports){ "use strict"; /** * Given a function fn that takes a callback as its last argument, returns * a new version of the function that takes the callback optionally. If * the function is not called with a callback for the last argument, the * function will return a promise instead. */ /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types */ function callbackToPromise(fn, context, callbackArgIndex) { if (callbackArgIndex === void 0) { callbackArgIndex = void 0; } /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types */ return function () { var callArgs = []; for (var _i = 0; _i < arguments.length; _i++) { callArgs[_i] = arguments[_i]; } var thisCallbackArgIndex; if (callbackArgIndex === void 0) { // istanbul ignore next thisCallbackArgIndex = callArgs.length > 0 ? callArgs.length - 1 : 0; } else { thisCallbackArgIndex = callbackArgIndex; } var callbackArg = callArgs[thisCallbackArgIndex]; if (typeof callbackArg === 'function') { fn.apply(context, callArgs); return void 0; } else { var args_1 = []; // If an explicit callbackArgIndex is set, but the function is called // with too few arguments, we want to push undefined onto args so that // our constructed callback ends up at the right index. var argLen = Math.max(callArgs.length, thisCallbackArgIndex); for (var i = 0; i < argLen; i++) { args_1.push(callArgs[i]); } return new Promise(function (resolve, reject) { args_1.push(function (err, result) { if (err) { reject(err); } else { resolve(result); } }); fn.apply(context, args_1); }); } }; } module.exports = callbackToPromise; },{}],5:[function(require,module,exports){ "use strict"; var didWarnForDeprecation = {}; /** * Convenience function for marking a function as deprecated. * * Will emit a warning the first time that function is called. * * @param fn the function to mark as deprecated. * @param key a unique key identifying the function. * @param message the warning message. * * @return a wrapped function */ function deprecate(fn, key, message) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!didWarnForDeprecation[key]) { didWarnForDeprecation[key] = true; console.warn(message); } fn.apply(this, args); }; } module.exports = deprecate; },{}],6:[function(require,module,exports){ "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var internal_config_json_1 = __importDefault(require("./internal_config.json")); // "Full Jitter" algorithm taken from https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ function exponentialBackoffWithJitter(numberOfRetries) { var rawBackoffTimeMs = internal_config_json_1.default.INITIAL_RETRY_DELAY_IF_RATE_LIMITED * Math.pow(2, numberOfRetries); var clippedBackoffTimeMs = Math.min(internal_config_json_1.default.MAX_RETRY_DELAY_IF_RATE_LIMITED, rawBackoffTimeMs); var jitteredBackoffTimeMs = Math.random() * clippedBackoffTimeMs; return jitteredBackoffTimeMs; } module.exports = exponentialBackoffWithJitter; },{"./internal_config.json":10}],7:[function(require,module,exports){ "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; // istanbul ignore file var node_fetch_1 = __importDefault(require("node-fetch")); var browserGlobal = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : null; // self is the global in web workers module.exports = !browserGlobal ? node_fetch_1.default : browserGlobal.fetch.bind(browserGlobal); },{"node-fetch":20}],8:[function(require,module,exports){ "use strict"; /* eslint-enable @typescript-eslint/no-explicit-any */ function has(object, property) { return Object.prototype.hasOwnProperty.call(object, property); } module.exports = has; },{}],9:[function(require,module,exports){ "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var keys_1 = __importDefault(require("lodash/keys")); var isBrowser = typeof window !== 'undefined'; var HttpHeaders = /** @class */ (function () { function HttpHeaders() { this._headersByLowercasedKey = {}; } HttpHeaders.prototype.set = function (headerKey, headerValue) { var lowercasedKey = headerKey.toLowerCase(); if (lowercasedKey === 'x-airtable-user-agent') { lowercasedKey = 'user-agent'; headerKey = 'User-Agent'; } this._headersByLowercasedKey[lowercasedKey] = { headerKey: headerKey, headerValue: headerValue, }; }; HttpHeaders.prototype.toJSON = function () { var result = {}; for (var _i = 0, _a = keys_1.default(this._headersByLowercasedKey); _i < _a.length; _i++) { var lowercasedKey = _a[_i]; var headerDefinition = this._headersByLowercasedKey[lowercasedKey]; var headerKey = void 0; /* istanbul ignore next */ if (isBrowser && lowercasedKey === 'user-agent') { // Some browsers do not allow overriding the user agent. // https://github.com/Airtable/airtable.js/issues/52 headerKey = 'X-Airtable-User-Agent'; } else { headerKey = headerDefinition.headerKey; } result[headerKey] = headerDefinition.headerValue; } return result; }; return HttpHeaders; }()); module.exports = HttpHeaders; },{"lodash/keys":93}],10:[function(require,module,exports){ module.exports={ "INITIAL_RETRY_DELAY_IF_RATE_LIMITED": 5000, "MAX_RETRY_DELAY_IF_RATE_LIMITED": 600000 } },{}],11:[function(require,module,exports){ "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var isArray_1 = __importDefault(require("lodash/isArray")); var isNil_1 = __importDefault(require("lodash/isNil")); var keys_1 = __importDefault(require("lodash/keys")); /* eslint-enable @typescript-eslint/no-explicit-any */ // Adapted from jQuery.param: // https://github.com/jquery/jquery/blob/2.2-stable/src/serialize.js function buildParams(prefix, obj, addFn) { if (isArray_1.default(obj)) { // Serialize array item. for (var index = 0; index < obj.length; index++) { var value = obj[index]; if (/\[\]$/.test(prefix)) { // Treat each array item as a scalar. addFn(prefix, value); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams(prefix + "[" + (typeof value === 'object' && value !== null ? index : '') + "]", value, addFn); } } } else if (typeof obj === 'object') { // Serialize object item. for (var _i = 0, _a = keys_1.default(obj); _i < _a.length; _i++) { var key = _a[_i]; var value = obj[key]; buildParams(prefix + "[" + key + "]", value, addFn); } } else { // Serialize scalar item. addFn(prefix, obj); } } function objectToQueryParamString(obj) { var parts = []; var addFn = function (key, value) { value = isNil_1.default(value) ? '' : value; parts.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)); }; for (var _i = 0, _a = keys_1.default(obj); _i < _a.length; _i++) { var key = _a[_i]; var value = obj[key]; buildParams(key, value, addFn); } return parts.join('&').replace(/%20/g, '+'); } module.exports = objectToQueryParamString; },{"lodash/isArray":79,"lodash/isNil":85,"lodash/keys":93}],12:[function(require,module,exports){ "use strict"; module.exports = "0.12.2"; },{}],13:[function(require,module,exports){ "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var isFunction_1 = __importDefault(require("lodash/isFunction")); var keys_1 = __importDefault(require("lodash/keys")); var record_1 = __importDefault(require("./record")); var callback_to_promise_1 = __importDefault(require("./callback_to_promise")); var has_1 = __importDefault(require("./has")); var query_params_1 = require("./query_params"); var object_to_query_param_string_1 = __importDefault(require("./object_to_query_param_string")); /** * Builds a query object. Won't fetch until `firstPage` or * or `eachPage` is called. * * Params should be validated prior to being passed to Query * with `Query.validateParams`. */ var Query = /** @class */ (function () { function Query(table, params) { this._table = table; this._params = params; this.firstPage = callback_to_promise_1.default(firstPage, this); this.eachPage = callback_to_promise_1.default(eachPage, this, 1); this.all = callback_to_promise_1.default(all, this); } /** * Validates the parameters for passing to the Query constructor. * * @params {object} params parameters to validate * * @return an object with two keys: * validParams: the object that should be passed to the constructor. * ignoredKeys: a list of keys that will be ignored. * errors: a list of error messages. */ Query.validateParams = function (params) { var validParams = {}; var ignoredKeys = []; var errors = []; for (var _i = 0, _a = keys_1.default(params); _i < _a.length; _i++) { var key = _a[_i]; var value = params[key]; if (has_1.default(Query.paramValidators, key)) { var validator = Query.paramValidators[key]; var validationResult = validator(value); if (validationResult.pass) { validParams[key] = value; } else { errors.push(validationResult.error); } } else { ignoredKeys.push(key); } } return { validParams: validParams, ignoredKeys: ignoredKeys, errors: errors, }; }; Query.paramValidators = query_params_1.paramValidators; return Query; }()); /** * Fetches the first page of results for the query asynchronously, * then calls `done(error, records)`. */ function firstPage(done) { if (!isFunction_1.default(done)) { throw new Error('The first parameter to `firstPage` must be a function'); } this.eachPage(function (records) { done(null, records); }, function (error) { done(error, null); }); } /** * Fetches each page of results for the query asynchronously. * * Calls `pageCallback(records, fetchNextPage)` for each * page. You must call `fetchNextPage()` to fetch the next page of * results. * * After fetching all pages, or if there's an error, calls * `done(error)`. */ function eachPage(pageCallback, done) { var _this = this; if (!isFunction_1.default(pageCallback)) { throw new Error('The first parameter to `eachPage` must be a function'); } if (!isFunction_1.default(done) && done !== void 0) { throw new Error('The second parameter to `eachPage` must be a function or undefined'); } var params = __assign({}, this._params); var pathAndParamsAsString = "/" + this._table._urlEncodedNameOrId() + "?" + object_to_query_param_string_1.default(params); var queryParams = {}; var requestData = null; var method; var path; if (params.method === 'post' || pathAndParamsAsString.length > query_params_1.URL_CHARACTER_LENGTH_LIMIT) { // There is a 16kb limit on GET requests. Since the URL makes up nearly all of the request size, we check for any requests that // that come close to this limit and send it as a POST instead. Additionally, we'll send the request as a post if it is specified // with the request params requestData = params; method = 'post'; path = "/" + this._table._urlEncodedNameOrId() + "/listRecords"; var paramNames = Object.keys(params); for (var _i = 0, paramNames_1 = paramNames; _i < paramNames_1.length; _i++) { var paramName = paramNames_1[_i]; if (query_params_1.shouldListRecordsParamBePassedAsParameter(paramName)) { // timeZone and userLocale is parsed from the GET request separately from the other params. This parsing // does not occurring within the body parser we use for POST requests, so this will still need to be passed // via query params queryParams[paramName] = params[paramName]; } else { requestData[paramName] = params[paramName]; } } } else { method = 'get'; queryParams = params; path = "/" + this._table._urlEncodedNameOrId(); } var inner = function () { _this._table._base.runAction(method, path, queryParams, requestData, function (err, response, result) { if (err) { done(err, null); } else { var next = void 0; if (result.offset) { params.offset = result.offset; next = inner; } else { next = function () { done(null); }; } var records = result.records.map(function (recordJson) { return new record_1.default(_this._table, null, recordJson); }); pageCallback(records, next); } }); }; inner(); } /** * Fetches all pages of results asynchronously. May take a long time. */ function all(done) { if (!isFunction_1.default(done)) { throw new Error('The first parameter to `all` must be a function'); } var allRecords = []; this.eachPage(function (pageRecords, fetchNextPage) { allRecords.push.apply(allRecords, pageRecords); fetchNextPage(); }, function (err) { if (err) { done(err, null); } else { done(null, allRecords); } }); } module.exports = Query; },{"./callback_to_promise":4,"./has":8,"./object_to_query_param_string":11,"./query_params":14,"./record":15,"lodash/isFunction":83,"lodash/keys":93}],14:[function(require,module,exports){ "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldListRecordsParamBePassedAsParameter = exports.URL_CHARACTER_LENGTH_LIMIT = exports.paramValidators = void 0; var typecheck_1 = __importDefault(require("./typecheck")); var isString_1 = __importDefault(require("lodash/isString")); var isNumber_1 = __importDefault(require("lodash/isNumber")); var isPlainObject_1 = __importDefault(require("lodash/isPlainObject")); var isBoolean_1 = __importDefault(require("lodash/isBoolean")); exports.paramValidators = { fields: typecheck_1.default(typecheck_1.default.isArrayOf(isString_1.default), 'the value for `fields` should be an array of strings'), filterByFormula: typecheck_1.default(isString_1.default, 'the value for `filterByFormula` should be a string'), maxRecords: typecheck_1.default(isNumber_1.default, 'the value for `maxRecords` should be a number'), pageSize: typecheck_1.default(isNumber_1.default, 'the value for `pageSize` should be a number'), offset: typecheck_1.default(isNumber_1.default, 'the value for `offset` should be a number'), sort: typecheck_1.default(typecheck_1.default.isArrayOf(function (obj) { return (isPlainObject_1.default(obj) && isString_1.default(obj.field) && (obj.direction === void 0 || ['asc', 'desc'].includes(obj.direction))); }), 'the value for `sort` should be an array of sort objects. ' + 'Each sort object must have a string `field` value, and an optional ' + '`direction` value that is "asc" or "desc".'), view: typecheck_1.default(isString_1.default, 'the value for `view` should be a string'), cellFormat: typecheck_1.default(function (cellFormat) { return isString_1.default(cellFormat) && ['json', 'string'].includes(cellFormat); }, 'the value for `cellFormat` should be "json" or "string"'), timeZone: typecheck_1.default(isString_1.default, 'the value for `timeZone` should be a string'), userLocale: typecheck_1.default(isString_1.default, 'the value for `userLocale` should be a string'), method: typecheck_1.default(function (method) { return isString_1.default(method) && ['get', 'post'].includes(method); }, 'the value for `method` should be "get" or "post"'), returnFieldsByFieldId: typecheck_1.default(isBoolean_1.default, 'the value for `returnFieldsByFieldId` should be a boolean'), recordMetadata: typecheck_1.default(typecheck_1.default.isArrayOf(isString_1.default), 'the value for `recordMetadata` should be an array of strings'), }; exports.URL_CHARACTER_LENGTH_LIMIT = 15000; exports.shouldListRecordsParamBePassedAsParameter = function (paramName) { return paramName === 'timeZone' || paramName === 'userLocale'; }; },{"./typecheck":18,"lodash/isBoolean":81,"lodash/isNumber":86,"lodash/isPlainObject":89,"lodash/isString":90}],15:[function(require,module,exports){ "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var callback_to_promise_1 = __importDefault(require("./callback_to_promise")); var Record = /** @class */ (function () { function Record(table, recordId, recordJson) { this._table = table; this.id = recordId || recordJson.id; if (recordJson) { this.commentCount = recordJson.commentCount; } this.setRawJson(recordJson); this.save = callback_to_promise_1.default(save, this); this.patchUpdate = callback_to_promise_1.default(patchUpdate, this); this.putUpdate = callback_to_promise_1.default(putUpdate, this); this.destroy = callback_to_promise_1.default(destroy, this); this.fetch = callback_to_promise_1.default(fetch, this); this.updateFields = this.patchUpdate; this.replaceFields = this.putUpdate; } Record.prototype.getId = function () { return this.id; }; Record.prototype.get = function (columnName) { return this.fields[columnName]; }; Record.prototype.set = function (columnName, columnValue) { this.fields[columnName] = columnValue; }; Record.prototype.setRawJson = function (rawJson) { this._rawJson = rawJson; this.fields = (this._rawJson && this._rawJson.fields) || {}; }; return Record; }()); function save(done) { this.putUpdate(this.fields, done); } function patchUpdate(cellValuesByName, opts, done) { var _this = this; if (!done) { done = opts; opts = {}; } var updateBody = __assign({ fields: cellValuesByName }, opts); this._table._base.runAction('patch', "/" + this._table._urlEncodedNameOrId() + "/" + this.id, {}, updateBody, function (err, response, results) { if (err) { done(err); return; } _this.setRawJson(results); done(null, _this); }); } function putUpdate(cellValuesByName, opts, done) { var _this = this; if (!done) { done = opts; opts = {}; } var updateBody = __assign({ fields: cellValuesByName }, opts); this._table._base.runAction('put', "/" + this._table._urlEncodedNameOrId() + "/" + this.id, {}, updateBody, function (err, response, results) { if (err) { done(err); return; } _this.setRawJson(results); done(null, _this); }); } function destroy(done) { var _this = this; this._table._base.runAction('delete', "/" + this._table._urlEncodedNameOrId() + "/" + this.id, {}, null, function (err) { if (err) { done(err); return; } done(null, _this); }); } function fetch(done) { var _this = this; this._table._base.runAction('get', "/" + this._table._urlEncodedNameOrId() + "/" + this.id, {}, null, function (err, response, results) { if (err) { done(err); return; } _this.setRawJson(results); done(null, _this); }); } module.exports = Record; },{"./callback_to_promise":4}],16:[function(require,module,exports){ "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var exponential_backoff_with_jitter_1 = __importDefault(require("./exponential_backoff_with_jitter")); var object_to_query_param_string_1 = __importDefault(require("./object_to_query_param_string")); var package_version_1 = __importDefault(require("./package_version")); var fetch_1 = __importDefault(require("./fetch")); var abort_controller_1 = __importDefault(require("./abort-controller")); var userAgent = "Airtable.js/" + package_version_1.default; function runAction(base, method, path, queryParams, bodyData, callback, numAttempts) { var url = base._airtable._endpointUrl + "/v" + base._airtable._apiVersionMajor + "/" + base._id + path + "?" + object_to_query_param_string_1.default(queryParams); var headers = { authorization: "Bearer " + base._airtable._apiKey, 'x-api-version': base._airtable._apiVersion, 'x-airtable-application-id': base.getId(), 'content-type': 'application/json', }; var isBrowser = typeof window !== 'undefined'; // Some browsers do not allow overriding the user agent. // https://github.com/Airtable/airtable.js/issues/52 if (isBrowser) { headers['x-airtable-user-agent'] = userAgent; } else { headers['User-Agent'] = userAgent; } var controller = new abort_controller_1.default(); var normalizedMethod = method.toUpperCase(); var options = { method: normalizedMethod, headers: headers, signal: controller.signal, }; if (bodyData !== null) { if (normalizedMethod === 'GET' || normalizedMethod === 'HEAD') { console.warn('body argument to runAction are ignored with GET or HEAD requests'); } else { options.body = JSON.stringify(bodyData); } } var timeout = setTimeout(function () { controller.abort(); }, base._airtable._requestTimeout); fetch_1.default(url, options) .then(function (resp) { clearTimeout(timeout); if (resp.status === 429 && !base._airtable._noRetryIfRateLimited) { var backoffDelayMs = exponential_backoff_with_jitter_1.default(numAttempts); setTimeout(function () { runAction(base, method, path, queryParams, bodyData, callback, numAttempts + 1); }, backoffDelayMs); } else { resp.json() .then(function (body) { var error = base._checkStatusForError(resp.status, body); // Ensure Response interface matches interface from // `request` Response object var r = {}; Object.keys(resp).forEach(function (property) { r[property] = resp[property]; }); r.body = body; r.statusCode = resp.status; callback(error, r, body); }) .catch(function () { callback(base._checkStatusForError(resp.status)); }); } }) .catch(function (error) { clearTimeout(timeout); callback(error); }); } module.exports = runAction; },{"./abort-controller":1,"./exponential_backoff_with_jitter":6,"./fetch":7,"./object_to_query_param_string":11,"./package_version":12}],17:[function(require,module,exports){ "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var isPlainObject_1 = __importDefault(require("lodash/isPlainObject")); var deprecate_1 = __importDefault(require("./deprecate")); var query_1 = __importDefault(require("./query")); var query_params_1 = require("./query_params"); var object_to_query_param_string_1 = __importDefault(require("./object_to_query_param_string")); var record_1 = __importDefault(require("./record")); var callback_to_promise_1 = __importDefault(require("./callback_to_promise")); var Table = /** @class */ (function () { function Table(base, tableId, tableName) { if (!tableId && !tableName) { throw new Error('Table name or table ID is required'); } this._base = base; this.id = tableId; this.name = tableName; // Public API this.find = callback_to_promise_1.default(this._findRecordById, this); this.select = this._selectRecords.bind(this); this.create = callback_to_promise_1.default(this._createRecords, this); this.update = callback_to_promise_1.default(this._updateRecords.bind(this, false), this); this.replace = callback_to_promise_1.default(this._updateRecords.bind(this, true), this); this.destroy = callback_to_promise_1.default(this._destroyRecord, this); // Deprecated API this.list = deprecate_1.default(this._listRecords.bind(this), 'table.list', 'Airtable: `list()` is deprecated. Use `select()` instead.'); this.forEach = deprecate_1.default(this._forEachRecord.bind(this), 'table.forEach', 'Airtable: `forEach()` is deprecated. Use `select()` instead.'); } Table.prototype._findRecordById = function (recordId, done) { var record = new record_1.default(this, recordId); record.fetch(done); }; Table.prototype._selectRecords = function (params) { if (params === void 0) { params = {}; } if (arguments.length > 1) { console.warn("Airtable: `select` takes only one parameter, but it was given " + arguments.length + " parameters. Use `eachPage` or `firstPage` to fetch records."); } if (isPlainObject_1.default(params)) { var validationResults = query_1.default.validateParams(params); if (validationResults.errors.length) { var formattedErrors = validationResults.errors.map(function (error) { return " * " + error; }); throw new Error("Airtable: invalid parameters for `select`:\n" + formattedErrors.join('\n')); } if (validationResults.ignoredKeys.length) { console.warn("Airtable: the following parameters to `select` will be ignored: " + validationResults.ignoredKeys.join(', ')); } return new query_1.default(this, validationResults.validParams); } else { throw new Error('Airtable: the parameter for `select` should be a plain object or undefined.'); } }; Table.prototype._urlEncodedNameOrId = function () { return this.id || encodeURIComponent(this.name); }; Table.prototype._createRecords = function (recordsData, optionalParameters, done) { var _this = this; var isCreatingMultipleRecords = Array.isArray(recordsData); if (!done) { done = optionalParameters; optionalParameters = {}; } var requestData; if (isCreatingMultipleRecords) { requestData = __assign({ records: recordsData }, optionalParameters); } else { requestData = __assign({ fields: recordsData }, optionalParameters); } this._base.runAction('post', "/" + this._urlEncodedNameOrId() + "/", {}, requestData, function (err, resp, body) { if (err) { done(err); return; } var result; if (isCreatingMultipleRecords) { result = body.records.map(function (record) { return new record_1.default(_this, record.id, record); }); } else { result = new record_1.default(_this, body.id, body); } done(null, result); }); }; Table.prototype._updateRecords = function (isDestructiveUpdate, recordsDataOrRecordId, recordDataOrOptsOrDone, optsOrDone, done) { var _this = this; var opts; if (Array.isArray(recordsDataOrRecordId)) { var recordsData = recordsDataOrRecordId; opts = isPlainObject_1.default(recordDataOrOptsOrDone) ? recordDataOrOptsOrDone : {}; done = (optsOrDone || recordDataOrOptsOrDone); var method = isDestructiveUpdate ? 'put' : 'patch'; var requestData = __assign({ records: recordsData }, opts); this._base.runAction(method, "/" + this._urlEncodedNameOrId() + "/", {}, requestData, function (err, resp, body) { if (err) { done(err); return; } var result = body.records.map(function (record) { return new record_1.default(_this, record.id, record); }); done(null, result); }); } else { var recordId = recordsDataOrRecordId; var recordData = recordDataOrOptsOrDone; opts = isPlainObject_1.default(optsOrDone) ? optsOrDone : {}; done = (done || optsOrDone); var record = new record_1.default(this, recordId); if (isDestructiveUpdate) { record.putUpdate(recordData, opts, done); } else { record.patchUpdate(recordData, opts, done); } } }; Table.prototype._destroyRecord = function (recordIdsOrId, done) { var _this = this; if (Array.isArray(recordIdsOrId)) { var queryParams = { records: recordIdsOrId }; this._base.runAction('delete', "/" + this._urlEncodedNameOrId(), queryParams, null, function (err, response, results) { if (err) { done(err); return; } var records = results.records.map(function (_a) { var id = _a.id; return new record_1.default(_this, id, null); }); done(null, records); }); } else { var record = new record_1.default(this, recordIdsOrId); record.destroy(done); } }; Table.prototype._listRecords = function (pageSize, offset, opts, done) { var _this = this; if (!done) { done = opts; opts = {}; } var pathAndParamsAsString = "/" + this._urlEncodedNameOrId() + "?" + object_to_query_param_string_1.default(opts); var path; var listRecordsParameters = {}; var listRecordsData = null; var method; if ((typeof opts !== 'function' && opts.method === 'post') || pathAndParamsAsString.length > query_params_1.URL_CHARACTER_LENGTH_LIMIT) { // // There is a 16kb limit on GET requests. Since the URL makes up nearly all of the request size, we check for any requests that // that come close to this limit and send it as a POST instead. Additionally, we'll send the request as a post if it is specified // with the request params path = "/" + this._urlEncodedNameOrId() + "/listRecords"; listRecordsData = __assign(__assign({}, (pageSize && { pageSize: pageSize })), (offset && { offset: offset })); method = 'post'; var paramNames = Object.keys(opts); for (var _i = 0, paramNames_1 = paramNames; _i < paramNames_1.length; _i++) { var paramName = paramNames_1[_i]; if (query_params_1.shouldListRecordsParamBePassedAsParameter(paramName)) { listRecordsParameters[paramName] = opts[paramName]; } else { listRecordsData[paramName] = opts[paramName]; } } } else { method = 'get'; path = "/" + this._urlEncodedNameOrId() + "/"; listRecordsParameters = __assign({ limit: pageSize, offset: offset }, opts); } this._base.runAction(method, path, listRecordsParameters, listRecordsData, function (err, response, results) { if (err) { done(err); return; } var records = results.records.map(function (recordJson) { return new record_1.default(_this, null, recordJson); }); done(null, records, results.offset); }); }; Table.prototype._forEachRecord = function (opts, callback, done) { var _this = this; if (arguments.length === 2) { done = callback; callback = opts; opts = {}; } var limit = Table.__recordsPerPageForIteration || 100; var offset = null; var nextPage = function () { _this._listRecords(limit, offset, opts, function (err, page, newOffset) { if (err) { done(err); return; } for (var index = 0; index < page.length; index++) { callback(page[index]); } if (newOffset) { offset = newOffset; nextPage(); } else { done(); } }); }; nextPage(); }; return Table; }()); module.exports = Table; },{"./callback_to_promise":4,"./deprecate":5,"./object_to_query_param_string":11,"./query":13,"./query_params":14,"./record":15,"lodash/isPlainObject":89}],18:[function(require,module,exports){ "use strict"; /* eslint-enable @typescript-eslint/no-explicit-any */ function check(fn, error) { return function (value) { if (fn(value)) { return { pass: true }; } else { return { pass: false, error: error }; } }; } check.isOneOf = function isOneOf(options) { return options.includes.bind(options); }; check.isArrayOf = function (itemValidator) { return function (value) { return Array.isArray(value) && value.every(itemValidator); }; }; module.exports = check; },{}],19:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _superPropBase(object