« get me outta code hell

find.js « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/find.js
blob: fecf1ab062706ee2edf591ed44cc35a9cdad9cdf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import {inspect} from 'node:util';

import CacheableObject from '#cacheable-object';
import {colors, logWarn} from '#cli';
import {typeAppearance} from '#sugar';
import {getKebabCase} from '#wiki-data';

function warnOrThrow(mode, message) {
  if (mode === 'error') {
    throw new Error(message);
  }

  if (mode === 'warn') {
    logWarn(message);
  }

  return null;
}

export function processAllAvailableMatches(data, {
  include = thing => true,

  getMatchableNames = thing =>
    (Object.hasOwn(thing, 'name')
      ? [thing.name]
      : []),

  getMatchableDirectories = thing =>
    (Object.hasOwn(thing, 'directory')
      ? [thing.directory]
      : [null]),
} = {}) {
  const byName = Object.create(null);
  const byDirectory = Object.create(null);
  const multipleNameMatches = Object.create(null);

  for (const thing of data) {
    if (!include(thing)) continue;

    for (const directory of getMatchableDirectories(thing)) {
      if (typeof directory !== 'string') {
        logWarn`Unexpected ${typeAppearance(directory)} returned in directories for ${inspect(thing)}`;
        continue;
      }

      byDirectory[directory] = thing;
    }

    for (const name of getMatchableNames(thing)) {
      if (typeof name !== 'string') {
        logWarn`Unexpected ${typeAppearance(name)} returned in names for ${inspect(thing)}`;
        continue;
      }

      const normalizedName = name.toLowerCase();

      if (normalizedName in byName) {
        const alreadyMatchesByName = byName[normalizedName];
        byName[normalizedName] = null;
        if (normalizedName in multipleNameMatches) {
          multipleNameMatches[normalizedName].push(thing);
        } else {
          multipleNameMatches[normalizedName] = [alreadyMatchesByName, thing];
        }
      } else {
        byName[normalizedName] = thing;
      }
    }
  }

  return {byName, byDirectory, multipleNameMatches};
}

function findHelper({
  referenceTypes,

  include = undefined,
  getMatchableNames = undefined,
}) {
  const keyRefRegex =
    new RegExp(String.raw`^(?:(${referenceTypes.join('|')}):(?=\S))?(.*)$`);

  // Note: This cache explicitly *doesn't* support mutable data arrays. If the
  // data array is modified, make sure it's actually a new array object, not
  // the original, or the cache here will break and act as though the data
  // hasn't changed!
  const cache = new WeakMap();

  // The mode argument here may be 'warn', 'error', or 'quiet'. 'error' throws
  // errors for null matches (with details about the error), while 'warn' and
  // 'quiet' both return null, with 'warn' logging details directly to the
  // console.
  return (fullRef, data, {mode = 'warn'} = {}) => {
    if (!fullRef) return null;
    if (typeof fullRef !== 'string') {
      throw new TypeError(`Expected a string, got ${typeAppearance(fullRef)}`);
    }

    if (!data) {
      throw new TypeError(`Expected data to be present`);
    }

    let subcache = cache.get(data);
    if (!subcache) {
      subcache =
        processAllAvailableMatches(data, {
          include,
          getMatchableNames,
        });

      cache.set(data, subcache);
    }

    const regexMatch = fullRef.match(keyRefRegex);
    if (!regexMatch) {
      warnOrThrow(mode, `Malformed link reference: "${fullRef}"`);
    }

    const typePart = regexMatch[1];
    const refPart = regexMatch[2];

    const normalizedName =
      (typePart
        ? null
        : refPart.toLowerCase());

    const match =
      (typePart
        ? subcache.byDirectory[refPart]
        : subcache.byName[normalizedName]);

    if (!match && !typePart) {
      if (subcache.multipleNameMatches[normalizedName]) {
        return warnOrThrow(mode,
          `Multiple matches for reference "${fullRef}". Please resolve:\n` +
          subcache.multipleNameMatches[normalizedName]
            .map(match => `- ${inspect(match)}\n`)
            .join('') +
          `Returning null for this reference.`);
      }
    }

    if (!match) {
      warnOrThrow(mode, `Didn't match anything for ${colors.bright(fullRef)}`);
      return null;
    }

    return match;
  };
}

