exifreader 4.45.2 → 4.47.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/README.md CHANGED
@@ -613,9 +613,11 @@ const tags = await ExifReader.load(file, {
613
613
  #### Limiting decompressed metadata size
614
614
 
615
615
  To avoid excessive memory use from pathological compressed inputs, ExifReader
616
- caps the size of any single decompressed metadata block. The default limit is
617
- 128 MiB, which is well above any realistic legitimate value. You can override
618
- it via the `maxDecompressedSize` field on the `decompress` option (in bytes):
616
+ caps the total decompressed size of the compressed metadata blocks in a file.
617
+ The limit covers all blocks decompressed in one `load()` call together, not
618
+ each block on its own. The default limit is 128 MiB, which is well above any
619
+ realistic legitimate value. You can override it via the `maxDecompressedSize`
620
+ field on the `decompress` option (in bytes):
619
621
 
620
622
  ```javascript
621
623
  const tags = await ExifReader.load(file, {
@@ -626,10 +628,18 @@ const tags = await ExifReader.load(file, {
626
628
  });
627
629
  ```
628
630
 
629
- If a compressed block would expand beyond the limit, that block is skipped, a
630
- warning is logged via `console.warn`, and the rest of the tags are returned as
631
- usual. The limit applies to the built-in Compression Streams paths and to any
632
- result returned by a custom `brotli`/`deflate` function.
631
+ If a compressed block would take the total beyond the limit, that block and
632
+ every later compressed block are skipped, one warning is logged via
633
+ `console.warn`, and the rest of the tags are returned as usual. Blocks that
634
+ are decompressed at the same time, such as several PNG text chunks, can all be
635
+ skipped when together they go beyond the limit. The limit applies to the
636
+ built-in Compression Streams paths and to any result returned by a custom
637
+ `brotli`/`deflate` function. With `length: 'auto'`, each read attempt parses
638
+ the bytes fetched so far and has its own total.
639
+
640
+ With `async: true`, ExifReader decompresses at most the first 255 compressed
641
+ PNG text chunks (zTXt and compressed iTXt) of a file and skips later ones.
642
+ Uncompressed text chunks are not limited.
633
643
 
634
644
  #### Parsing XMP tags when not in a DOM environment
635
645
 
@@ -830,6 +840,38 @@ This reads the `exifreader` configuration from your `package.json`, rebuilds the
830
840
  library, and writes the result to `node_modules/exifreader/dist/exif-reader.js`.
831
841
  It works the same way with npm, yarn, and pnpm.
832
842
 
843
+ **Derive the configuration from your images.** Instead of writing the
844
+ configuration by hand, point `analyze` at a directory of sample images (or at
845
+ individual files):
846
+
847
+ ```bash
848
+ npx exifreader analyze ./samples
849
+ ```
850
+
851
+ It reads the images with the full library and prints the smallest `include`
852
+ configuration that reads everything found in them: the file formats, the Exif
853
+ and IPTC tags, and the XMP, ICC, Photoshop, maker note, MPF and thumbnail
854
+ groups. Add `--write` to put it in your `package.json`, replacing any
855
+ `include` or `exclude` section there, then run `npx exifreader build`. To
856
+ analyze and build in one step, and then check the result:
857
+
858
+ ```bash
859
+ npx exifreader build --auto ./samples --verify
860
+ ```
861
+
862
+ `--verify` (which also works without `--auto`) reads the images with both the
863
+ full library and the installed custom bundle and exits with an error listing
864
+ every difference.
865
+
866
+ The configuration covers exactly what the sample images contain, so use a
867
+ sample that is representative of the images your app reads. A format, tag or
868
+ group that is not in the samples is left out of the build. Pass every sample
869
+ in one run, since each run replaces the configuration instead of adding to it.
870
+ `build --auto` does not save the configuration. A later `npm ci` restores the
871
+ full bundle, and a plain `build`, `build --check` or `build --if-needed` reads
872
+ the configuration in `package.json` instead. For a lasting setup, run `analyze --write` once and then `build` (or
873
+ `build --if-needed` in a script). Use `build --auto` for one-off builds.
874
+
833
875
  **Re-run after every install.** A fresh `npm install`, `npm ci`, or upgrade
834
876
  restores the full bundle, so run `npx exifreader build` again afterwards. The
835
877
  most reliable approach is to wire it into your own build step, for example (in
@@ -837,10 +879,29 @@ your own `package.json`):
837
879
 
838
880
  ```json
839
881
  "scripts": {
840
- "prebuild": "exifreader build"
882
+ "prebuild": "exifreader build --if-needed"
841
883
  }
842
884
  ```
843
885
 
886
+ With `--if-needed` the rebuild is skipped when the installed bundle was already
887
+ built from the current configuration and exifreader version. Each custom build
888
+ records these in `node_modules/exifreader/dist/.exifreader-custom-build.json`.
889
+
890
+ To catch a stock or outdated bundle in CI, add a step that runs:
891
+
892
+ ```bash
893
+ npx exifreader build --check
894
+ ```
895
+
896
+ It never builds anything. It exits with a non-zero code when the installed
897
+ bundle is the stock full build or was built from a different configuration or
898
+ exifreader version, and with 0 when it is up to date or when no configuration is
899
+ found. `--check` and `--if-needed` only see the configuration source they are
900
+ given, so pass them the same one as the build: a project that builds with
901
+ `--config exifreader.json` checks with
902
+ `npx exifreader build --check --config exifreader.json`, since without it no
903
+ configuration is found and `--check` exits with 0.
904
+
844
905
  **Deprecated: automatic rebuild on install.** Older versions rebuilt the library
845
906
  automatically through an npm `postinstall` script, so a plain install or `npm
846
907
  rebuild exifreader` (or `yarn rebuild exifreader` with yarn 2+, or `yarn add
@@ -853,11 +914,16 @@ If you are using `vite`, you will need to [clear the dependency cache](https://v
853
914
  after a rebuild.
854
915
 
855
916
  **Advanced and monorepos.** Instead of the `package.json` configuration you can
856
- pass the same `include`/`exclude` object as JSON in the `EXIFREADER_CUSTOM_BUILD`
857
- environment variable, which takes priority over `package.json`. In a monorepo,
917
+ put the same `include`/`exclude` object in a JSON file and pass it with
918
+ `npx exifreader build --config <path>` (a relative path is resolved from the
919
+ current directory), or pass it as JSON in the `EXIFREADER_CUSTOM_BUILD`
920
+ environment variable. `--config` takes priority over `EXIFREADER_CUSTOM_BUILD`,
921
+ which takes priority over `package.json`. In a monorepo,
858
922
  `npx exifreader build` reads the configuration from the package you run it in,
859
- but a hoisted `node_modules/exifreader` is shared by every workspace package, so
860
- there is only one custom bundle and the last build wins.
923
+ but a hoisted `node_modules/exifreader` (or, with pnpm, the copy in the
924
+ workspace root's `node_modules/.pnpm`) is shared by every workspace package, so
925
+ there is only one custom bundle and the last build wins. The CLI prints a
926
+ warning when you build from a workspace package into such a shared copy.
861
927
 
862
928
  If you're using the include pattern config, remember to include everything you
863
929
  want to use. If you want `xmp` and don't specify any file types, you will get
@@ -17,18 +17,6 @@ const modules = {
17
17
  ]
18
18
  };
19
19
 
20
- const filterTagsVisitor = {
21
- ObjectProperty(path, opts) {
22
- if (path.node.key.type === 'NumericLiteral') {
23
- if ((path.node.value.type === 'StringLiteral') && !opts.include.includes(path.node.value.value.toLowerCase())) {
24
- path.remove();
25
- } else if (path.node.value.type === 'ObjectExpression' && !tagNameIsIncluded(path, path.get('value'), opts.include)) {
26
- path.remove();
27
- }
28
- }
29
- }
30
- };
31
-
32
20
  const parseNameFunctionVisitor = {
33
21
  ReturnStatement(path, opts) {
34
22
  if ((path.node.argument.type === 'StringLiteral') && opts.include.includes(path.node.argument.value.toLowerCase())) {
@@ -59,8 +47,9 @@ module.exports = function TagFilter() {
59
47
  visitor: {
60
48
  ExportDefaultDeclaration(path, state) {
61
49
  const type = getFileModuleType(state.filename);
62
- if (type && Array.isArray(state.opts.include[type])) {
63
- path.traverse(filterTagsVisitor, {include: state.opts.include[type].map((tagName) => tagName.toLowerCase())});
50
+ const declarationPath = path.get('declaration');
51
+ if (type && Array.isArray(state.opts.include[type]) && declarationPath.isObjectExpression()) {
52
+ filterTagDictionary(declarationPath, state.opts.include[type].map((tagName) => tagName.toLowerCase()));
64
53
  }
65
54
  }
66
55
  }
@@ -81,3 +70,23 @@ function getFileModuleType(filename) {
81
70
  function endsWith(string, suffix) {
82
71
  return new RegExp(`${suffix}$`).test(string);
83
72
  }
73
+
74
+ // Walks only the dictionary's own entries: the lookup tables inside a tag's
75
+ // description share the numeric-key shape and must stay.
76
+ function filterTagDictionary(dictionaryPath, include) {
77
+ for (const propertyPath of dictionaryPath.get('properties')) {
78
+ if (!propertyPath.isObjectProperty()) {
79
+ continue;
80
+ }
81
+ const valuePath = propertyPath.get('value');
82
+ if (propertyPath.node.key.type === 'NumericLiteral') {
83
+ if (valuePath.isStringLiteral() && !include.includes(valuePath.node.value.toLowerCase())) {
84
+ propertyPath.remove();
85
+ } else if (valuePath.isObjectExpression() && !tagNameIsIncluded(propertyPath, valuePath, include)) {
86
+ propertyPath.remove();
87
+ }
88
+ } else if (valuePath.isObjectExpression()) {
89
+ filterTagDictionary(valuePath, include);
90
+ }
91
+ }
92
+ }
package/bin/analyze.js ADDED
@@ -0,0 +1,345 @@
1
+ /* This Source Code Form is subject to the terms of the Mozilla Public
2
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
+
5
+ const path = require('path');
6
+ const url = require('url');
7
+
8
+ const EXIFREADER_ROOT_DIR = path.join(__dirname, '..');
9
+
10
+ const FORMATS = ['jpeg', 'tiff', 'png', 'heic', 'avif', 'jxl', 'webp', 'gif'];
11
+ const FORMAT_NAMES = {
12
+ jpeg: 'JPEG',
13
+ tiff: 'TIFF',
14
+ png: 'PNG',
15
+ heic: 'HEIC',
16
+ avif: 'AVIF',
17
+ jxl: 'JPEG XL',
18
+ webp: 'WebP',
19
+ gif: 'GIF'
20
+ };
21
+ const MODULE_ORDER = FORMATS.concat(['file', 'jfif', 'png_file', 'exif', 'iptc', 'xmp', 'icc', 'photoshop', 'maker_notes', 'mpf', 'thumbnail']);
22
+ const GROUP_MODULES = {
23
+ jfif: 'jfif',
24
+ pngFile: 'png_file',
25
+ xmp: 'xmp',
26
+ icc: 'icc',
27
+ mpf: 'mpf',
28
+ photoshop: 'photoshop',
29
+ makerNotes: 'maker_notes'
30
+ };
31
+ const THUMBNAIL_NON_TAG_KEYS = ['image', 'base64', 'type'];
32
+ const GPS_POINTER = 'GPS Info IFD Pointer';
33
+ const INTEROPERABILITY_POINTER = 'Interoperability IFD Pointer';
34
+
35
+ module.exports = {
36
+ collectImagePaths,
37
+ loadFullParser,
38
+ resolveDomParser,
39
+ analyzeImages,
40
+ deriveConfig,
41
+ writeConfigToPackageJson
42
+ };
43
+
44
+ /**
45
+ * Expand the named files and directories into a sorted list of files.
46
+ * Directories are walked recursively, following symlinks.
47
+ *
48
+ * @param {string[]} paths Absolute paths of files and directories.
49
+ * @param {Object} fs Node's fs module or a stand-in with statSync, readdirSync
50
+ * and realpathSync.
51
+ * @returns {{paths: string[], skipped: {path: string, message: string}[]}}
52
+ * Throws when a named path cannot be read. Entries found during the walk
53
+ * that cannot be read go to skipped.
54
+ */
55
+ function collectImagePaths(paths, fs) {
56
+ const walk = {fs, files: new Set(), skipped: [], visitedDirectories: new Set()};
57
+ for (const namedPath of paths) {
58
+ const resolvedPath = path.resolve(namedPath);
59
+ let stats;
60
+ try {
61
+ stats = fs.statSync(resolvedPath);
62
+ } catch (error) {
63
+ throw new Error(`Could not read ${resolvedPath}: ${error.message}`);
64
+ }
65
+ addEntry(resolvedPath, stats, walk);
66
+ }
67
+ return {paths: Array.from(walk.files).sort(), skipped: walk.skipped};
68
+ }
69
+
70
+ function addEntry(entryPath, stats, walk) {
71
+ if (!stats.isDirectory()) {
72
+ walk.files.add(entryPath);
73
+ return;
74
+ }
75
+ try {
76
+ const realDirectory = walk.fs.realpathSync(entryPath);
77
+ if (walk.visitedDirectories.has(realDirectory)) {
78
+ return;
79
+ }
80
+ walk.visitedDirectories.add(realDirectory);
81
+ for (const name of walk.fs.readdirSync(entryPath)) {
82
+ addWalkedEntry(path.join(entryPath, name), walk);
83
+ }
84
+ } catch (error) {
85
+ walk.skipped.push({path: entryPath, message: error.message});
86
+ }
87
+ }
88
+
89
+ function addWalkedEntry(entryPath, walk) {
90
+ let stats;
91
+ try {
92
+ stats = walk.fs.statSync(entryPath);
93
+ } catch (error) {
94
+ walk.skipped.push({path: entryPath, message: error.message});
95
+ return;
96
+ }
97
+ addEntry(entryPath, stats, walk);
98
+ }
99
+
100
+ /**
101
+ * Load the ExifReader ES module source, which always has every module, unlike
102
+ * dist/exif-reader.js which may be a custom build.
103
+ *
104
+ * @returns {Promise<Object>} The ExifReader default export.
105
+ */
106
+ function loadFullParser() {
107
+ const sourceUrl = url.pathToFileURL(path.join(EXIFREADER_ROOT_DIR, 'src', 'exif-reader.js')).href;
108
+ return import(sourceUrl).then((sourceModule) => sourceModule.default);
109
+ }
110
+
111
+ /**
112
+ * Create the xmldom DOM parser the way src/dom-parser.js does, resolving the
113
+ * package from the exifreader directory first and then from cwd.
114
+ *
115
+ * @param {string} cwd The directory the command runs in.
116
+ * @param {Object} [options] Stand-ins for require.resolve (resolve) and
117
+ * require (require).
118
+ * @returns {Object|undefined} The DOM parser, or undefined when xmldom is not
119
+ * available.
120
+ */
121
+ function resolveDomParser(cwd, options) {
122
+ options = options || {};
123
+ const resolve = options.resolve || require.resolve;
124
+ const load = options.require || require;
125
+ try {
126
+ const {DOMParser, onErrorStopParsing} = load(resolve('@xmldom/xmldom', {paths: [EXIFREADER_ROOT_DIR, cwd]}));
127
+ return new DOMParser({onError: onErrorStopParsing});
128
+ } catch (error) {
129
+ return undefined;
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Parse each file with the given parser into expanded tags.
135
+ *
136
+ * @param {string[]} paths Absolute file paths.
137
+ * @param {{fs: Object, parser: Object, domParser: (Object|undefined)}} deps
138
+ * @returns {Promise<{results: {path: string, tags: Object}[], skipped: {path: string, message: string}[]}>}
139
+ * Files that cannot be read or parsed go to skipped.
140
+ */
141
+ async function analyzeImages(paths, deps) {
142
+ const results = [];
143
+ const skipped = [];
144
+ for (const filePath of paths) {
145
+ try {
146
+ const buffer = deps.fs.readFileSync(filePath);
147
+ const tags = await deps.parser.load(buffer, {expanded: true, async: true, domParser: deps.domParser});
148
+ results.push({path: filePath, tags});
149
+ } catch (error) {
150
+ skipped.push({path: filePath, message: error.message});
151
+ }
152
+ }
153
+ return {results, skipped};
154
+ }
155
+
156
+ /**
157
+ * Derive the smallest include configuration that reads everything found in
158
+ * the given parse results.
159
+ *
160
+ * @param {Object[]} results Expanded ExifReader results.
161
+ * @returns {{config: {include: Object}, fileTypes: string[], warnings: string[]}}
162
+ */
163
+ function deriveConfig(results) {
164
+ const found = {modules: new Set(), exifNames: new Set(), iptcNames: new Set(), fileTypes: new Set(), exifArray: false};
165
+ for (const tags of results) {
166
+ observeResult(tags, found);
167
+ }
168
+
169
+ const modules = {};
170
+ for (const moduleName of found.modules) {
171
+ modules[moduleName] = true;
172
+ }
173
+ if (found.modules.has('iptc')) {
174
+ modules.iptc = Array.from(found.iptcNames).sort();
175
+ }
176
+ if (found.exifArray) {
177
+ modules.exif = withoutInjectedNames(Array.from(found.exifNames), modules).sort();
178
+ }
179
+
180
+ const include = {};
181
+ for (const moduleName of MODULE_ORDER.filter((name) => name in modules)) {
182
+ include[moduleName] = modules[moduleName];
183
+ }
184
+
185
+ return {
186
+ config: {include},
187
+ fileTypes: Array.from(found.fileTypes).sort(),
188
+ warnings: warningsFor(found.modules)
189
+ };
190
+ }
191
+
192
+ function observeResult(tags, found) {
193
+ const fileType = tags.file.FileType.value;
194
+ found.fileTypes.add(fileType);
195
+ if (FORMATS.includes(fileType)) {
196
+ found.modules.add(fileType);
197
+ }
198
+ if (fileType === 'jpeg' && Object.keys(tags.file).some((name) => name !== 'FileType')) {
199
+ found.modules.add('file');
200
+ }
201
+ for (const group of Object.keys(GROUP_MODULES)) {
202
+ if (group in tags) {
203
+ found.modules.add(GROUP_MODULES[group]);
204
+ }
205
+ }
206
+ if ('iptc' in tags) {
207
+ found.modules.add('iptc');
208
+ addNames(found.iptcNames, Object.keys(tags.iptc));
209
+ }
210
+ if ('exif' in tags) {
211
+ found.exifArray = true;
212
+ addNames(found.exifNames, Object.keys(tags.exif).filter((name) => name !== 'Thumbnail'));
213
+ }
214
+ observeThumbnail(tags.Thumbnail, found);
215
+ observeThumbnail(tags.exif && tags.exif.Thumbnail, found);
216
+ if ('makerNotes' in tags || 'photoshop' in tags || (fileType === 'tiff' && ['iptc', 'xmp', 'icc'].some((group) => group in tags))) {
217
+ found.exifArray = true;
218
+ }
219
+ }
220
+
221
+ function addNames(names, newNames) {
222
+ for (const name of newNames) {
223
+ names.add(name);
224
+ }
225
+ }
226
+
227
+ function observeThumbnail(thumbnail, found) {
228
+ if (thumbnail === undefined) {
229
+ return;
230
+ }
231
+ found.modules.add('thumbnail');
232
+ found.exifArray = true;
233
+ addNames(found.exifNames, Object.keys(thumbnail).filter((name) => !THUMBNAIL_NON_TAG_KEYS.includes(name)));
234
+ }
235
+
236
+ // Mirrors the tags webpack.config.js getConfig() adds to an exif array, so the
237
+ // derived array does not repeat them. A pointer is only left out when another
238
+ // name will make the build add it.
239
+ function withoutInjectedNames(names, modules) {
240
+ const otherNames = names.filter((name) => name !== GPS_POINTER && name !== INTEROPERABILITY_POINTER);
241
+ const injected = ['Exif IFD Pointer'];
242
+ if (otherNames.some((name) => name.toLowerCase().startsWith('gps'))) {
243
+ injected.push(GPS_POINTER);
244
+ }
245
+ if (otherNames.some((name) => /^(interoperability|relatedimage)/i.test(name))) {
246
+ injected.push(INTEROPERABILITY_POINTER);
247
+ }
248
+ if (modules.iptc) {
249
+ injected.push('IPTC-NAA');
250
+ }
251
+ if (modules.xmp) {
252
+ injected.push('ApplicationNotes');
253
+ }
254
+ if (modules.icc) {
255
+ injected.push('ICC_Profile');
256
+ }
257
+ if (modules.photoshop) {
258
+ injected.push('ImageSourceData', 'PhotoshopSettings');
259
+ }
260
+ if (modules.thumbnail) {
261
+ injected.push('JPEGInterchangeFormat', 'JPEGInterchangeFormatLength');
262
+ }
263
+ if (modules.maker_notes) {
264
+ injected.push('MakerNote', 'Make');
265
+ }
266
+ return names.filter((name) => !injected.includes(name));
267
+ }
268
+
269
+ function warningsFor(modules) {
270
+ const warnings = [];
271
+ const missingFormats = FORMATS.filter((format) => !modules.has(format)).map((format) => FORMAT_NAMES[format]);
272
+ if (missingFormats.length > 0) {
273
+ warnings.push(missingFormatsWarning(missingFormats));
274
+ }
275
+ warnings.push('Tags and metadata groups that do not appear in these images are left out of the build, so pass a '
276
+ + 'sample of every kind of image your app reads, all in one run.');
277
+ return warnings;
278
+ }
279
+
280
+ function missingFormatsWarning(names) {
281
+ if (names.length === 1) {
282
+ return `No ${names[0]} images were found, so the build will not read that format.`;
283
+ }
284
+ return `No ${names.slice(0, -1).join(', ')} or ${names[names.length - 1]} images were found, so the build `
285
+ + 'will not read those formats.';
286
+ }
287
+
288
+ /**
289
+ * Set the include section of the "exifreader" key in a package.json file,
290
+ * replacing any include or exclude section there and keeping everything else,
291
+ * including the indentation, line endings, trailing newline and a leading
292
+ * byte order mark.
293
+ *
294
+ * @param {string} filePath Path of the package.json file.
295
+ * @param {Object} include The include section to write.
296
+ * @param {Object} fs Node's fs module or a stand-in with readFileSync and
297
+ * writeFileSync.
298
+ * @returns {{created: boolean, replaced: (Object|undefined)}} created is true
299
+ * when there was no "exifreader" object. replaced holds the include and
300
+ * exclude sections that were replaced, if any. Throws when the file cannot
301
+ * be read or is not valid JSON.
302
+ */
303
+ function writeConfigToPackageJson(filePath, include, fs) {
304
+ const original = fs.readFileSync(filePath, 'utf8');
305
+ const byteOrderMark = original.startsWith('\uFEFF') ? '\uFEFF' : '';
306
+ const text = original.slice(byteOrderMark.length);
307
+ const packageJson = JSON.parse(text);
308
+
309
+ const indentMatch = /^([ \t]+)"/m.exec(text);
310
+ const indent = indentMatch ? indentMatch[1] : ' ';
311
+ const newline = text.includes('\r\n') ? '\r\n' : '\n';
312
+ const trailingNewline = text.endsWith('\n') ? newline : '';
313
+
314
+ const update = updatedSection(packageJson.exifreader, include);
315
+ packageJson.exifreader = update.section;
316
+
317
+ const json = JSON.stringify(packageJson, null, indent).replace(/\n/g, newline);
318
+ fs.writeFileSync(filePath, byteOrderMark + json + trailingNewline);
319
+ return {created: update.created, replaced: update.replaced};
320
+ }
321
+
322
+ function updatedSection(section, include) {
323
+ if (section === null || typeof section !== 'object' || Array.isArray(section)) {
324
+ return {section: {include}, created: true, replaced: undefined};
325
+ }
326
+
327
+ const entries = [];
328
+ const replaced = {};
329
+ let placed = false;
330
+ for (const [key, value] of Object.entries(section)) {
331
+ if (key !== 'include' && key !== 'exclude') {
332
+ entries.push([key, value]);
333
+ continue;
334
+ }
335
+ replaced[key] = value;
336
+ if (!placed) {
337
+ entries.push(['include', include]);
338
+ placed = true;
339
+ }
340
+ }
341
+ if (!placed) {
342
+ entries.push(['include', include]);
343
+ }
344
+ return {section: Object.fromEntries(entries), created: false, replaced: placed ? replaced : undefined};
345
+ }
package/bin/build.js CHANGED
@@ -7,6 +7,7 @@ const fs = require('fs');
7
7
  const os = require('os');
8
8
  const {execSync} = require('child_process');
9
9
  const dependentHasExifReaderConfig = require('./findDependentConfig');
10
+ const {writeMarker, removeMarker} = require('./custom-build-marker');
10
11
 
11
12
  const EXIFREADER_ROOT_DIR = path.join(__dirname, '..');
12
13
 
@@ -26,7 +27,8 @@ if (require.main === module) {
26
27
  *
27
28
  * @param {{config?: object}} [options] When `config` is given (the `exifreader`
28
29
  * config object), it is passed to webpack via the EXIFREADER_CUSTOM_BUILD env
29
- * var. Otherwise webpack resolves the config from package.json itself.
30
+ * var. Otherwise webpack resolves the config from package.json itself. A
31
+ * custom build records its config and version in the dist marker file.
30
32
  */
31
33
  function runBuild(options) {
32
34
  options = options || {};
@@ -39,10 +41,13 @@ function runBuild(options) {
39
41
  if (options.config) {
40
42
  env.EXIFREADER_CUSTOM_BUILD = JSON.stringify(options.config);
41
43
  }
44
+ const config = env.EXIFREADER_CUSTOM_BUILD ? JSON.parse(env.EXIFREADER_CUSTOM_BUILD) : dependentHasExifReaderConfig();
45
+ const distDir = path.join(EXIFREADER_ROOT_DIR, 'dist');
46
+ removeMarker(distDir);
42
47
 
43
48
  let tmpDir;
44
49
  try {
45
- if (env.EXIFREADER_CUSTOM_BUILD || hasDependentConfig()) {
50
+ if (config) {
46
51
  tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'exifreader-build-'));
47
52
  installCustomBuildDependencies(tmpDir);
48
53
  const buildModules = path.join(tmpDir, 'node_modules');
@@ -55,6 +60,9 @@ function runBuild(options) {
55
60
  }
56
61
 
57
62
  execSync(`npx -p ${getPackage('webpack-cli')} -p ${getPackage('webpack')} webpack`, {stdio: 'inherit', env});
63
+ if (config) {
64
+ writeMarker(distDir, config, require(path.join(EXIFREADER_ROOT_DIR, 'package.json')).version);
65
+ }
58
66
  } finally {
59
67
  if (tmpDir) {
60
68
  try {