@jungvonmatt/contentful-ssg 1.0.6 → 1.4.9

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/README.md CHANGED
@@ -217,6 +217,11 @@ Fetch all content entries and store them as yaml in the configured directory
217
217
  npx cssg fetch
218
218
  ```
219
219
 
220
+ To see all available command line options call
221
+ ```bash
222
+ npx cssg help fetch
223
+ ```
224
+
220
225
  ## Example configuration
221
226
 
222
227
  ### Grow
package/dist/cli.js CHANGED
@@ -14,10 +14,10 @@ import { getConfig, getEnvironmentConfig } from './lib/config.js';
14
14
  import { run } from './index.js';
15
15
  const env = dotenv.config();
16
16
  dotenvExpand(env);
17
- const parseArgs = (cmd) => ({
18
- environment: cmd.env,
19
- preview: Boolean(cmd.preview),
20
- verbose: Boolean(cmd.verbose),
17
+ const parseFetchArgs = (cmd) => ({
18
+ preview: cmd.preview,
19
+ verbose: cmd.verbose,
20
+ ignoreErrors: cmd.ignoreErrors,
21
21
  });
22
22
  const errorHandler = (error, silence) => {
23
23
  if (!silence) {
@@ -37,7 +37,7 @@ program
37
37
  .option('--typescript', 'Initialize typescript config')
38
38
  .action(actionRunner(async (cmd) => {
39
39
  const useTypescript = Boolean(cmd?.typescript ?? false);
40
- const config = await getConfig(parseArgs(cmd || {}));
40
+ const config = await getConfig();
41
41
  const verified = await askAll(config);
42
42
  const environmentConfig = getEnvironmentConfig();
43
43
  const filePath = path.join(process.cwd(), `contentful-ssg.config.${useTypescript ? 'ts' : 'js'}`);
@@ -88,8 +88,9 @@ program
88
88
  .description('Fetch content objects')
89
89
  .option('-p, --preview', 'Fetch with preview mode')
90
90
  .option('-v, --verbose', 'Verbose output')
91
+ .option('--ignore-errors', 'No error return code when transform has errors')
91
92
  .action(actionRunner(async (cmd) => {
92
- const config = await getConfig(parseArgs(cmd || {}));
93
+ const config = await getConfig(parseFetchArgs(cmd || {}));
93
94
  const verified = await askMissing(config);
94
95
  return run(verified);
95
96
  }));
package/dist/index.js CHANGED
@@ -54,10 +54,7 @@ export const run = async (config) => {
54
54
  {
55
55
  title: 'Before Hook',
56
56
  skip: (ctx) => !ctx.hooks.has('before'),
57
- task: async (ctx) => {
58
- const result = await ctx.hooks.before();
59
- ctx = { ...ctx, ...(result || {}) };
60
- },
57
+ task: async (ctx) => ctx.hooks.before(),
61
58
  },
62
59
  {
63
60
  title: 'Writing files',
@@ -109,10 +106,7 @@ export const run = async (config) => {
109
106
  {
110
107
  title: 'After Hook',
111
108
  skip: (ctx) => !ctx.hooks.has('after'),
112
- task: async (ctx) => {
113
- const result = await ctx.hooks.after();
114
- ctx = { ...ctx, ...(result || {}) };
115
- },
109
+ task: async (ctx) => ctx.hooks.after(),
116
110
  },
117
111
  {
118
112
  title: 'Cleanup',
@@ -122,4 +116,7 @@ export const run = async (config) => {
122
116
  const ctx = await tasks.run();
123
117
  await ctx.stats.print();
124
118
  console.log('\n---------------------------------------------');
119
+ if (ctx.stats.errors?.length && !config.ignoreErrors) {
120
+ process.exit(1);
121
+ }
125
122
  };
@@ -4,6 +4,7 @@ import { cosmiconfig } from 'cosmiconfig';
4
4
  import mergeOptionsModule from 'merge-options';
5
5
  import { dirname, isAbsolute, resolve } from 'path';
6
6
  import slash from 'slash';
7
+ import { reduceAsync } from './array.js';
7
8
  import { createRequire } from './create-require.js';
8
9
  import { isObject, removeEmpty } from './object.js';
9
10
  const typescriptLoader = async (filePath) => {
@@ -79,11 +80,12 @@ export const getEnvironmentConfig = (strict = true) => removeEmpty({
79
80
  previewAccessToken: process.env.CONTENTFUL_PREVIEW_TOKEN,
80
81
  accessToken: process.env.CONTENTFUL_DELIVERY_TOKEN,
81
82
  }, strict);
82
- export const getConfig = async (args) => {
83
+ export const getConfig = async (args = {}) => {
83
84
  const defaultOptions = {
84
85
  environmentId: 'master',
85
86
  host: 'api.contentful.com',
86
87
  directory: resolve(process.cwd(), 'content'),
88
+ managedDirectories: [],
87
89
  plugins: [],
88
90
  resolvedPlugins: [],
89
91
  };
@@ -140,5 +142,10 @@ export const getConfig = async (args) => {
140
142
  ...result.resolvedPlugins,
141
143
  ...(await Promise.all((result.plugins || []).map(async (plugin) => resolvePlugin(plugin, result)))),
142
144
  ];
143
- return { ...result, resolvedPlugins };
145
+ result.managedDirectories = [...result.managedDirectories, result.directory];
146
+ const hookedConfig = await reduceAsync(resolvedPlugins.filter((plugin) => typeof plugin.config === 'function'), async (prev, hooks) => {
147
+ const hook = hooks.config;
148
+ return hook(prev);
149
+ }, result);
150
+ return { ...hookedConfig, ...result, resolvedPlugins };
144
151
  };
@@ -26,7 +26,11 @@ export class FileManager {
26
26
  const ignorePatterns = await readFile(gitignore);
27
27
  this.ignore = ignore().add(ignorePatterns.toString('utf8'));
28
28
  }
29
- const existing = await globby([`${this.config.directory}/**/*.*`, `data/**/*.*`]);
29
+ const directories = [
30
+ ...new Set([...(this.config.managedDirectories || []), this.config.directory]),
31
+ ];
32
+ const globPattern = directories.map((directory) => resolve(this.config.rootDir || '', directory, '**/*.*'));
33
+ const existing = await globby(globPattern);
30
34
  this.files = new Set(existing.map((file) => resolve(file)));
31
35
  }
32
36
  async writeFile(file, data, options) {
package/dist/types.d.ts CHANGED
@@ -30,10 +30,12 @@ export interface ContentfulRcConfig {
30
30
  activeEnvironmentId: string;
31
31
  host: string;
32
32
  }
33
+ export declare type ConfigHook = (config: Config) => Config | Promise<Config>;
33
34
  export declare type RuntimeHook = (runtimeContext: RuntimeContext) => Promise<Partial<RuntimeContext>> | Partial<RuntimeContext> | void;
34
35
  export declare type TransformHook<T> = (transformContext: TransformContext, runtimeContext?: RuntimeContext, prev?: T) => Promise<T> | T;
35
36
  export declare type ValidateHook = (transformContext: TransformContext, runtimeContext?: RuntimeContext) => Promise<boolean> | boolean;
36
37
  export interface Hooks {
38
+ config?: ConfigHook;
37
39
  before?: RuntimeHook;
38
40
  after?: RuntimeHook;
39
41
  transform?: TransformHook<KeyValueMap>;
@@ -46,7 +48,9 @@ export interface Hooks {
46
48
  export declare type Config = Partial<ContentfulConfig> & Hooks & {
47
49
  rootDir?: string;
48
50
  directory: string;
51
+ managedDirectories?: string[];
49
52
  verbose?: boolean;
53
+ ignoreErrors?: boolean;
50
54
  plugins?: Array<[string, KeyValueMap] | PluginInfo | string>;
51
55
  resolvedPlugins?: Hooks[];
52
56
  preset?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jungvonmatt/contentful-ssg",
3
- "version": "1.0.6",
3
+ "version": "1.4.9",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "type": "module",
@@ -8,11 +8,14 @@
8
8
  "exports": {
9
9
  ".": "./dist/index.js",
10
10
  "./lib/object": "./dist/lib/object.js",
11
+ "./lib/config": "./dist/lib/config.js",
11
12
  "./lib/array": "./dist/lib/array.js",
12
13
  "./lib/utils": "./dist/lib/utils.js",
14
+ "./lib/ui": "./dist/lib/ui.js",
13
15
  "./lib/contentful": "./dist/lib/contentful.js",
14
16
  "./lib/hook-manager": "./dist/lib/hook-manager.js",
15
17
  "./lib/file-manager": "./dist/lib/file-manager.js",
18
+ "./converter": "./dist/converter/index.js",
16
19
  "./converter/json": "./dist/converter/json.js",
17
20
  "./converter/yaml": "./dist/converter/yaml.js",
18
21
  "./converter/toml": "./dist/converter/toml.js",
@@ -27,6 +30,12 @@
27
30
  "lib/utils": [
28
31
  "./dist/lib/utils.d.ts"
29
32
  ],
33
+ "lib/ui": [
34
+ "./dist/lib/ui.d.ts"
35
+ ],
36
+ "lib/config": [
37
+ "./dist/lib/config.d.ts"
38
+ ],
30
39
  "lib/object": [
31
40
  "./dist/lib/object.d.ts"
32
41
  ],
@@ -42,6 +51,9 @@
42
51
  "lib/file-manager": [
43
52
  "./dist/lib/file-manager.d.ts"
44
53
  ],
54
+ "converter": [
55
+ "./dist/converter/index.d.ts"
56
+ ],
45
57
  "converter/json": [
46
58
  "./dist/converter/json.d.ts"
47
59
  ],
@@ -79,7 +91,7 @@
79
91
  "dist"
80
92
  ],
81
93
  "author": "Jung von Matt TECH GmbH",
82
- "license": "ISC",
94
+ "license": "MIT",
83
95
  "dependencies": {
84
96
  "@contentful/rich-text-html-renderer": "^15.6.2",
85
97
  "@contentful/rich-text-types": "^15.6.2",
@@ -143,5 +155,5 @@
143
155
  "module": "es2020"
144
156
  }
145
157
  },
146
- "gitHead": "72fea365aa247c8942d01c499becf8548874b09d"
158
+ "gitHead": "17ccdcf1aedc0eea54740aa71279e5bd1cb77699"
147
159
  }
package/src/cli.ts CHANGED
@@ -15,15 +15,15 @@ import { omitKeys } from './lib/object.js';
15
15
 
16
16
  import { getConfig, getEnvironmentConfig } from './lib/config.js';
17
17
  import { run } from './index.js';
18
- import { ContentfulConfig } from './types.js';
18
+ import { Config, ContentfulConfig } from './types.js';
19
19
 
20
20
  const env = dotenv.config();
21
21
  dotenvExpand(env);
22
22
 
23
- const parseArgs = (cmd) => ({
24
- environment: cmd.env as string,
25
- preview: Boolean(cmd.preview),
26
- verbose: Boolean(cmd.verbose),
23
+ const parseFetchArgs = (cmd): Partial<Config> => ({
24
+ preview: cmd.preview as boolean,
25
+ verbose: cmd.verbose as boolean,
26
+ ignoreErrors: cmd.ignoreErrors as boolean,
27
27
  });
28
28
 
29
29
  type CommandError = Error & {
@@ -54,7 +54,7 @@ program
54
54
  .action(
55
55
  actionRunner(async (cmd) => {
56
56
  const useTypescript = Boolean(cmd?.typescript ?? false);
57
- const config = await getConfig(parseArgs(cmd || {}));
57
+ const config = await getConfig();
58
58
  const verified = await askAll(config);
59
59
 
60
60
  const environmentConfig = getEnvironmentConfig();
@@ -148,9 +148,10 @@ program
148
148
  .description('Fetch content objects')
149
149
  .option('-p, --preview', 'Fetch with preview mode')
150
150
  .option('-v, --verbose', 'Verbose output')
151
+ .option('--ignore-errors', 'No error return code when transform has errors')
151
152
  .action(
152
153
  actionRunner(async (cmd) => {
153
- const config = await getConfig(parseArgs(cmd || {}));
154
+ const config = await getConfig(parseFetchArgs(cmd || {}));
154
155
  const verified = await askMissing(config);
155
156
 
156
157
  return run(verified);
package/src/index.test.ts CHANGED
@@ -86,4 +86,62 @@ describe('Run', () => {
86
86
  expect(output).toMatch(`${chalk.cyan(0)} entries skipped due to validation issues`);
87
87
  expect(output).toMatch(`${chalk.red(0)} errors`);
88
88
  });
89
+
90
+ test('fails on exception before/after', async () => {
91
+ console.log = jest.fn();
92
+ const mockError = jest.fn().mockImplementation(() => {
93
+ throw new Error();
94
+ });
95
+
96
+ await expect(async () => {
97
+ await run({
98
+ directory: 'test',
99
+ before: mockError,
100
+ });
101
+ }).rejects.toThrowError();
102
+
103
+ await expect(async () => {
104
+ await run({
105
+ directory: 'test',
106
+ after: mockError,
107
+ });
108
+ }).rejects.toThrowError();
109
+ });
110
+
111
+ test('fails on transform exception', async () => {
112
+ console.log = jest.fn();
113
+ const mockExit = jest.spyOn(process, 'exit').mockImplementation((number) => {
114
+ throw new Error('process.exit: ' + number);
115
+ });
116
+
117
+ await expect(async () => {
118
+ await run({
119
+ directory: 'test',
120
+ transform: async () => {
121
+ throw new Error();
122
+ },
123
+ });
124
+ }).rejects.toThrowError();
125
+
126
+ expect(mockExit).toHaveBeenCalledWith(1);
127
+ mockExit.mockRestore();
128
+ });
129
+
130
+ test('does not fail on transform exception with ignoreErrors option', async () => {
131
+ console.log = jest.fn();
132
+ const mockExit = jest.spyOn(process, 'exit').mockImplementation((number) => {
133
+ throw new Error('process.exit: ' + number);
134
+ });
135
+
136
+ await run({
137
+ directory: 'test',
138
+ ignoreErrors: true,
139
+ transform: async () => {
140
+ throw new Error();
141
+ },
142
+ });
143
+
144
+ expect(mockExit).toBeCalledTimes(0);
145
+ mockExit.mockRestore();
146
+ });
89
147
  });
package/src/index.ts CHANGED
@@ -73,10 +73,7 @@ export const run = async (config: Config): Promise<void> => {
73
73
  {
74
74
  title: 'Before Hook',
75
75
  skip: (ctx) => !ctx.hooks.has('before'),
76
- task: async (ctx) => {
77
- const result = await ctx.hooks.before();
78
- ctx = { ...ctx, ...(result || {}) };
79
- },
76
+ task: async (ctx) => ctx.hooks.before(),
80
77
  },
81
78
  {
82
79
  title: 'Writing files',
@@ -135,12 +132,8 @@ export const run = async (config: Config): Promise<void> => {
135
132
  {
136
133
  title: 'After Hook',
137
134
  skip: (ctx) => !ctx.hooks.has('after'),
138
- task: async (ctx) => {
139
- const result = await ctx.hooks.after();
140
- ctx = { ...ctx, ...(result || {}) };
141
- },
135
+ task: async (ctx) => ctx.hooks.after(),
142
136
  },
143
-
144
137
  {
145
138
  title: 'Cleanup',
146
139
  task: async (ctx) => ctx.fileManager.cleanup(),
@@ -152,4 +145,8 @@ export const run = async (config: Config): Promise<void> => {
152
145
  const ctx = await tasks.run();
153
146
  await ctx.stats.print();
154
147
  console.log('\n---------------------------------------------');
148
+
149
+ if (ctx.stats.errors?.length && !config.ignoreErrors) {
150
+ process.exit(1);
151
+ }
155
152
  };
package/src/lib/config.ts CHANGED
@@ -14,6 +14,7 @@ import type {
14
14
  PluginInfo,
15
15
  PluginModule,
16
16
  } from '../types.js';
17
+ import { reduceAsync } from './array.js';
17
18
  import { createRequire } from './create-require.js';
18
19
  import { isObject, removeEmpty } from './object.js';
19
20
 
@@ -121,11 +122,12 @@ export const getEnvironmentConfig = (strict = true): ContentfulConfig =>
121
122
  * Get configuration
122
123
  * @param {Object} args
123
124
  */
124
- export const getConfig = async (args?: Partial<Config>): Promise<Config> => {
125
+ export const getConfig = async (args: Partial<Config> = {}): Promise<Config> => {
125
126
  const defaultOptions: Config = {
126
127
  environmentId: 'master',
127
128
  host: 'api.contentful.com',
128
129
  directory: resolve(process.cwd(), 'content'),
130
+ managedDirectories: [],
129
131
  plugins: [],
130
132
  resolvedPlugins: [],
131
133
  };
@@ -197,5 +199,17 @@ export const getConfig = async (args?: Partial<Config>): Promise<Config> => {
197
199
  (result.plugins || []).map(async (plugin) => resolvePlugin(plugin, result))
198
200
  )),
199
201
  ];
200
- return { ...result, resolvedPlugins };
202
+
203
+ result.managedDirectories = [...result.managedDirectories, result.directory];
204
+
205
+ const hookedConfig = await reduceAsync(
206
+ resolvedPlugins.filter((plugin) => typeof plugin.config === 'function'),
207
+ async (prev: Config, hooks) => {
208
+ const hook = hooks.config;
209
+ return hook(prev);
210
+ },
211
+ result
212
+ );
213
+
214
+ return { ...hookedConfig, ...result, resolvedPlugins };
201
215
  };
@@ -39,8 +39,15 @@ export class FileManager {
39
39
  this.ignore = ignore().add(ignorePatterns.toString('utf8'));
40
40
  }
41
41
 
42
+ const directories = [
43
+ ...new Set([...(this.config.managedDirectories || []), this.config.directory]),
44
+ ];
45
+
46
+ const globPattern = directories.map((directory) =>
47
+ resolve(this.config.rootDir || '', directory, '**/*.*')
48
+ );
42
49
  // Create set of existing files
43
- const existing = await globby([`${this.config.directory}/**/*.*`, `data/**/*.*`]);
50
+ const existing = await globby(globPattern);
44
51
 
45
52
  this.files = new Set(existing.map((file) => resolve(file)));
46
53
  }
package/src/types.ts CHANGED
@@ -52,6 +52,8 @@ export interface ContentfulRcConfig {
52
52
  host: string;
53
53
  }
54
54
 
55
+ export type ConfigHook = (config: Config) => Config | Promise<Config>;
56
+
55
57
  export type RuntimeHook = (
56
58
  runtimeContext: RuntimeContext
57
59
  ) => Promise<Partial<RuntimeContext>> | Partial<RuntimeContext> | void;
@@ -66,6 +68,7 @@ export type ValidateHook = (
66
68
  ) => Promise<boolean> | boolean;
67
69
 
68
70
  export interface Hooks {
71
+ config?: ConfigHook;
69
72
  before?: RuntimeHook;
70
73
  after?: RuntimeHook;
71
74
  transform?: TransformHook<KeyValueMap>;
@@ -80,7 +83,9 @@ export type Config = Partial<ContentfulConfig> &
80
83
  Hooks & {
81
84
  rootDir?: string;
82
85
  directory: string;
86
+ managedDirectories?: string[];
83
87
  verbose?: boolean;
88
+ ignoreErrors?: boolean;
84
89
  plugins?: Array<[string, KeyValueMap] | PluginInfo | string>;
85
90
  resolvedPlugins?: Hooks[];
86
91
  preset?: string;