« get me outta code hell

index.js « things « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/things/index.js
blob: 3bf84091f648f9870fdd9035336f27c14fee389b (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
import * as path from 'node:path';
import {fileURLToPath} from 'node:url';

import {openAggregate, showAggregate} from '#aggregate';
import {logError} from '#cli';
import {compositeFrom} from '#composite';
import * as serialize from '#serialize';

import Thing from '#thing';

import * as albumClasses from './album.js';
import * as artTagClasses from './art-tag.js';
import * as artistClasses from './artist.js';
import * as flashClasses from './flash.js';
import * as groupClasses from './group.js';
import * as homepageLayoutClasses from './homepage-layout.js';
import * as languageClasses from './language.js';
import * as newsEntryClasses from './news-entry.js';
import * as staticPageClasses from './static-page.js';
import * as trackClasses from './track.js';
import * as wikiInfoClasses from './wiki-info.js';

const allClassLists = {
  'album.js': albumClasses,
  'art-tag.js': artTagClasses,
  'artist.js': artistClasses,
  'flash.js': flashClasses,
  'group.js': groupClasses,
  'homepage-layout.js': homepageLayoutClasses,
  'language.js': languageClasses,
  'news-entry.js': newsEntryClasses,
  'static-page.js': staticPageClasses,
  'track.js': trackClasses,
  'wiki-info.js': wikiInfoClasses,
};

let allClasses = Object.create(null);

// src/data/things/index.js -> src/
const __dirname = path.dirname(
  path.resolve(
    fileURLToPath(import.meta.url),
    '../..'));

function niceShowAggregate(error, ...opts) {
  showAggregate(error, {
    pathToFileURL: (f) => path.relative(__dirname, fileURLToPath(f)),
    ...opts,
  });
}

function errorDuplicateClassNames() {
  const locationDict = Object.create(null);

  for (const [location, classes] of Object.entries(allClassLists)) {
    for (const className of Object.keys(classes)) {
      if (className in locationDict) {
        locationDict[className].push(location);
      } else {
        locationDict[className] = [location];
      }
    }
  }

  let success = true;

  for (const [className, locations] of Object.entries(locationDict)) {
    if (locations.length === 1) {
      continue;
    }

    logError`Thing class name ${`"${className}"`} is defined more than once: ${locations.join(', ')}`;
    success = false;
  }

  return success;
}

function flattenClassLists() {
  for (const classes of Object.values(allClassLists)) {
    for (const [name, constructor] of Object.entries(classes)) {
      if (typeof constructor !== 'function') continue;
      if (!(constructor.prototype instanceof Thing)) continue;
      allClasses[name] = constructor;
    }
  }
}

function descriptorAggregateHelper({
  showFailedClasses,
  message,
  op,
}) {
  const failureSymbol = Symbol();
  const aggregate = openAggregate({
    message,
    returnOnFail: failureSymbol,
  });

  const failedClasses = [];

  for (const [name, constructor] of Object.entries(allClasses)) {
    const result = aggregate.call(op, constructor);

    if (result === failureSymbol) {
      failedClasses.push(name);
    }
  }

  try {
    aggregate.close();
    return true;
  } catch (error) {
    niceShowAggregate(error);
    showFailedClasses(failedClasses);
    return false;
  }
}

function evaluatePropertyDescriptors() {
  const opts = {...allClasses};

  return descriptorAggregateHelper({
    message: `Errors evaluating Thing class property descriptors`,

    op(constructor) {
      if (!constructor[Thing.getPropertyDescriptors]) {
        throw new Error(`Missing [Thing.getPropertyDescriptors] function`);
      }

      const results = constructor[Thing.getPropertyDescriptors](opts);

      for (const [key, value] of Object.entries(results)) {
        if (Array.isArray(value)) {
          results[key] = compositeFrom({
            annotation: `${constructor.name}.${key}`,
            compose: false,
            steps: value,
          });
        } else if (value.toResolvedComposition) {
          results[key] = compositeFrom(value.toResolvedComposition());
        }
      }

      constructor.propertyDescriptors = results;
    },

    showFailedClasses(failedClasses) {
      logError`Failed to evaluate property descriptors for classes: ${failedClasses.join(', ')}`;
    },
  });
}

function evaluateSerializeDescriptors() {
  const opts = {...allClasses, serialize};

  return descriptorAggregateHelper({
    message: `Errors evaluating Thing class serialize descriptors`,

    op(constructor) {
      if (!constructor[Thing.getSerializeDescriptors]) {
        return;
      }

      constructor[serialize.serializeDescriptors] =
        constructor[Thing.getSerializeDescriptors](opts);
    },

    showFailedClasses(failedClasses) {
      logError`Failed to evaluate serialize descriptors for classes: ${failedClasses.join(', ')}`;
    },
  });
}

if (!errorDuplicateClassNames())
  process.exit(1);

flattenClassLists();

if (!evaluatePropertyDescriptors())
  process.exit(1);

if (!evaluateSerializeDescriptors())
  process.exit(1);

Object.assign(allClasses, {Thing});

export default allClasses;