algolia-codegen 0.1.0 → 0.1.2

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/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,18 +17,606 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var src_exports = {};
22
32
  __export(src_exports, {
23
- main: () => main
33
+ main: () => main,
34
+ validateConfig: () => validateConfig,
35
+ validateGeneratorConfig: () => validateGeneratorConfig,
36
+ validateUrlSchema: () => validateUrlSchema
24
37
  });
25
38
  module.exports = __toCommonJS(src_exports);
26
- var main = () => {
27
- console.log("Main!");
39
+
40
+ // src/utils/load-config.ts
41
+ var import_fs2 = require("fs");
42
+ var import_path = require("path");
43
+ var import_url = require("url");
44
+
45
+ // src/utils/load-typescript-config.ts
46
+ var import_fs = require("fs");
47
+ async function loadTypeScriptConfig(resolvedPath) {
48
+ const esbuild = await import("esbuild");
49
+ const source = (0, import_fs.readFileSync)(resolvedPath, "utf-8");
50
+ const result = esbuild.transformSync(source, {
51
+ loader: "ts",
52
+ format: "esm",
53
+ target: "node18",
54
+ sourcefile: resolvedPath
55
+ });
56
+ if (!result.code) {
57
+ throw new Error("Failed to transform TypeScript config file");
58
+ }
59
+ const dataUrl = `data:text/javascript;charset=utf-8,${encodeURIComponent(result.code)}`;
60
+ const module2 = await import(dataUrl);
61
+ return module2;
62
+ }
63
+
64
+ // src/utils/validations/generator-config.ts
65
+ function validateGeneratorConfig(config, path) {
66
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
67
+ throw new Error(
68
+ `Invalid generator config: must be an object
69
+ Path: ${path}`
70
+ );
71
+ }
72
+ const cfg = config;
73
+ const requiredFields = [
74
+ "appId",
75
+ "searchKey",
76
+ "indexName"
77
+ ];
78
+ for (const field of requiredFields) {
79
+ if (!(field in cfg)) {
80
+ throw new Error(
81
+ `Invalid generator config: missing required property '${field}'
82
+ Path: ${path}`
83
+ );
84
+ }
85
+ if (typeof cfg[field] !== "string") {
86
+ throw new Error(
87
+ `Invalid generator config: '${field}' must be a string
88
+ Path: ${path}
89
+ Received: ${typeof cfg[field]}`
90
+ );
91
+ }
92
+ }
93
+ if ("prefix" in cfg && cfg.prefix !== void 0 && typeof cfg.prefix !== "string") {
94
+ throw new Error(
95
+ `Invalid generator config: 'prefix' must be a string or undefined
96
+ Path: ${path}
97
+ Received: ${typeof cfg.prefix}`
98
+ );
99
+ }
100
+ if ("postfix" in cfg && cfg.postfix !== void 0 && typeof cfg.postfix !== "string") {
101
+ throw new Error(
102
+ `Invalid generator config: 'postfix' must be a string or undefined
103
+ Path: ${path}
104
+ Received: ${typeof cfg.postfix}`
105
+ );
106
+ }
107
+ }
108
+
109
+ // src/utils/validations/url-schema.ts
110
+ function validateUrlSchema(urlSchema, path) {
111
+ if (typeof urlSchema !== "object" || urlSchema === null || Array.isArray(urlSchema)) {
112
+ throw new Error(
113
+ `Invalid generates entry: must be an object
114
+ Path: ${path}`
115
+ );
116
+ }
117
+ const schema = urlSchema;
118
+ for (const [filePath, generatorConfig] of Object.entries(schema)) {
119
+ if (typeof filePath !== "string") {
120
+ throw new Error(
121
+ `Invalid generates entry: file path must be a string
122
+ Path: ${path}[${filePath}]`
123
+ );
124
+ }
125
+ validateGeneratorConfig(generatorConfig, `${path}["${filePath}"]`);
126
+ }
127
+ }
128
+
129
+ // src/utils/validations/config.ts
130
+ function validateConfig(config, configPath) {
131
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
132
+ throw new Error(
133
+ `Invalid config: must be an object
134
+ Config file: ${configPath}`
135
+ );
136
+ }
137
+ const cfg = config;
138
+ if (!("overwrite" in cfg)) {
139
+ throw new Error(
140
+ `Invalid config: missing required property 'overwrite'
141
+ Config file: ${configPath}`
142
+ );
143
+ }
144
+ if (typeof cfg.overwrite !== "boolean") {
145
+ throw new Error(
146
+ `Invalid config: 'overwrite' must be a boolean
147
+ Config file: ${configPath}
148
+ Received: ${typeof cfg.overwrite}`
149
+ );
150
+ }
151
+ if (!("generates" in cfg)) {
152
+ throw new Error(
153
+ `Invalid config: missing required property 'generates'
154
+ Config file: ${configPath}`
155
+ );
156
+ }
157
+ const generates = cfg.generates;
158
+ if (Array.isArray(generates)) {
159
+ generates.forEach((item, index) => {
160
+ validateUrlSchema(item, `${configPath}[generates][${index}]`);
161
+ });
162
+ } else if (typeof generates === "object" && generates !== null) {
163
+ validateUrlSchema(generates, `${configPath}[generates]`);
164
+ } else {
165
+ throw new Error(
166
+ `Invalid config: 'generates' must be an object or an array of objects
167
+ Config file: ${configPath}
168
+ Received: ${typeof generates}`
169
+ );
170
+ }
171
+ }
172
+
173
+ // src/utils/load-config.ts
174
+ async function loadConfig(configPath) {
175
+ const defaultConfigPath = "algolia-codegen.ts";
176
+ const finalConfigPath = configPath || defaultConfigPath;
177
+ const resolvedPath = (0, import_path.resolve)(process.cwd(), finalConfigPath);
178
+ if (!(0, import_fs2.existsSync)(resolvedPath)) {
179
+ throw new Error(
180
+ `Config file not found: ${resolvedPath}
181
+ Please create a config file or specify a different path using --config option.`
182
+ );
183
+ }
184
+ const configUrl = (0, import_url.pathToFileURL)(resolvedPath).href;
185
+ let configModule;
186
+ if (resolvedPath.endsWith(".ts")) {
187
+ try {
188
+ configModule = await loadTypeScriptConfig(resolvedPath);
189
+ } catch (tsError) {
190
+ const jsPath = resolvedPath.replace(/\.ts$/, ".js");
191
+ if ((0, import_fs2.existsSync)(jsPath)) {
192
+ const jsUrl = (0, import_url.pathToFileURL)(jsPath).href;
193
+ try {
194
+ configModule = await import(jsUrl);
195
+ } catch (jsImportError) {
196
+ throw new Error(
197
+ `Failed to import config file: ${resolvedPath}
198
+ Tried both .ts (via esbuild) and .js extensions.
199
+ TypeScript error: ${tsError instanceof Error ? tsError.message : String(tsError)}
200
+ JavaScript error: ${jsImportError instanceof Error ? jsImportError.message : String(jsImportError)}`
201
+ );
202
+ }
203
+ } else {
204
+ throw new Error(
205
+ `Failed to load TypeScript config file: ${resolvedPath}
206
+ Error: ${tsError instanceof Error ? tsError.message : String(tsError)}
207
+ Make sure esbuild is installed as a dependency.`
208
+ );
209
+ }
210
+ }
211
+ } else {
212
+ try {
213
+ configModule = await import(configUrl);
214
+ } catch (importError) {
215
+ const errorMessage = importError instanceof Error ? importError.message : String(importError);
216
+ throw new Error(
217
+ `Failed to import config file: ${resolvedPath}
218
+ Error: ${errorMessage}`
219
+ );
220
+ }
221
+ }
222
+ if (!configModule.default) {
223
+ throw new Error(
224
+ `Config file does not export a default object: ${resolvedPath}
225
+ Please ensure your config file exports a default object: export default { ... }`
226
+ );
227
+ }
228
+ const config = configModule.default;
229
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
230
+ throw new Error(
231
+ `Config file default export must be an object: ${resolvedPath}
232
+ Received: ${typeof config}`
233
+ );
234
+ }
235
+ validateConfig(config, resolvedPath);
236
+ return config;
237
+ }
238
+
239
+ // src/utils/fetch-algolia-data.ts
240
+ var import_algoliasearch = require("algoliasearch");
241
+ var import_fs3 = require("fs");
242
+ var import_path2 = require("path");
243
+
244
+ // src/utils/generate-typescript-types.ts
245
+ var TypeGenerator = class {
246
+ typeMap = /* @__PURE__ */ new Map();
247
+ generatedTypes = /* @__PURE__ */ new Set();
248
+ idValueTypes = /* @__PURE__ */ new Set();
249
+ prefix;
250
+ postfix;
251
+ indexName;
252
+ constructor(config) {
253
+ this.prefix = config.prefix || "";
254
+ this.postfix = config.postfix || "";
255
+ this.indexName = config.indexName;
256
+ }
257
+ /**
258
+ * Convert a value to its TypeScript type representation
259
+ */
260
+ inferType(value, path = []) {
261
+ if (value === null || value === void 0) {
262
+ return { type: "unknown", isOptional: true, isArray: false, nestedTypes: /* @__PURE__ */ new Map() };
263
+ }
264
+ if (Array.isArray(value)) {
265
+ if (value.length === 0) {
266
+ return { type: "unknown[]", isOptional: false, isArray: true, nestedTypes: /* @__PURE__ */ new Map() };
267
+ }
268
+ const itemTypes = value.map((item, idx) => this.inferType(item, [...path, `[${idx}]`]));
269
+ if (this.isIdValuePattern(value)) {
270
+ const firstItem = value[0];
271
+ const valueType = this.inferType(firstItem.value, [...path, "[0].value"]);
272
+ const idValueTypeName = `${this.prefix}IdValue`;
273
+ this.idValueTypes.add(idValueTypeName);
274
+ const typeString = valueType.type !== "string" ? `${idValueTypeName}<${valueType.type}>` : idValueTypeName;
275
+ return {
276
+ type: `${typeString}[]`,
277
+ isOptional: false,
278
+ isArray: true,
279
+ nestedTypes: /* @__PURE__ */ new Map()
280
+ };
281
+ }
282
+ const firstType = itemTypes[0];
283
+ const allSameType = itemTypes.every(
284
+ (t) => t.type === firstType.type && !t.isArray && t.nestedTypes.size === firstType.nestedTypes.size
285
+ );
286
+ if (allSameType && !firstType.isArray) {
287
+ return {
288
+ type: `${firstType.type}[]`,
289
+ isOptional: false,
290
+ isArray: true,
291
+ nestedTypes: firstType.nestedTypes
292
+ };
293
+ }
294
+ const uniqueTypes = Array.from(new Set(itemTypes.map((t) => t.type)));
295
+ const unionType = uniqueTypes.length === 1 ? uniqueTypes[0] : uniqueTypes.join(" | ");
296
+ return {
297
+ type: `${unionType}[]`,
298
+ isOptional: false,
299
+ isArray: true,
300
+ nestedTypes: /* @__PURE__ */ new Map()
301
+ };
302
+ }
303
+ if (typeof value === "object") {
304
+ const obj = value;
305
+ const typeName = this.generateTypeName(path);
306
+ const nestedTypes = /* @__PURE__ */ new Map();
307
+ for (const [key, val] of Object.entries(obj)) {
308
+ nestedTypes.set(key, this.inferType(val, [...path, key]));
309
+ }
310
+ if (!this.generatedTypes.has(typeName)) {
311
+ this.generatedTypes.add(typeName);
312
+ this.typeMap.set(typeName, this.generateInterface(typeName, nestedTypes, obj));
313
+ }
314
+ return {
315
+ type: typeName,
316
+ isOptional: false,
317
+ isArray: false,
318
+ nestedTypes
319
+ };
320
+ }
321
+ const jsType = typeof value;
322
+ let tsType;
323
+ if (jsType === "number") {
324
+ tsType = "number";
325
+ } else if (jsType === "boolean") {
326
+ tsType = "boolean";
327
+ } else {
328
+ tsType = "string";
329
+ }
330
+ return { type: tsType, isOptional: false, isArray: false, nestedTypes: /* @__PURE__ */ new Map() };
331
+ }
332
+ /**
333
+ * Check if an array follows the AlgoliaIdValue pattern
334
+ */
335
+ isIdValuePattern(arr) {
336
+ return arr.length > 0 && arr.every(
337
+ (item) => typeof item === "object" && item !== null && "id" in item && "value" in item && typeof item.id === "string"
338
+ );
339
+ }
340
+ /**
341
+ * Generate a TypeScript type name from a path
342
+ */
343
+ generateTypeName(path) {
344
+ if (path.length === 0) {
345
+ return `${this.prefix}Hit${this.postfix}`;
346
+ }
347
+ const lastPart = path[path.length - 1];
348
+ const parts = lastPart.replace(/[\[\]]/g, "").split(/[-_\s]+/).filter(Boolean);
349
+ const pascalCase = parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("");
350
+ if (path.length > 1) {
351
+ const parent = path[path.length - 2];
352
+ if (parent.includes("Info")) {
353
+ return `${this.prefix}${pascalCase}Info${this.postfix}`;
354
+ }
355
+ }
356
+ return `${this.prefix}${pascalCase}${this.postfix}`;
357
+ }
358
+ /**
359
+ * Generate TypeScript interface code
360
+ */
361
+ generateInterface(typeName, nestedTypes, sampleObj) {
362
+ const lines = [];
363
+ const description = this.getTypeDescription(typeName);
364
+ lines.push("/**");
365
+ lines.push(` * ${description}`);
366
+ lines.push(" */");
367
+ lines.push(`export interface ${typeName} {`);
368
+ const sortedKeys = Array.from(nestedTypes.keys()).sort();
369
+ for (const key of sortedKeys) {
370
+ const typeInfo = nestedTypes.get(key);
371
+ const value = sampleObj[key];
372
+ const isOptional = typeInfo.isOptional || value === null || value === void 0;
373
+ const optionalMarker = isOptional ? "?" : "";
374
+ let typeString = typeInfo.type;
375
+ if (typeInfo.isArray && !typeString.endsWith("[]")) {
376
+ typeString = `${typeString}[]`;
377
+ }
378
+ if (value === null && typeString !== "null") {
379
+ typeString = `${typeString} | null`;
380
+ }
381
+ lines.push(` ${key}${optionalMarker}: ${typeString};`);
382
+ }
383
+ lines.push("}");
384
+ lines.push("");
385
+ return lines.join("\n");
386
+ }
387
+ /**
388
+ * Get a description for a type based on its name
389
+ */
390
+ getTypeDescription(typeName) {
391
+ const withoutPrefix = typeName.replace(new RegExp(`^${this.prefix}`), "");
392
+ const withoutPostfix = withoutPrefix.replace(new RegExp(`${this.postfix}$`), "");
393
+ const readable = withoutPostfix.replace(/([A-Z])/g, " $1").trim().toLowerCase();
394
+ return readable.charAt(0).toUpperCase() + readable.slice(1) + " structure in Algolia";
395
+ }
396
+ /**
397
+ * Collect all types that need to be generated
398
+ */
399
+ collectTypes(typeInfo, typesToGenerate) {
400
+ if (typeInfo.nestedTypes.size > 0 && !typeInfo.isArray) {
401
+ typesToGenerate.add(typeInfo.type);
402
+ for (const nestedTypeInfo of typeInfo.nestedTypes.values()) {
403
+ this.collectTypes(nestedTypeInfo, typesToGenerate);
404
+ }
405
+ }
406
+ }
407
+ /**
408
+ * Get dependencies for a type (types that it references)
409
+ */
410
+ getTypeDependencies(typeName) {
411
+ const typeCode = this.typeMap.get(typeName);
412
+ if (!typeCode) return [];
413
+ const dependencies = [];
414
+ const importRegex = new RegExp(`(${this.prefix}\\w+)`, "g");
415
+ const matches = typeCode.matchAll(importRegex);
416
+ for (const match of matches) {
417
+ const depTypeName = match[1];
418
+ if (depTypeName !== typeName && this.generatedTypes.has(depTypeName)) {
419
+ dependencies.push(depTypeName);
420
+ }
421
+ }
422
+ return Array.from(new Set(dependencies));
423
+ }
424
+ /**
425
+ * Sort types by dependencies (topological sort)
426
+ */
427
+ sortTypesByDependencies(typeNames) {
428
+ const sorted = [];
429
+ const visited = /* @__PURE__ */ new Set();
430
+ const visiting = /* @__PURE__ */ new Set();
431
+ const visit = (typeName) => {
432
+ if (visiting.has(typeName)) {
433
+ return;
434
+ }
435
+ if (visited.has(typeName)) {
436
+ return;
437
+ }
438
+ visiting.add(typeName);
439
+ const dependencies = this.getTypeDependencies(typeName);
440
+ for (const dep of dependencies) {
441
+ visit(dep);
442
+ }
443
+ visiting.delete(typeName);
444
+ visited.add(typeName);
445
+ sorted.push(typeName);
446
+ };
447
+ for (const typeName of typeNames) {
448
+ visit(typeName);
449
+ }
450
+ return sorted;
451
+ }
452
+ /**
453
+ * Generate IdValue type definition (generic type)
454
+ */
455
+ generateIdValueType(typeName) {
456
+ return `export type ${typeName}<T = string> = {
457
+ id: string;
458
+ value: T;
459
+ };
460
+
461
+ `;
462
+ }
463
+ /**
464
+ * Generate all types as a single file content
465
+ */
466
+ generateAllTypes(sampleHit) {
467
+ const rootType = this.inferType(sampleHit, []);
468
+ const typesToGenerate = /* @__PURE__ */ new Set();
469
+ this.collectTypes(rootType, typesToGenerate);
470
+ const rootTypeName = rootType.type;
471
+ if (rootType.nestedTypes.size > 0 && !rootType.isArray) {
472
+ typesToGenerate.add(rootTypeName);
473
+ }
474
+ const sortedTypes = this.sortTypesByDependencies(Array.from(typesToGenerate));
475
+ const lines = [];
476
+ lines.push("/**");
477
+ lines.push(` * Generated TypeScript types for Algolia index: ${this.indexName}`);
478
+ lines.push(" * This file is auto-generated. Do not edit manually.");
479
+ lines.push(" */");
480
+ lines.push("");
481
+ if (this.idValueTypes.size > 0) {
482
+ const idValueTypeName = Array.from(this.idValueTypes)[0];
483
+ lines.push(this.generateIdValueType(idValueTypeName));
484
+ }
485
+ for (const typeName of sortedTypes) {
486
+ const typeCode = this.typeMap.get(typeName);
487
+ if (typeCode) {
488
+ lines.push(typeCode);
489
+ }
490
+ }
491
+ return lines.join("\n");
492
+ }
493
+ };
494
+ function generateTypeScriptTypes(sampleHit, config) {
495
+ const generator = new TypeGenerator(config);
496
+ return generator.generateAllTypes(sampleHit);
497
+ }
498
+
499
+ // src/utils/fetch-algolia-data.ts
500
+ async function fetchAlgoliaData(filePath, generatorConfig, overwrite) {
501
+ console.log(`
502
+ Processing file: ${filePath}`);
503
+ const resolvedPath = (0, import_path2.resolve)(process.cwd(), filePath);
504
+ if ((0, import_fs3.existsSync)(resolvedPath) && !overwrite) {
505
+ throw new Error(
506
+ `File already exists: ${resolvedPath}
507
+ Set overwrite: true in config to allow overwriting existing files.`
508
+ );
509
+ }
510
+ console.log(`Connecting to Algolia...`);
511
+ console.log(`App ID: ${generatorConfig.appId}`);
512
+ let client;
513
+ try {
514
+ client = (0, import_algoliasearch.algoliasearch)(
515
+ generatorConfig.appId,
516
+ generatorConfig.searchKey
517
+ );
518
+ } catch (error) {
519
+ throw new Error(
520
+ `Failed to initialize Algolia client: ${error instanceof Error ? error.message : String(error)}`
521
+ );
522
+ }
523
+ console.log(`Fetching sample record from index: ${generatorConfig.indexName}`);
524
+ let results;
525
+ try {
526
+ results = await client.search([
527
+ {
528
+ indexName: generatorConfig.indexName,
529
+ params: {
530
+ query: "",
531
+ hitsPerPage: 1
532
+ }
533
+ }
534
+ ]);
535
+ } catch (error) {
536
+ let errorMessage;
537
+ if (error instanceof Error) {
538
+ errorMessage = error.message;
539
+ } else if (error && typeof error === "object") {
540
+ const errorObj = error;
541
+ if (errorObj.message) {
542
+ errorMessage = String(errorObj.message);
543
+ } else if (errorObj.status) {
544
+ errorMessage = `HTTP ${errorObj.status}: ${errorObj.statusText || "Unknown error"}`;
545
+ } else {
546
+ try {
547
+ errorMessage = JSON.stringify(error, null, 2);
548
+ } catch {
549
+ errorMessage = String(error);
550
+ }
551
+ }
552
+ } else {
553
+ errorMessage = String(error);
554
+ }
555
+ throw new Error(
556
+ `Failed to fetch data from Algolia index "${generatorConfig.indexName}" (App ID: ${generatorConfig.appId}): ${errorMessage}`
557
+ );
558
+ }
559
+ if (!results.results || results.results.length === 0) {
560
+ throw new Error(`No results found in Algolia index: ${generatorConfig.indexName}`);
561
+ }
562
+ const result = results.results[0];
563
+ if (!("hits" in result) || !result.hits || result.hits.length === 0) {
564
+ throw new Error(`No hits found in Algolia index: ${generatorConfig.indexName}`);
565
+ }
566
+ const sampleHit = result.hits[0];
567
+ console.log("Sample record fetched successfully");
568
+ console.log(`ObjectID: ${sampleHit.objectID || "N/A"}`);
569
+ const fileContent = generateTypeScriptTypes(sampleHit, generatorConfig);
570
+ const dir = (0, import_path2.dirname)(resolvedPath);
571
+ if (!(0, import_fs3.existsSync)(dir)) {
572
+ (0, import_fs3.mkdirSync)(dir, { recursive: true });
573
+ }
574
+ (0, import_fs3.writeFileSync)(resolvedPath, fileContent, "utf-8");
575
+ console.log(`Generated file: ${filePath}`);
576
+ }
577
+
578
+ // src/index.ts
579
+ var main = async (configPath) => {
580
+ try {
581
+ const config = await loadConfig(configPath);
582
+ console.log("Config loaded successfully");
583
+ const generatesArray = Array.isArray(config.generates) ? config.generates : [config.generates];
584
+ for (const urlSchema of generatesArray) {
585
+ for (const [filePath, generatorConfig] of Object.entries(urlSchema)) {
586
+ try {
587
+ await fetchAlgoliaData(filePath, generatorConfig, config.overwrite);
588
+ } catch (error) {
589
+ console.error(`
590
+ Error processing file: ${filePath}`);
591
+ if (error instanceof Error) {
592
+ console.error(error.message);
593
+ if (error.stack) {
594
+ console.error(error.stack);
595
+ }
596
+ } else {
597
+ try {
598
+ console.error(JSON.stringify(error, null, 2));
599
+ } catch {
600
+ console.error(String(error));
601
+ }
602
+ }
603
+ }
604
+ }
605
+ }
606
+ } catch (error) {
607
+ console.error("Error loading config:");
608
+ if (error instanceof Error) {
609
+ console.error(error.message);
610
+ } else {
611
+ console.error(String(error));
612
+ }
613
+ process.exit(1);
614
+ }
28
615
  };
