contentful-import 9.0.21 → 9.2.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.
package/package.json CHANGED
@@ -1,22 +1,30 @@
1
1
  {
2
2
  "name": "contentful-import",
3
- "version": "9.0.21",
3
+ "version": "9.2.0",
4
4
  "description": "this tool allows you to import JSON dump exported by contentful-export",
5
- "main": "dist/index.js",
5
+ "main": "dist/index.mjs",
6
+ "typings": "dist/index.d.ts",
7
+ "module": "dist/index.mjs",
6
8
  "engines": {
7
9
  "node": ">=16"
8
10
  },
11
+ "exports": {
12
+ "default": "./dist/index.js",
13
+ "require": "./dist/index.js",
14
+ "import": "./dist/index.mjs",
15
+ "node": "./dist/index.js"
16
+ },
9
17
  "bin": {
10
18
  "contentful-import": "./bin/contentful-import"
11
19
  },
12
20
  "scripts": {
13
- "build": "npm run clean && babel lib --out-dir dist",
21
+ "build": "tsup",
14
22
  "build:watch": "babel lib --out-dir dist --watch",
15
23
  "clean": "rimraf dist && rimraf coverage",
16
24
  "lint": "eslint lib bin/contentful-import test",
17
25
  "pretest": "npm run lint && npm run build",
18
26
  "test": "npm run test:unit && npm run test:integration",
19
- "test:unit": "jest --testPathPattern=test/unit --coverage",
27
+ "test:unit": "jest --testPathPattern=test/unit --runInBand --coverage",
20
28
  "test:unit:debug": "node --inspect-brk ./node_modules/.bin/jest --runInBand --watch --testPathPattern=test/unit",
21
29
  "test:unit:watch": "npm run test:unit -- --watch",
22
30
  "test:integration": "jest --testPathPattern=test/integration",
@@ -49,8 +57,18 @@
49
57
  "bugs": {
50
58
  "url": "https://github.com/contentful/contentful-import/issues"
51
59
  },
60
+ "tsup": {
61
+ "entry": [
62
+ "lib/index.ts"
63
+ ],
64
+ "format": [
65
+ "cjs",
66
+ "esm"
67
+ ],
68
+ "clean": true,
69
+ "dts": true
70
+ },
52
71
  "dependencies": {
53
- "@babel/eslint-parser": "^7.22.15",
54
72
  "@discoveryjs/json-ext": "^0.5.7",
55
73
  "bluebird": "^3.5.1",
56
74
  "cli-table3": "^0.6.0",
@@ -68,10 +86,14 @@
68
86
  "yargs": "^17.7.2"
69
87
  },
70
88
  "devDependencies": {
71
- "@babel/cli": "^7.22.15",
72
- "@babel/core": "^7.22.20",
89
+ "@babel/cli": "^7.23.0",
90
+ "@babel/core": "^7.23.0",
73
91
  "@babel/plugin-proposal-object-rest-spread": "^7.20.7",
74
92
  "@babel/preset-env": "^7.22.20",
93
+ "@types/jest": "^29.5.5",
94
+ "@types/node": "^20.6.3",
95
+ "@typescript-eslint/eslint-plugin": "^6.7.2",
96
+ "@typescript-eslint/parser": "^6.7.2",
75
97
  "babel-jest": "^29.7.0",
76
98
  "babel-plugin-add-module-exports": "^1.0.2",
77
99
  "babel-preset-env": "^1.7.0",
@@ -80,10 +102,14 @@
80
102
  "eslint-plugin-jest": "^27.4.0",
81
103
  "eslint-plugin-node": "^11.1.0",
82
104
  "eslint-plugin-promise": "^6.1.1",
105
+ "eslint-plugin-standard": "^5.0.0",
83
106
  "husky": "^8.0.3",
84
107
  "jest": "^29.7.0",
85
108
  "rimraf": "^5.0.0",
86
- "semantic-release": "^19.0.5"
109
+ "semantic-release": "^19.0.5",
110
+ "ts-jest": "^29.1.1",
111
+ "tsup": "^7.2.0",
112
+ "typescript": "^5.2.2"
87
113
  },
88
114
  "files": [
89
115
  "bin",
@@ -113,17 +139,5 @@
113
139
  "@semantic-release/npm",
114
140
  "@semantic-release/github"
115
141
  ]
116
- },
117
- "jest": {
118
- "testEnvironment": "node",
119
- "collectCoverageFrom": [
120
- "lib/**/*.js"
121
- ],
122
- "coveragePathIgnorePatterns": [
123
- "usageParams.js"
124
- ],
125
- "transformIgnorePatterns": [
126
- "node_modules/(?!(contentful-batch-libs)/)"
127
- ]
128
142
  }
129
143
  }
