-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathindex.ts
More file actions
277 lines (251 loc) · 9.68 KB
/
index.ts
File metadata and controls
277 lines (251 loc) · 9.68 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
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
import fs from "node:fs";
import path from "node:path";
import { parseArgs } from "node:util";
import { z } from "zod";
import {
extendZodWithOpenApi,
OpenAPIRegistry,
OpenApiGeneratorV3
} from "@asteasolutions/zod-to-openapi";
extendZodWithOpenApi(z);
const registry = new OpenAPIRegistry();
const topicsDir = path.join(__dirname, "./metadata/topics");
const languagesDir = path.join(__dirname, "./metadata/languages");
export const fileNameToId = (fileName: string) =>
path.basename(fileName, ".yaml");
const validTopics = fs
.readdirSync(topicsDir, { recursive: true })
.filter((f) => typeof f === "string" && f.endsWith(".yaml"))
.map((f) => fileNameToId(f as string));
const validLanguages = fs
.readdirSync(languagesDir, { recursive: true })
.filter((f) => typeof f === "string" && f.endsWith(".yaml"))
.map((f) => fileNameToId(f as string));
const allValidTags = [...validTopics, ...validLanguages].toSorted();
if (allValidTags.length === 0) {
throw new Error("No metadata entities found!");
}
const EntityTagEnum = registry.register("EntityTag", z.enum([allValidTags[0], ...allValidTags.slice(1)] as [
string,
...string[],
]));
const PaidPricingSchema = registry.register("PaidPricing", z
.strictObject({
model: z
.enum(["Subscription", "One Time"])
.describe(
"The Paid Pricing Model of this resource. 'Subscription' means the resource is paid on a recurring basis (e.g. monthly or yearly), while 'One Time' means the resource is paid with a single upfront payment. If the price varies or is not fixed, provide a close approximation. Note that the subscription renewal cycle is not specified, so if the price has different renewal cycles, provide the most common or default one (usually monthly).",
),
amount: z
.number()
.gt(0)
.describe("The price of this resource, in US Dollars."),
})
.meta({ id: "PaidPricing" }));
const FreePricingSchema = registry.register("FreePricing", z
.strictObject({
model: z
.enum(["Free", "Freemium"])
.describe(
"The Free(mium) Pricing Model of this resource. 'Free' should be used for resources where 100% (or close) of the content is free. 'Freemium' describes a pricing model where the core content is available for free, but features paid extensions. If the resource has a freemium model but the free portion is very limited, consider using 'Paid' instead and providing an estimated price for the full version. ",
),
})
.meta({ id: "FreePricing" }));
/**
* The Pricing of a Resource, which can either be Free/Freemium or Paid (Subscription/One Time)
*/
const PricingSchema = registry.register("Pricing", z
.discriminatedUnion("model", [FreePricingSchema, PaidPricingSchema])
.meta({ id: "Pricing" })
.describe("Details about the cost of the resource."));
export const LanguageDomainSchema = registry.register("LanguageDomain", z
.enum([
"Web Development",
"Data Science",
"Mobile Development",
"Game Development",
"Systems Programming",
"Scripting",
"General Purpose",
"DevOps",
])
.meta({ id: "LanguageDomain" })
.describe("A domain that a programming language may be used in."));
export const ProgrammingParadigmSchema = registry.register("ProgrammingParadigm", z
.enum([
"Object-Oriented Programming",
"Functional Programming",
"Procedural Programming",
"Logic Programming",
])
.meta({ id: "ProgrammingParadigm" })
.describe("A programming paradigm."));
export const ResourceCategorySchema = registry.register("ResourceCategory", z
.discriminatedUnion("type", [
z.object({
type: z.literal("Language"),
paradigms: z
.array(ProgrammingParadigmSchema)
.describe(
"The programming paradigms that this language focuses on, e.g. 'Object-Oriented Programming', 'Functional Programming', 'Procedural Programming', etc.",
),
}).meta({ id: "CategoryLanguage" }),
z.object({
type: z.literal("Platform"),
}).meta({
id: "CategoryPlatform",
description: "A platform used to learn programming, which may teach a variety of languages and concepts.",
}),
z.object({
type: z.literal("Tool"),
}).meta({ id: "CategoryTool" }),
])
.meta({ id: "ResourceCategory" }));
const ResourceTypeSchema = registry.register("ResourceType", z
.enum(["Video", "Article", "Interactive Tutorial", "Book", "Course"])
.describe("The type of the resource"));
export const ResourceSchema = registry.register("Resource", z
.strictObject({
name: z.string().describe("The official name of the resource"),
description: z
.string()
.max(256)
.optional()
.describe("A brief description of the resource"),
url: z.url().describe("URL to the resource"),
type: z
.array(ResourceTypeSchema)
.min(1, "Must specify at least one resource type")
.describe(
"The type(s) of the resource, e.g. 'Video', 'Book', 'Course', etc.",
),
teaches: z
.array(EntityTagEnum)
.min(1, "Must teach at least one topic")
.describe("The topics that this resource teaches."),
pricing: PricingSchema,
pros: z
.array(z.string())
.optional()
.describe(
"Array of pros for using the resource, e.g. 'explains difficult concepts with good analogies'",
),
cons: z
.array(z.string())
.optional()
.describe(
"Array of cons for using the resource, e.g. 'only teaches the basics rather than more advanced concepts'",
),
})
.meta({ id: "Resource" }));
export const MetaSchema = registry.register("Meta", z
.strictObject({
name: z
.string()
.describe(
"The name of the language, tool, etc being described by this metadata.",
),
description: z
.string()
.describe(
"A brief description of the language, tool, etc being described by this metadata.",
),
emoji: z
.string()
.optional()
.describe(
"A Unicode emoji glyph to represent the entity, if applicable. If there is no suitable (Unicode) emoji, omit this field. Consumers may choose to ignore this field, or replace it with a custom image.",
),
domains: z
.array(LanguageDomainSchema)
.describe(
"The domain(s) that the entity is commonly used in, or best suited for.",
),
category: ResourceCategorySchema,
})
.meta({ id: "Meta" }));
export const CompiledMetaSchema = MetaSchema.extend({
id: EntityTagEnum,
}).meta({ id: "CompiledMeta" });
export const DatabaseSchema = registry.register("Database", z
.strictObject({
metadata: z
.array(CompiledMetaSchema)
.describe("List of all entities in the system"),
resources: z
.array(ResourceSchema)
.describe("List of all learning resources"),
})
.meta({ id: "Database" }));
export type Meta = z.infer<typeof MetaSchema>;
export type Resource = z.infer<typeof ResourceSchema>;
export type Database = z.infer<typeof DatabaseSchema>;
function main() {
const header = "// Generated by index.ts - DO NOT EDIT THIS FILE DIRECTLY";
const { values, positionals: _ } = parseArgs({
args: Bun.argv,
options: {
schema: {
type: "string",
},
},
strict: true,
allowPositionals: true,
});
const schemaArg = values.schema?.toLowerCase();
if (schemaArg === "openapi") {
registry.registerPath({
method: 'get',
path: '/resources',
summary: 'Get all learning resources',
responses: {
200: {
description: 'Successful response',
content: {
'application/json': {
schema: DatabaseSchema,
},
},
},
},
});
const generator = new OpenApiGeneratorV3(registry.definitions);
const openApiDocument = generator.generateDocument({
openapi: "3.0.0",
info: {
title: "Learning Resources",
version: "1.0.0",
description: "// Generated by index.ts - DO NOT EDIT THIS FILE DIRECTLY"
},
});
console.log(JSON.stringify(openApiDocument, null, 2));
process.exit(0);
}
let schema: z.ZodObject;
switch (schemaArg) {
case "metadata":
schema = MetaSchema;
break;
case "resource":
schema = ResourceSchema;
break;
case "database":
schema = DatabaseSchema;
break;
case undefined:
console.error(
"No schema specified. Use --schema to specify which schema to generate (e.g. --schema resource)",
);
process.exit(1);
break;
default:
console.error(`Unknown schema: ${values.schema}`);
process.exit(1);
}
const jsonSchema = z.toJSONSchema(schema, { reused: "inline" });
jsonSchema.$comment = header;
console.log(JSON.stringify(jsonSchema, null, 2));
}
if (import.meta.main) {
main();
}