29
616
  // Annotate the CommonJS export names for ESM import in node:
30
617
  0 && (module.exports = {
31
- main
618
+ main,
619
+ validateConfig,
620
+ validateGeneratorConfig,
621
+ validateUrlSchema
32
622
  });
package/dist/index.d.cts CHANGED
@@ -1,3 +1,37 @@
1
- declare const main: () => void;
1
+ type InstanceOrArray<T> = T | T[];
2
+ type UrlSchema = {
3
+ [url: string]: AlgoliaCodegenGeneratorConfig;
4
+ };
5
+ type AlgoliaCodegenGeneratorConfig = {
6
+ appId: string;
7
+ searchKey: string;
8
+ indexName: string;
9
+ prefix?: string;
10
+ postfix?: string;
11
+ };
12
+ type AlgoliaCodegenConfig = {
13
+ overwrite: boolean;
14
+ generates: InstanceOrArray<UrlSchema>;
15
+ };
2
16
 
3
- export { main };
17
+ /**
18
+ * Validates the structure of AlgoliaCodegenConfig
19
+ */
20
+ declare function validateConfig(config: unknown, configPath: string): asserts config is AlgoliaCodegenConfig;
21
+
22
+ /**
23
+ * Validates a UrlSchema object
24
+ */
25
+ declare function validateUrlSchema(urlSchema: unknown, path: string): asserts urlSchema is UrlSchema;
26
+
27
+ /**
28
+ * Validates AlgoliaCodegenGeneratorConfig
29
+ */
30
+ declare function validateGeneratorConfig(config: unknown, path: string): asserts config is AlgoliaCodegenGeneratorConfig;
31
+
32
+ /**
33
+ * Main function to load and process configuration
34
+ */
35
+ declare const main: (configPath?: string) => Promise<void>;
36
+
37
+ export { type AlgoliaCodegenConfig, type AlgoliaCodegenGeneratorConfig, type InstanceOrArray, type UrlSchema, main, validateConfig, validateGeneratorConfig, validateUrlSchema };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,37 @@
1
- declare const main: () => void;
1
+ type InstanceOrArray<T> = T | T[];
2
+ type UrlSchema = {
3
+ [url: string]: AlgoliaCodegenGeneratorConfig;
4
+ };
5
+ type AlgoliaCodegenGeneratorConfig = {
6
+ appId: string;
7
+ searchKey: string;
8
+ indexName: string;
9
+ prefix?: string;
10
+ postfix?: string;
11
+ };
12
+ type AlgoliaCodegenConfig = {
13
+ overwrite: boolean;
14
+ generates: InstanceOrArray<UrlSchema>;
15
+ };
2
16
 
3
- export { main };
17
+ /**
18
+ * Validates the structure of AlgoliaCodegenConfig
19
+ */
20
+ declare function validateConfig(config: unknown, configPath: string): asserts config is AlgoliaCodegenConfig;
21
+
22
+ /**
23
+ * Validates a UrlSchema object
24
+ */
25
+ declare function validateUrlSchema(urlSchema: unknown, path: string): asserts urlSchema is UrlSchema;
26
+
27
+ /**
28
+ * Validates AlgoliaCodegenGeneratorConfig
29
+ */
30
+ declare function validateGeneratorConfig(config: unknown, path: string): asserts config is AlgoliaCodegenGeneratorConfig;
31
+
32
+ /**
33
+ * Main function to load and process configuration
34
+ */
35
+ declare const main: (configPath?: string) => Promise<void>;
36
+
37
+ export { type AlgoliaCodegenConfig, type AlgoliaCodegenGeneratorConfig, type InstanceOrArray, type UrlSchema, main, validateConfig, validateGeneratorConfig, validateUrlSchema };