@@ -1,94 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = parseOptions;
7
- var _fs = _interopRequireDefault(require("fs"));
8
- var _path = require("path");
9
- var _format = _interopRequireDefault(require("date-fns/format"));
10
- var _package = require("../package");
11
- var _headers = require("./utils/headers");
12
- var _proxy = require("contentful-batch-libs/dist/proxy");
13
- var _addSequenceHeader = _interopRequireDefault(require("contentful-batch-libs/dist/add-sequence-header"));
14
- var _jsonExt = require("@discoveryjs/json-ext");
15
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
17
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
18
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
19
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
20
- function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
21
- const SUPPORTED_ENTITY_TYPES = ['contentTypes', 'tags', 'entries', 'assets', 'locales', 'webhooks', 'editorInterfaces'];
22
- async function parseOptions(params) {
23
- const defaultOptions = {
24
- skipContentModel: false,
25
- skipLocales: false,
26
- skipContentPublishing: false,
27
- useVerboseRenderer: false,
28
- environmentId: 'master',
29
- rawProxy: false,
30
- uploadAssets: false,
31
- rateLimit: 7
32
- };
33
- const configFile = params.config ? require((0, _path.resolve)(process.cwd(), params.config)) : {};
34
- const options = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, defaultOptions), configFile), params), {}, {
35
- headers: (0, _addSequenceHeader.default)(params.headers || (0, _headers.getHeadersConfig)(params.header))
36
- });
37
-
38
- // Validation
39
- if (!options.spaceId) {
40
- throw new Error('The `spaceId` option is required.');
41
- }
42
- if (!options.managementToken) {
43
- throw new Error('The `managementToken` option is required.');
44
- }
45
- if (!options.contentFile && !options.content) {
46
- throw new Error('Either the `contentFile` or `content` option are required.');
47
- }
48
- if (options.contentModelOnly && options.skipContentModel) {
49
- throw new Error('`contentModelOnly` and `skipContentModel` cannot be used together');
50
- }
51
- if (options.skipLocales && !options.contentModelOnly) {
52
- throw new Error('`skipLocales` can only be used together with `contentModelOnly`');
53
- }
54
- const proxySimpleExp = /.+:\d+/;
55
- const proxyAuthExp = /.+:.+@.+:\d+/;
56
- if (typeof options.proxy === 'string' && options.proxy && !(proxySimpleExp.test(options.proxy) || proxyAuthExp.test(options.proxy))) {
57
- throw new Error('Please provide the proxy config in the following format:\nhost:port or user:password@host:port');
58
- }
59
- options.startTime = new Date();
60
- if (!options.errorLogFile) {
61
- options.errorLogFile = (0, _path.resolve)(process.cwd(), `contentful-import-error-log-${options.spaceId}-${(0, _format.default)(options.startTime, "yyyy-MM-dd'T'HH-mm-ss")}.json`);
62
- } else {
63
- options.errorLogFile = (0, _path.resolve)(process.cwd(), options.errorLogFile);
64
- }
65
- options.accessToken = options.managementToken;
66
- if (!options.content) {
67
- // using a stream parser allows input files > 512 MB
68
- const fileStream = _fs.default.createReadStream(options.contentFile, {
69
- encoding: 'utf8'
70
- });
71
- options.content = await (0, _jsonExt.parseChunked)(fileStream);
72
- }
73
-
74
- // Clean up content to only include supported entity types
75
- Object.keys(options.content).forEach(type => {
76
- if (SUPPORTED_ENTITY_TYPES.indexOf(type) === -1) {
77
- delete options.content[type];
78
- }
79
- });
80
- SUPPORTED_ENTITY_TYPES.forEach(type => {
81
- options.content[type] = options.content[type] || [];
82
- });
83
- if (typeof options.proxy === 'string') {
84
- options.proxy = (0, _proxy.proxyStringToObject)(options.proxy);
85
- }
86
- if (!options.rawProxy && options.proxy) {
87
- options.httpsAgent = (0, _proxy.agentFromProxy)(options.proxy);
88
- delete options.proxy;
89
- }
90
- options.application = options.managementApplication || `contentful.import/${_package.version}`;
91
- options.feature = options.managementFeature || 'library-import';
92
- return options;
93
- }
94
- module.exports = exports.default;
@@ -1,155 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = getDestinationData;
7
- var _bluebird = _interopRequireDefault(require("bluebird"));
8
- var _logging = require("contentful-batch-libs/dist/logging");
9
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
11
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
12
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
13
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
14
- function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
15
- const BATCH_CHAR_LIMIT = 1990;
16
- const BATCH_SIZE_LIMIT = 100;
17
- const METHODS = {
18
- contentTypes: {
19
- name: 'content types',
20
- method: 'getContentTypes'
21
- },
22
- locales: {
23
- name: 'locales',
24
- method: 'getLocales'
25
- },
26
- entries: {
27
- name: 'entries',
28
- method: 'getEntries'
29
- },
30
- assets: {
31
- name: 'assets',
32
- method: 'getAssets'
33
- }
34
- };
35
- async function batchedIdQuery({
36
- environment,
37
- type,
38
- ids,
39
- requestQueue
40
- }) {
41
- const method = METHODS[type].method;
42
- const entityTypeName = METHODS[type].name;
43
- const batches = getIdBatches(ids);
44
- let totalFetched = 0;
45
- const allPendingResponses = batches.map(idBatch => {
46
- // TODO: add batch count to indicate that it's running
47
- return requestQueue.add(async () => {
48
- const response = await environment[method]({
49
- 'sys.id[in]': idBatch,
50
- limit: idBatch.split(',').length
51
- });
52
- totalFetched = totalFetched + response.items.length;
53
- _logging.logEmitter.emit('info', `Fetched ${totalFetched} of ${response.total} ${entityTypeName}`);
54
- return response.items;
55
- });
56
- });
57
- const responses = await _bluebird.default.all(allPendingResponses);
58
- return responses.flat();
59
- }
60
- function getIdBatches(ids) {
61
- const batches = [];
62
- let currentBatch = '';
63
- let currentSize = 0;
64
- while (ids.length > 0) {
65
- const id = ids.splice(0, 1);
66
- currentBatch += id;
67
- currentSize = currentSize + 1;
68
- if (currentSize === BATCH_SIZE_LIMIT || currentBatch.length > BATCH_CHAR_LIMIT || ids.length === 0) {
69
- batches.push(currentBatch);
70
- currentBatch = '';
71
- currentSize = 0;
72
- } else {
73
- currentBatch += ',';
74
- }
75
- }
76
- return batches;
77
- }
78
-
79
- /**
80
- * Gets content from a space which will have content copied to it, based on a
81
- * collection of existing content.
82
- *
83
- * Only the supplied entry/asset/contentType/locale IDs will be retrieved.
84
- * All tags will be retrieved.
85
- *
86
- */
87
-
88
- async function getDestinationData({
89
- client,
90
- spaceId,
91
- environmentId,
92
- sourceData,
93
- contentModelOnly,
94
- skipLocales,
95
- skipContentModel,
96
- requestQueue
97
- }) {
98
- const space = await client.getSpace(spaceId);
99
- const environment = await space.getEnvironment(environmentId);
100
- const result = {
101
- contentTypes: [],
102
- tags: [],
103
- locales: [],
104
- entries: [],
105
- assets: []
106
- };
107
-
108
- // Make sure all required properties are available and at least an empty array
109
- sourceData = _objectSpread(_objectSpread({}, result), sourceData);
110
- if (!skipContentModel) {
111
- const contentTypeIds = sourceData.contentTypes.map(e => e.sys.id);
112
- result.contentTypes = batchedIdQuery({
113
- environment,
114
- type: 'contentTypes',
115
- ids: contentTypeIds,
116
- requestQueue
117
- });
118
- if (!skipLocales) {
119
- const localeIds = sourceData.locales.map(e => e.sys.id);
120
- result.locales = batchedIdQuery({
121
- environment,
122
- type: 'locales',
123
- ids: localeIds,
124
- requestQueue
125
- });
126
- }
127
- }
128
-
129
- // include tags even if contentModelOnly = true
130
- result.tags = environment.getTags().then(response => response.items).catch(e => {
131
- // users without access to Tags will get 404
132
- // if they dont have access, remove tags array so they're not handled in future steps
133
- delete result.tags;
134
- });
135
- if (contentModelOnly) {
136
- return _bluebird.default.props(result);
137
- }
138
- const entryIds = sourceData.entries.map(e => e.sys.id);
139
- const assetIds = sourceData.assets.map(e => e.sys.id);
140
- result.entries = batchedIdQuery({
141
- environment,
142
- type: 'entries',
143
- ids: entryIds,
144
- requestQueue
145
- });
146
- result.assets = batchedIdQuery({
147
- environment,
148
- type: 'assets',
149
- ids: assetIds,
150
- requestQueue
151
- });
152
- result.webhooks = [];
153
- return _bluebird.default.props(result);
154
- }
155
- module.exports = exports.default;
@@ -1,25 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = initClient;
7
- var _contentfulManagement = require("contentful-management");
8
- var _logging = require("contentful-batch-libs/dist/logging");
9
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
10
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
11
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
12
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
13
- function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
14
- function logHandler(level, data) {
15
- _logging.logEmitter.emit(level, data);
16
- }
17
- function initClient(opts) {
18
- const defaultOpts = {
19
- timeout: 30000,
20
- logHandler
21
- };
22
- const config = _objectSpread(_objectSpread({}, defaultOpts), opts);
23
- return (0, _contentfulManagement.createClient)(config);
24
- }
25
- module.exports = exports.default;
@@ -1,83 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.getAssetStreamForURL = getAssetStreamForURL;
7
- exports.processAssets = processAssets;
8
- var _fs = _interopRequireDefault(require("fs"));
9
- var _path = require("path");
10
- var _util = require("util");
11
- var _getEntityName = _interopRequireDefault(require("contentful-batch-libs/dist/get-entity-name"));
12
- var _logging = require("contentful-batch-libs/dist/logging");
13
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
- const stat = (0, _util.promisify)(_fs.default.stat);
15
- async function getAssetStreamForURL(url, assetsDirectory) {
16
- const [, assetPath] = url.split('//');
17
- const filePath = (0, _path.join)(assetsDirectory, assetPath);
18
- try {
19
- await stat(filePath);
20
- return _fs.default.createReadStream(filePath);
21
- } catch (err) {
22
- const error = new Error('Cannot open asset from filesystem');
23
- error.filePath = filePath;
24
- throw error;
25
- }
26
- }
27
- async function processAssetForLocale(locale, asset, processingOptions) {
28
- try {
29
- return await asset.processForLocale(locale, processingOptions);
30
- } catch (err) {
31
- err.entity = asset;
32
- _logging.logEmitter.emit('error', err);
33
- throw err;
34
- }
35
- }
36
-
37
- // From
38
- // https://stackoverflow.com/questions/67339630/how-to-get-last-resolved-promise-from-a-list-of-resolved-promises-in-javascript
39
- async function lastResult(promises) {
40
- if (!promises.length) throw new RangeError('No last result from no promises');
41
- const results = [];
42
- await Promise.all(promises.map(p => p.then(v => {
43
- results.push(v);
44
- })));
45
- return results[results.length - 1];
46
- }
47
- async function processAssets({
48
- assets,
49
- timeout,
50
- retryLimit,
51
- requestQueue
52
- }) {
53
- const processingOptions = Object.assign({}, timeout && {
54
- processingCheckWait: timeout
55
- }, retryLimit && {
56
- processingCheckRetry: retryLimit
57
- });
58
- const pendingProcessingAssets = assets.map(async asset => {
59
- _logging.logEmitter.emit('info', `Processing Asset ${(0, _getEntityName.default)(asset)}`);
60
-
61
- // We want to do what processForAllLocale does, but as the rate
62
- // limit is only enforced if we have a dedicated requestQueue item
63
- // for every processForLocale call, we need to duplicate the logic
64
- // here
65
- const locales = Object.keys(asset.fields.file || {});
66
- let latestAssetVersion = asset;
67
- try {
68
- // The last resolved promise will return the most up to date asset
69
- // version which we need for next import steps (e.g. publishing)
70
- latestAssetVersion = await lastResult(locales.map(locale => {
71
- return requestQueue.add(() => processAssetForLocale(locale, asset, processingOptions));
72
- }));
73
- } catch (err) {
74
- // Handle any error that arises during the processing of any locale
75
- return null;
76
- }
77
- return latestAssetVersion;
78
- });
79
- const potentiallyProcessedAssets = await Promise.all(pendingProcessingAssets);
80
-
81
- // This filters out all process attempts which failed
82
- return potentiallyProcessedAssets.filter(asset => asset);
83
- }