This repository was archived by the owner on Jul 10, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.js
More file actions
233 lines (200 loc) · 6.54 KB
/
build.js
File metadata and controls
233 lines (200 loc) · 6.54 KB
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
/**
* build.js
*
* 1) Finds all .json in dist/@ and dist/nips.
* 2) Builds named exports in dist/bundle/schemas.js with custom logic:
* - If parent (or grandparent) is "tag":
* * File named "_A" => "ATagSchema", "_P" => "PTagSchema", etc.
* * Single letter like "a" => "aTagSchema"
* * "schema.json" in "tag/" => "tagSchema"
* - If file is dist/@/note.json => "noteSchema", etc.
* - If file base is "schema" => skip it, to avoid "SchemaSchema".
* - If file base starts with "schema." => remove "schema." => uppercase first letter of remainder.
* - Remove invalid chars (like @, -).
* 3) Outputs dist/bundle/schemas.js + .d.ts, runs esbuild => dist/bundle/schemas.bundle.js
*/
import esbuild from 'esbuild';
import {
readdirSync,
statSync,
writeFileSync,
mkdirSync,
existsSync
} from 'fs';
import { resolve, join, basename, dirname } from 'path';
const aliasDir = resolve('dist/@');
const nipsDir = resolve('dist/nips');
const bundleDir = resolve('dist/bundle');
function getAllJsonFiles(dir) {
if (!existsSync(dir)) return [];
const entries = readdirSync(dir, { withFileTypes: true });
return entries.flatMap((ent) => {
const full = join(dir, ent.name);
if (ent.isDirectory()) {
return getAllJsonFiles(full);
}
if (ent.name.endsWith('.json')) {
return [full];
}
return [];
});
}
/**
* Remove invalid chars like "@", "-", etc. so we produce a valid JS identifier.
*/
function sanitize(str) {
return str.replace(/[^a-zA-Z0-9]/g, '');
}
/**
* "kind-3" => "kind3", "client-req" => "clientReq"
*/
function camelCaseHyphens(str) {
const parts = str.split('-').filter(Boolean);
if (!parts.length) return '';
const [first, ...rest] = parts;
const lowered = first.toLowerCase();
const appended = rest
.map(s => s.charAt(0).toUpperCase() + s.slice(1).toLowerCase())
.join('');
return lowered + appended;
}
/**
* If file base is exactly "schema", we remove it (avoid "SchemaSchema").
* If it starts with "schema.", remove "schema." => uppercase the remainder's first letter.
*/
function processBaseName(baseName) {
if (baseName === 'schema') {
return '';
}
if (baseName.startsWith('schema.')) {
const after = baseName.slice('schema.'.length);
return after.charAt(0).toUpperCase() + after.slice(1);
}
return baseName;
}
/**
* If the folder path includes "tag", we do special logic:
* - If file is "_A" => "ATagSchema"
* - If file is "p" => "pTagSchema"
* - If file is "schema" => "tagSchema"
*/
function handleTagCase(dirParts, baseName) {
const lastDir = dirParts[dirParts.length - 1] || '';
const secondLast = dirParts[dirParts.length - 2] || '';
if (lastDir === 'tag' && baseName === 'schema') {
return 'tagSchema';
}
if (secondLast === 'tag') {
if (baseName === 'schema') {
let name = lastDir;
if (name.startsWith('_') && name.length > 1) {
name = name.charAt(1).toUpperCase() + name.slice(2);
}
return name + 'TagSchema';
} else {
return '';
}
}
if (lastDir === 'tag' && baseName) {
if (baseName.startsWith('_') && baseName.length > 1) {
const letter = baseName.charAt(1).toUpperCase() + baseName.slice(2);
return letter + 'TagSchema';
}
return baseName + 'TagSchema';
}
return '';
}
/**
* Generate exports for dist/nips
*/
function generateNipsExports(filePath) {
const distRoot = resolve('dist');
const relativePath = filePath.replace(distRoot, '').replace(/^[\\/]/, '');
const baseName = basename(filePath, '.json');
const processed = processBaseName(baseName);
const dirParts = dirname(filePath).split(/[/\\]/).filter(Boolean);
const tagResult = handleTagCase(dirParts, baseName);
if (tagResult) {
return { exportName: sanitize(tagResult), relativePath };
}
const parent = dirParts[dirParts.length - 1] || '';
const parentCased = camelCaseHyphens(parent);
let combined = parentCased + processed;
if (!combined) {
combined = 'Unnamed';
}
combined += 'Schema';
return { exportName: sanitize(combined), relativePath };
}
/**
* For dist/@:
* If we have direct parent '@' => e.g. dist/@/note.json => "noteSchema" in lowercase
* If we have a "tag" subfolder => handleTagCase
*/
function generateAliasExports(filePath) {
const distRoot = resolve('dist');
const relativePath = filePath.replace(distRoot, '').replace(/^[\\/]/, '');
const baseName = basename(filePath, '.json');
const processed = processBaseName(baseName);
const dirParts = dirname(filePath).split(/[/\\]/).filter(Boolean);
const last = dirParts[dirParts.length - 1] || '';
if (last === '@') {
const final = processed.toLowerCase() + 'Schema';
return { exportName: sanitize(final), relativePath };
}
const tagResult = handleTagCase(dirParts, baseName);
if (tagResult) {
return { exportName: sanitize(tagResult), relativePath };
}
const parent = dirParts[dirParts.length - 1] || '';
const parentCased = camelCaseHyphens(parent);
let combined = parentCased + processed;
if (!combined) {
combined = 'Unnamed';
}
combined += 'Schema';
return { exportName: sanitize(combined), relativePath };
}
/**
* If two exports share the same name, keep the first (nips).
*/
function prioritizeExports(exports) {
const seen = new Set();
return exports.filter(({ exportName }) => {
if (seen.has(exportName)) return false;
seen.add(exportName);
return true;
});
}
function main() {
const aliasFiles = getAllJsonFiles(aliasDir);
const nipsFiles = getAllJsonFiles(nipsDir);
const aliasExports = aliasFiles.map(generateAliasExports);
const nipsExports = nipsFiles.map(generateNipsExports);
const combined = prioritizeExports([...nipsExports, ...aliasExports]);
const exportLines = combined.map(({ exportName, relativePath }) =>
`export { default as ${exportName} } from '../${relativePath}';`
);
const typeLines = combined.map(({ exportName }) =>
`declare const ${exportName}: unknown;\nexport { ${exportName} };`
);
if (!existsSync(bundleDir)) {
mkdirSync(bundleDir, { recursive: true });
}
const schemasFile = join(bundleDir, 'schemas.js');
const dtsFile = join(bundleDir, 'schemas.d.ts');
writeFileSync(schemasFile, exportLines.join('\n'));
writeFileSync(dtsFile, typeLines.join('\n'));
esbuild.build({
entryPoints: [schemasFile],
outfile: join(bundleDir, 'schemas.bundle.js'),
format: 'esm',
platform: 'node',
target: 'es2020',
sourcemap: true,
minify: true,
})
.then(() => console.log('Schemas bundled successfully!'))
.catch(() => process.exit(1));
}
main();