const find = {
  album: findHelper({
    referenceTypes: ['album', 'album-commentary', 'album-gallery'],
  }),

  artist: findHelper({
    referenceTypes: ['artist', 'artist-gallery'],

    include: artist => !artist.isAlias,
  }),

  artistIncludingAliases: findHelper({
    referenceTypes: ['artist', 'artist-gallery'],

    getMatchableDirectories(artist) {
      // Regular artists are always matchable by their directory.
      if (!artist.isAlias) {
        return [artist.directory];
      }

      const originalArtist = artist.aliasedArtist;

      // Aliases never match by the same directory as the original.
      if (artist.directory === originalArtist.directory) {
        return [];
      }

      // Aliases never match by the same directory as some *previous* alias
      // in the original's alias list. This is honestly a bit awkward, but it
      // avoids artist aliases conflicting with each other when checking for
      // duplicate directories.
      for (const aliasName of originalArtist.aliasNames) {
        // These are trouble. We should be accessing aliases' directories
        // directly, but artists currently don't expose a reverse reference
        // list for aliases. (This is pending a cleanup of "reverse reference"
        // behavior in general.) It doesn't actually cause problems *here*
        // because alias directories are computed from their names 100% of the
        // time, but that *is* an assumption this code makes.
        if (aliasName === artist.name) continue;
        if (artist.directory === getKebabCase(aliasName)) {
          return [];
        }
      }

      // And, aliases never return just a blank string. This part is pretty
      // spooky because it doesn't handle two differently named aliases, on
      // different artists, who have names that are similar *apart* from a
      // character that's shortened. But that's also so fundamentally scary
      // that we can't support it properly with existing code, anyway - we
      // would need to be able to specifically set a directory *on an alias,*
      // which currently can't be done in YAML data files.
      if (artist.directory === '') {
        return [];
      }

      return [artist.directory];
    },
  }),

  artTag: findHelper({
    referenceTypes: ['tag'],

    getMatchableNames: tag =>
      (tag.isContentWarning
        ? [`cw: ${tag.name}`]
        : [tag.name]),
  }),

  flash: findHelper({
    referenceTypes: ['flash'],
  }),

  flashAct: findHelper({
    referenceTypes: ['flash-act'],
  }),

  group: findHelper({
    referenceTypes: ['group', 'group-gallery'],
  }),

  listing: findHelper({
    referenceTypes: ['listing'],
  }),

  newsEntry: findHelper({
    referenceTypes: ['news-entry'],
  }),

  staticPage: findHelper({
    referenceTypes: ['static'],
  }),

  track: findHelper({
    referenceTypes: ['track'],

    getMatchableNames: track =>
      (track.alwaysReferenceByDirectory
        ? []
        : [track.name]),
  }),

  trackOriginalReleasesOnly: findHelper({
    referenceTypes: ['track'],

    include: track =>
      !CacheableObject.getUpdateValue(track, 'originalReleaseTrack'),

    // It's still necessary to check alwaysReferenceByDirectory here, since it
    // may be set manually (with the `Always Reference By Directory` field), and
    // these shouldn't be matched by name (as per usual). See the definition for
    // that property for more information.
    getMatchableNames: track =>
      (track.alwaysReferenceByDirectory
        ? []
        : [track.name]),
  }),
};

export default find;

// Handy utility function for binding the find.thing() functions to a complete
// wikiData object, optionally taking default options to provide to the find
// function. Note that this caches the arrays read from wikiData right when it's
// called, so if their values change, you'll have to continue with a fresh call
// to bindFind.
export function bindFind(wikiData, opts1) {
  return Object.fromEntries(
    Object.entries({
      album: 'albumData',
      artist: 'artistData',
      artTag: 'artTagData',
      flash: 'flashData',
      flashAct: 'flashActData',
      group: 'groupData',
      listing: 'listingSpec',
      newsEntry: 'newsData',
      staticPage: 'staticPageData',
      track: 'trackData',
      trackOriginalReleasesOnly: 'trackData',
    }).map(([key, value]) => {
      const findFn = find[key];
      const thingData = wikiData[value];
      return [
        key,
        opts1
          ? (ref, opts2) =>
              opts2
                ? findFn(ref, thingData, {...opts1, ...opts2})
                : findFn(ref, thingData, opts1)
          : (ref, opts2) =>
              opts2
                ? findFn(ref, thingData, opts2)
                : findFn(ref, thingData),
      ];
    })
  );
}