@content-collections/core 0.3.0 → 0.4.0

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/README.md CHANGED
@@ -110,6 +110,18 @@ Transform your content into type-safe data collections. Eliminate the need for m
110
110
 
111
111
  For a more detailed guide, please refer to the [documentation](https://content-collections.dev/docs/guides/getting-started).
112
112
 
113
+ ## Sponsors
114
+
115
+ <a href="https://supastarter.dev">
116
+ <picture>
117
+ <source media="(prefers-color-scheme: dark)" srcset="./assets/sponsors/supastarter/dark.svg">
118
+ <source media="(prefers-color-scheme: light)" srcset="./assets/sponsors/supastarter/light.svg">
119
+ <img alt="supastarter" src="./assets/sponsors/supastarter/light.svg" height="64">
120
+ </picture>
121
+ </a>
122
+
123
+ ### [Become a sponsor](https://github.com/sponsors/sdorra)
124
+
113
125
  ## License
114
126
 
115
127
  Content Collections is licensed under the [MIT License](./LICENSE).
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ZodRawShape, z, ZodObject, ZodTypeAny, ZodString } from 'zod';
1
+ import z, { ZodRawShape, z as z$1, ZodObject, ZodTypeAny, ZodString } from 'zod';
2
2
  import { parse } from 'yaml';
3
3
 
4
4
  type Parsers = typeof parsers;
@@ -23,6 +23,14 @@ declare const parsers: {
23
23
 
24
24
  type CacheFn = <TInput, TOutput>(input: TInput, compute: (input: TInput) => Promise<TOutput> | TOutput) => Promise<TOutput>;
25
25
 
26
+ declare const literalSchema: z.ZodUnion<[z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull, z.ZodUndefined]>;
27
+ type Literal = z.infer<typeof literalSchema>;
28
+ type Json = Literal | {
29
+ [key: string]: Json;
30
+ } | Json[];
31
+ declare const jsonObjectScheme: z.ZodRecord<z.ZodString, z.ZodType<Json, z.ZodTypeDef, Json>>;
32
+ type JSONObject = z.infer<typeof jsonObjectScheme>;
33
+
26
34
  type Meta = {
27
35
  filePath: string;
28
36
  fileName: string;
@@ -38,14 +46,14 @@ type AddContent<TShape extends ZodRawShape> = TShape extends {
38
46
  } ? TShape : TShape & WithContent;
39
47
  type GetParsedShape<TParser extends Parser, TShape extends ZodRawShape> = Parsers[TParser]["hasContent"] extends true ? AddContent<TShape> : TShape;
40
48
  type GetShape<TParser extends Parser | undefined, TShape extends ZodRawShape> = TParser extends Parser ? GetParsedShape<TParser, TShape> : AddContent<TShape>;
41
- type Schema<TParser extends Parser | undefined, TShape extends ZodRawShape> = z.infer<ZodObject<GetShape<TParser, TShape>>> & {
49
+ type Schema<TParser extends Parser | undefined, TShape extends ZodRawShape> = z$1.infer<ZodObject<GetShape<TParser, TShape>>> & {
42
50
  _meta: Meta;
43
51
  };
44
52
  type Context = {
45
53
  documents<TCollection extends AnyCollection>(collection: TCollection): Array<Schema<TCollection["parser"], TCollection["schema"]>>;
46
54
  cache: CacheFn;
47
55
  };
48
- type Z = typeof z;
56
+ type Z = typeof z$1;
49
57
  type CollectionRequest<TName extends string, TShape extends ZodRawShape, TParser, TSchema, TTransformResult, TDocument> = {
50
58
  name: TName;
51
59
  parser?: TParser;
@@ -62,7 +70,13 @@ type Collection<TName extends string, TShape extends ZodRawShape, TParser extend
62
70
  parser: TParser;
63
71
  };
64
72
  type AnyCollection = Collection<any, ZodRawShape, Parser, any, any, any>;
65
- declare function defineCollection<TName extends string, TShape extends ZodRawShape, TParser extends Parser = "frontmatter", TSchema = Schema<TParser, TShape>, TTransformResult = never, TDocument = [TTransformResult] extends [never] ? Schema<TParser, TShape> : Awaited<TTransformResult>>(collection: CollectionRequest<TName, TShape, TParser, TSchema, TTransformResult, TDocument>): Collection<TName, TShape, TParser, TSchema, TTransformResult, TDocument>;
73
+ type NonJSONObjectError = "The return type of the transform function must be an valid JSONObject, the following type is not valid:";
74
+ declare const InvalidReturnTypeSymbol: unique symbol;
75
+ type InvalidReturnType<TMessage extends string, TObject> = {
76
+ [InvalidReturnTypeSymbol]: TMessage;
77
+ object: TObject;
78
+ };
79
+ declare function defineCollection<TName extends string, TShape extends ZodRawShape, TParser extends Parser = "frontmatter", TSchema = Schema<TParser, TShape>, TTransformResult = never, TDocument = [TTransformResult] extends [never] ? Schema<TParser, TShape> : Awaited<TTransformResult>, TResult = TDocument extends JSONObject ? Collection<TName, TShape, TParser, TSchema, TTransformResult, TDocument> : InvalidReturnType<NonJSONObjectError, TDocument>>(collection: CollectionRequest<TName, TShape, TParser, TSchema, TTransformResult, TDocument>): TResult;
66
80
  type Cache = "memory" | "file" | "none";
67
81
  type Configuration<TCollections extends Array<AnyCollection>> = {
68
82
  collections: TCollections;
@@ -107,12 +121,17 @@ type TransformerEvents = {
107
121
  file: CollectionFile;
108
122
  error: TransformError;
109
123
  };
124
+ "transformer:result-error": {
125
+ collection: AnyCollection;
126
+ document: any;
127
+ error: TransformError;
128
+ };
110
129
  "transformer:error": {
111
130
  collection: AnyCollection;
112
131
  error: TransformError;
113
132
  };
114
133
  };
115
- type ErrorType$1 = "Validation" | "Configuration" | "Transform";
134
+ type ErrorType$1 = "Validation" | "Configuration" | "Transform" | "Result";
116
135
  declare class TransformError extends Error {
117
136
  type: ErrorType$1;
118
137
  constructor(type: ErrorType$1, message: string);
@@ -167,7 +186,7 @@ declare function createBuilder(configurationPath: string, options?: Options): Pr
167
186
  unsubscribe: () => Promise<void>;
168
187
  }>;
169
188
  on: {
170
- <TKey extends "builder:start" | "builder:end" | "collector:read-error" | "collector:parse-error" | "transformer:validation-error" | "transformer:error" | "watcher:file-changed">(key: TKey, listener: (event: Events[TKey]) => void): void;
189
+ <TKey extends "builder:start" | "builder:end" | "collector:read-error" | "collector:parse-error" | "transformer:validation-error" | "transformer:result-error" | "transformer:error" | "watcher:file-changed">(key: TKey, listener: (event: Events[TKey]) => void): void;
171
190
  <TKey_1 extends "_error" | "_all">(key: TKey_1, listener: (event: SystemEvents[TKey_1]) => void): void;
172
191
  };
173
192
  }>;
package/dist/index.js CHANGED
@@ -16,6 +16,7 @@ function orderByPath(a, b) {
16
16
  }
17
17
 
18
18
  // src/config.ts
19
+ var InvalidReturnTypeSymbol = Symbol(`InvalidReturnType`);
19
20
  function defineCollection(collection) {
20
21
  let typeName = collection.typeName;
21
22
  if (!typeName) {
@@ -44,9 +45,9 @@ import path from "path";
44
45
  // package.json
45
46
  var package_default = {
46
47
  name: "@content-collections/core",
47
- version: "0.3.0",
48
+ version: "0.4.0",
48
49
  type: "module",
49
- main: "dist/index.cjs",
50
+ main: "dist/index.js",
50
51
  types: "./dist/index.d.ts",
51
52
  exports: {
52
53
  "./package.json": "./package.json",
@@ -121,6 +122,7 @@ async function compile(configurationPath, outfile) {
121
122
  }
122
123
  await esbuild.build({
123
124
  entryPoints: [configurationPath],
125
+ packages: "external",
124
126
  external: [
125
127
  ...Object.keys(package_default.dependencies),
126
128
  "@content-collections/*"
@@ -347,7 +349,23 @@ async function createWriter(directory) {
347
349
 
348
350
  // src/transformer.ts
349
351
  import { basename, dirname, extname } from "path";
350
- import { z as z2 } from "zod";
352
+ import { z as z3 } from "zod";
353
+
354
+ // src/json.ts
355
+ import z2 from "zod";
356
+ var literalSchema = z2.union([
357
+ z2.string(),
358
+ z2.number(),
359
+ z2.boolean(),
360
+ z2.null(),
361
+ z2.undefined()
362
+ ]);
363
+ var jsonSchema = z2.lazy(
364
+ () => z2.union([literalSchema, z2.array(jsonSchema), z2.record(jsonSchema)])
365
+ );
366
+ var jsonObjectScheme = z2.record(jsonSchema);
367
+
368
+ // src/transformer.ts
351
369
  var TransformError = class extends Error {
352
370
  type;
353
371
  constructor(type, message) {
@@ -366,10 +384,10 @@ function createTransformer(emitter, cacheManager) {
366
384
  function createSchema(parserName, schema) {
367
385
  const parser = parsers[parserName];
368
386
  if (!parser.hasContent) {
369
- return z2.object(schema);
387
+ return z3.object(schema);
370
388
  }
371
- return z2.object({
372
- content: z2.string(),
389
+ return z3.object({
390
+ content: z3.string(),
373
391
  ...schema
374
392
  });
375
393
  }
@@ -432,12 +450,16 @@ function createTransformer(emitter, cacheManager) {
432
450
  if (collection.transform) {
433
451
  const docs = [];
434
452
  for (const doc of collection.documents) {
435
- const cache = cacheManager.cache(collection.name, doc.document._meta.path);
453
+ const cache = cacheManager.cache(
454
+ collection.name,
455
+ doc.document._meta.path
456
+ );
436
457
  const context = createContext(collections, cache);
437
458
  try {
459
+ const document = await collection.transform(doc.document, context);
438
460
  docs.push({
439
461
  ...doc,
440
- document: await collection.transform(doc.document, context)
462
+ document
441
463
  });
442
464
  await cache.tidyUp();
443
465
  } catch (error) {
@@ -459,13 +481,30 @@ function createTransformer(emitter, cacheManager) {
459
481
  }
460
482
  return collection.documents;
461
483
  }
484
+ async function validateDocuments(collection, documents) {
485
+ const docs = [];
486
+ for (const doc of documents) {
487
+ let parsedData = await jsonObjectScheme.safeParseAsync(doc.document);
488
+ if (parsedData.success) {
489
+ docs.push(doc);
490
+ } else {
491
+ emitter.emit("transformer:result-error", {
492
+ collection,
493
+ document: doc.document,
494
+ error: new TransformError("Result", parsedData.error.message)
495
+ });
496
+ }
497
+ }
498
+ return docs;
499
+ }
462
500
  return async (untransformedCollections) => {
463
501
  const promises = untransformedCollections.map(
464
502
  (collection) => parseCollection(collection)
465
503
  );
466
504
  const collections = await Promise.all(promises);
467
505
  for (const collection of collections) {
468
- collection.documents = await transformCollection(collections, collection);
506
+ const documents = await transformCollection(collections, collection);
507
+ collection.documents = await validateDocuments(collection, documents);
469
508
  }
470
509
  return collections;
471
510
  };
@@ -475,9 +514,9 @@ function createTransformer(emitter, cacheManager) {
475
514
  import micromatch from "micromatch";
476
515
  import path4 from "path";
477
516
  function createSynchronizer(readCollectionFile, collections, baseDirectory = ".") {
478
- function findCollection(filePath) {
517
+ function findCollections(filePath) {
479
518
  const resolvedFilePath = path4.resolve(filePath);
480
- return collections.find((collection) => {
519
+ return collections.filter((collection) => {
481
520
  return resolvedFilePath.startsWith(
482
521
  path4.resolve(baseDirectory, collection.directory)
483
522
  );
@@ -493,51 +532,56 @@ function createSynchronizer(readCollectionFile, collections, baseDirectory = "."
493
532
  return relativePath;
494
533
  }
495
534
  function resolve(filePath) {
496
- const collection = findCollection(filePath);
497
- if (!collection) {
498
- return null;
499
- }
500
- const relativePath = createRelativePath(collection.directory, filePath);
501
- if (!micromatch.isMatch(relativePath, collection.include)) {
502
- return null;
503
- }
504
- return {
505
- collection,
506
- relativePath
507
- };
535
+ const collections2 = findCollections(filePath);
536
+ return collections2.map((collection) => {
537
+ const relativePath = createRelativePath(collection.directory, filePath);
538
+ return {
539
+ collection,
540
+ relativePath
541
+ };
542
+ }).filter(({ collection, relativePath }) => {
543
+ return micromatch.isMatch(relativePath, collection.include);
544
+ });
508
545
  }
509
546
  function deleted(filePath) {
510
- const resolved = resolve(filePath);
511
- if (!resolved) {
547
+ const resolvedCollections = resolve(filePath);
548
+ if (resolvedCollections.length === 0) {
512
549
  return false;
513
550
  }
514
- const { collection, relativePath } = resolved;
515
- const index = collection.files.findIndex(
516
- (file) => file.path === relativePath
517
- );
518
- const deleted2 = collection.files.splice(index, 1);
519
- return deleted2.length > 0;
551
+ let changed2 = false;
552
+ for (const { collection, relativePath } of resolvedCollections) {
553
+ const index = collection.files.findIndex(
554
+ (file) => file.path === relativePath
555
+ );
556
+ const deleted2 = collection.files.splice(index, 1);
557
+ if (deleted2.length > 0) {
558
+ changed2 = true;
559
+ }
560
+ }
561
+ return changed2;
520
562
  }
521
563
  async function changed(filePath) {
522
- const resolved = resolve(filePath);
523
- if (!resolved) {
564
+ const resolvedCollections = resolve(filePath);
565
+ if (resolvedCollections.length === 0) {
524
566
  return false;
525
567
  }
526
- const { collection, relativePath } = resolved;
527
- const index = collection.files.findIndex(
528
- (file2) => file2.path === relativePath
529
- );
530
- const file = await readCollectionFile(collection, relativePath);
531
- if (!file) {
532
- return false;
533
- }
534
- if (index === -1) {
535
- collection.files.push(file);
536
- collection.files.sort(orderByPath);
537
- } else {
538
- collection.files[index] = file;
568
+ let changed2 = false;
569
+ for (const { collection, relativePath } of resolvedCollections) {
570
+ const index = collection.files.findIndex(
571
+ (file2) => file2.path === relativePath
572
+ );
573
+ const file = await readCollectionFile(collection, relativePath);
574
+ if (file) {
575
+ changed2 = true;
576
+ if (index === -1) {
577
+ collection.files.push(file);
578
+ collection.files.sort(orderByPath);
579
+ } else {
580
+ collection.files[index] = file;
581
+ }
582
+ }
539
583
  }
540
- return true;
584
+ return changed2;
541
585
  }
542
586
  return {
543
587
  deleted,
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@content-collections/core",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
- "main": "dist/index.cjs",
5
+ "main": "dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "exports": {
8
8
  "./package.json": "./package.json",
package/dist/apidoc.d.ts DELETED
@@ -1,186 +0,0 @@
1
- import { z } from 'zod';
2
- import { ZodObject } from 'zod';
3
- import { ZodRawShape } from 'zod';
4
- import { ZodString } from 'zod';
5
- import { ZodTypeAny } from 'zod';
6
-
7
- declare type AddContent<TShape extends ZodRawShape> = TShape extends {
8
- content: ZodTypeAny;
9
- } ? TShape : TShape & WithContent;
10
-
11
- export declare type AnyCollection = Collection<any, ZodRawShape, any, any, any>;
12
-
13
- export declare type AnyConfiguration = Configuration<Array<AnyCollection>>;
14
-
15
- export declare type Builder = Awaited<ReturnType<typeof createBuilder>>;
16
-
17
- export declare type BuilderEvents = {
18
- "builder:start": {
19
- startedAt: number;
20
- };
21
- "builder:end": {
22
- startedAt: number;
23
- endedAt: number;
24
- };
25
- };
26
-
27
- export declare class CollectError extends Error {
28
- type: ErrorType$2;
29
- constructor(type: ErrorType$2, message: string);
30
- }
31
-
32
- export declare type Collection<TName extends string, TShape extends ZodRawShape, TSchema, TTransformResult, TDocument> = Omit<CollectionRequest<TName, TShape, TSchema, TTransformResult, TDocument>, "schema"> & {
33
- typeName: string;
34
- schema: TShape;
35
- };
36
-
37
- declare type CollectionByName<TConfiguration extends AnyConfiguration> = {
38
- [TCollection in TConfiguration["collections"][number] as TCollection["name"]]: TCollection;
39
- };
40
-
41
- declare type CollectionFile = {
42
- data: {
43
- content: string;
44
- [key: string]: unknown;
45
- };
46
- path: string;
47
- };
48
-
49
- export declare type CollectionRequest<TName extends string, TShape extends ZodRawShape, TSchema, TTransformResult, TDocument> = {
50
- /**
51
- * The name of the collection
52
- */
53
- name: TName;
54
- /**
55
- * The name of the generated TypeScript type.
56
- * If the typeName is undefined the pluralized name of the collection will be used.
57
- */
58
- typeName?: string;
59
- schema: (z: Z) => TShape;
60
- transform?: (context: Context, data: TSchema) => TTransformResult;
61
- directory: string | string[];
62
- include: string | string[];
63
- onSuccess?: (documents: Array<TDocument>) => void | Promise<void>;
64
- };
65
-
66
- declare type CollectorEvents = {
67
- "collector:read-error": {
68
- filePath: string;
69
- error: CollectError;
70
- };
71
- "collector:parse-error": {
72
- filePath: string;
73
- error: CollectError;
74
- };
75
- };
76
-
77
- export declare type Configuration<TCollections extends Array<AnyCollection>> = {
78
- collections: TCollections;
79
- };
80
-
81
- export declare class ConfigurationError extends Error {
82
- type: ErrorType;
83
- constructor(type: ErrorType, message: string);
84
- }
85
-
86
- export declare type Context = {
87
- documents<TCollection extends AnyCollection>(collection: TCollection): Array<Schema<TCollection["schema"]>>;
88
- };
89
-
90
- export declare function createBuilder(configurationPath: string, options?: Options): Promise<{
91
- sync: (modification: Modification, filePath: string) => Promise<boolean>;
92
- build: () => Promise<void>;
93
- watch: () => Promise<{
94
- unsubscribe: () => Promise<void>;
95
- }>;
96
- on: {
97
- <TKey extends "builder:start" | "builder:end" | "collector:read-error" | "collector:parse-error" | "transformer:validation-error" | "transformer:error" | "watcher:file-changed">(key: TKey, listener: (event: Events[TKey]) => void): void;
98
- <TKey_1 extends "_error" | "_all">(key: TKey_1, listener: (event: SystemEvents[TKey_1]) => void): void;
99
- };
100
- }>;
101
-
102
- export declare function defineCollection<TName extends string, TShape extends ZodRawShape, TSchema = Schema<TShape>, TTransformResult = never, TDocument = [TTransformResult] extends [never] ? Schema<TShape> : Awaited<TTransformResult>>(collection: CollectionRequest<TName, TShape, TSchema, TTransformResult, TDocument>): Collection<TName, TShape, TSchema, TTransformResult, TDocument>;
103
-
104
- export declare function defineConfig<TConfig extends AnyConfiguration>(config: TConfig): TConfig;
105
-
106
- declare type ErrorEvent = EventWithError & SystemEvent;
107
-
108
- declare type ErrorType$1 = "Validation" | "Configuration" | "Transform";
109
-
110
- declare type ErrorType$2 = "Parse" | "Read";
111
-
112
- declare type ErrorType = "Read" | "Compile";
113
-
114
- declare type Events = BuilderEvents & CollectorEvents & TransformerEvents & WatcherEvents;
115
-
116
- declare type EventWithError = {
117
- error: Error;
118
- };
119
-
120
- declare type GetDocument<TCollection extends AnyCollection> = TCollection extends Collection<any, ZodRawShape, any, any, infer TDocument> ? TDocument : never;
121
-
122
- export declare type GetTypeByName<TConfiguration extends AnyConfiguration, TName extends keyof CollectionByName<TConfiguration>, TCollection = CollectionByName<TConfiguration>[TName]> = TCollection extends AnyCollection ? GetDocument<TCollection> : never;
123
-
124
- export declare type Meta = {
125
- filePath: string;
126
- fileName: string;
127
- directory: string;
128
- path: string;
129
- extension: string;
130
- };
131
-
132
- export declare type Modification = "create" | "update" | "delete";
133
-
134
- declare type Options$1 = {
135
- configName: string;
136
- cacheDir?: string;
137
- };
138
-
139
- declare type Options = Options$1 & {
140
- outputDir?: string;
141
- };
142
-
143
- export declare type Schema<TShape extends ZodRawShape> = z.infer<ZodObject<AddContent<TShape>>> & {
144
- _meta: Meta;
145
- };
146
-
147
- declare type SystemEvent = {
148
- _event: string;
149
- };
150
-
151
- declare type SystemEvents = {
152
- _error: ErrorEvent;
153
- _all: SystemEvent;
154
- };
155
-
156
- declare type TransformerEvents = {
157
- "transformer:validation-error": {
158
- collection: AnyCollection;
159
- file: CollectionFile;
160
- error: TransformError;
161
- };
162
- "transformer:error": {
163
- collection: AnyCollection;
164
- error: TransformError;
165
- };
166
- };
167
-
168
- export declare class TransformError extends Error {
169
- type: ErrorType$1;
170
- constructor(type: ErrorType$1, message: string);
171
- }
172
-
173
- declare type WatcherEvents = {
174
- "watcher:file-changed": {
175
- filePath: string;
176
- modification: Modification;
177
- };
178
- };
179
-
180
- declare type WithContent = {
181
- content: ZodString;
182
- };
183
-
184
- declare type Z = typeof z;
185
-
186
- export { }
package/dist/index.cjs DELETED
@@ -1,416 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
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
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- applyConfig: () => applyConfig,
34
- build: () => build2,
35
- createRunner: () => createRunner,
36
- defineCollection: () => defineCollection,
37
- defineConfig: () => defineConfig
38
- });
39
- module.exports = __toCommonJS(src_exports);
40
- var import_path2 = __toESM(require("path"), 1);
41
-
42
- // src/applyConfig.ts
43
- var esbuild = __toESM(require("esbuild"), 1);
44
- var import_promises = __toESM(require("fs/promises"), 1);
45
- var import_node_path = __toESM(require("path"), 1);
46
-
47
- // package.json
48
- var package_default = {
49
- name: "@mdx-collections/core",
50
- version: "1.0.0",
51
- type: "module",
52
- main: "dist/index.cjs",
53
- exports: {
54
- "./package.json": "./package.json",
55
- ".": {
56
- import: "./dist/index.js",
57
- require: "./dist/index.cjs"
58
- }
59
- },
60
- types: "./dist/index.d.ts",
61
- scripts: {
62
- build: "tsup src/index.ts --format esm,cjs --dts -d dist",
63
- typecheck: "tsc",
64
- test: "vitest --run --coverage"
65
- },
66
- devDependencies: {
67
- "@types/micromatch": "^4.0.6",
68
- "@types/node": "^20.9.0",
69
- "@types/pluralize": "^0.0.33",
70
- "@vitest/coverage-v8": "^0.34.6",
71
- tsup: "^7.2.0",
72
- tsx: "^4.1.1",
73
- typescript: "^5.3.2",
74
- vitest: "^0.34.6"
75
- },
76
- dependencies: {
77
- camelcase: "^8.0.0",
78
- esbuild: "^0.19.5",
79
- "fast-glob": "^3.3.2",
80
- "gray-matter": "^4.0.3",
81
- micromatch: "^4.0.5",
82
- pluralize: "^8.0.0",
83
- zod: "^3.22.4"
84
- }
85
- };
86
-
87
- // src/applyConfig.ts
88
- var importPathPlugin = {
89
- name: "import-path",
90
- setup(build3) {
91
- build3.onResolve({ filter: /^\@mdx-collections\/core$/ }, () => {
92
- return { path: import_node_path.default.join(__dirname, "index.ts"), external: true };
93
- });
94
- }
95
- };
96
- function resolveCacheDir(config, options) {
97
- if (options.cacheDir) {
98
- return options.cacheDir;
99
- }
100
- return import_node_path.default.join(import_node_path.default.dirname(config), ".mdx-collections", "cache");
101
- }
102
- async function applyConfig(config, options = {
103
- configName: "mdx-collection-config.mjs"
104
- }) {
105
- const cacheDir = resolveCacheDir(config, options);
106
- await import_promises.default.mkdir(cacheDir, { recursive: true });
107
- const outfile = import_node_path.default.join(cacheDir, options.configName);
108
- const plugins = [];
109
- if (process.env.NODE_ENV === "test") {
110
- plugins.push(importPathPlugin);
111
- }
112
- await esbuild.build({
113
- entryPoints: [config],
114
- external: [...Object.keys(package_default.dependencies), "@mdx-collections/*"],
115
- bundle: true,
116
- platform: "node",
117
- format: "esm",
118
- plugins,
119
- outfile
120
- });
121
- const module2 = await import(`file://${import_node_path.default.resolve(outfile)}?x=${Date.now()}`);
122
- return {
123
- ...module2.default,
124
- path: config,
125
- generateTypes: true
126
- };
127
- }
128
-
129
- // src/run.ts
130
- var import_promises3 = __toESM(require("fs/promises"), 1);
131
- var import_node_path2 = __toESM(require("path"), 1);
132
- var import_pluralize = __toESM(require("pluralize"), 1);
133
-
134
- // src/collect.ts
135
- var import_gray_matter = __toESM(require("gray-matter"), 1);
136
- var import_fast_glob = __toESM(require("fast-glob"), 1);
137
- var import_promises2 = require("fs/promises");
138
- var import_path = __toESM(require("path"), 1);
139
- var import_micromatch = __toESM(require("micromatch"), 1);
140
- async function collectFile(directory, filePath) {
141
- const file = await (0, import_promises2.readFile)(import_path.default.join(directory, filePath), "utf-8");
142
- const { data, content: body } = (0, import_gray_matter.default)(file);
143
- return {
144
- data,
145
- body,
146
- path: filePath
147
- };
148
- }
149
- async function resolveCollection(collection) {
150
- const filePaths = await (0, import_fast_glob.default)(collection.include, {
151
- cwd: collection.directory,
152
- onlyFiles: true,
153
- absolute: false
154
- });
155
- const promises = filePaths.map(
156
- (filePath) => collectFile(collection.directory, filePath)
157
- );
158
- return {
159
- ...collection,
160
- files: await Promise.all(promises)
161
- };
162
- }
163
- async function collect(unresolvedCollections) {
164
- const promises = unresolvedCollections.map(
165
- (collection) => resolveCollection(collection)
166
- );
167
- return await Promise.all(promises);
168
- }
169
- function createRelativePath(directory, filePath) {
170
- if (!filePath.startsWith(directory)) {
171
- throw new Error("Path is not in collection directory");
172
- }
173
- let relativePath = filePath.slice(directory.length);
174
- if (relativePath.startsWith("/")) {
175
- relativePath = relativePath.slice(1);
176
- }
177
- return relativePath;
178
- }
179
- function isIncluded(collection, path5) {
180
- if (path5.startsWith(collection.directory)) {
181
- const relativePath = createRelativePath(collection.directory, path5);
182
- return import_micromatch.default.isMatch(relativePath, collection.include);
183
- }
184
- return false;
185
- }
186
- async function syncFile(collection, modification, path5) {
187
- if ("added" === modification) {
188
- const file = await collectFile(collection.directory, path5);
189
- collection.files.push(file);
190
- } else if ("changed" === modification) {
191
- const file = await collectFile(collection.directory, path5);
192
- const index = collection.files.findIndex((file2) => file2.path === path5);
193
- collection.files[index] = file;
194
- } else if ("removed" === modification) {
195
- const index = collection.files.findIndex((file) => file.path === path5);
196
- collection.files.splice(index, 1);
197
- }
198
- }
199
- function sync(collection, modification, path5) {
200
- const relativePath = createRelativePath(collection.directory, path5);
201
- return syncFile(collection, modification, relativePath);
202
- }
203
-
204
- // src/transformer.ts
205
- var TransformError = class extends Error {
206
- type;
207
- constructor(type, message) {
208
- super(message);
209
- this.type = type;
210
- }
211
- };
212
- var throwingErrorHandler = (error) => {
213
- throw error;
214
- };
215
- function isDefined(value) {
216
- return value !== void 0 && value !== null;
217
- }
218
- async function transform(untransformedCollections, errorHandler = throwingErrorHandler) {
219
- async function parseFile(collection, file) {
220
- const { data, body, path: path5 } = file;
221
- let parsedData = await collection.schema.safeParseAsync(data);
222
- if (!parsedData.success) {
223
- errorHandler(new TransformError("Validation", parsedData.error.message));
224
- return null;
225
- }
226
- const document = {
227
- ...parsedData.data,
228
- _meta: {
229
- path: path5
230
- }
231
- };
232
- return {
233
- document,
234
- content: body
235
- };
236
- }
237
- async function parseCollection(collection) {
238
- const promises2 = collection.files.map(
239
- (file) => parseFile(collection, file)
240
- );
241
- return {
242
- ...collection,
243
- documents: (await Promise.all(promises2)).filter(isDefined)
244
- };
245
- }
246
- function createContext(collections2, file) {
247
- return {
248
- content: async () => file.content,
249
- documents: (collection) => {
250
- const resolved = collections2.find((c) => c.name === collection.name);
251
- if (!resolved) {
252
- throw new TransformError(
253
- "Configuration",
254
- `Collection ${collection.name} not found, do you have registered it in your configuration?`
255
- );
256
- }
257
- return resolved.documents.map((doc) => doc.document);
258
- }
259
- };
260
- }
261
- async function transformCollection(collections2, collection) {
262
- if (collection.transform) {
263
- const docs = [];
264
- for (const doc of collection.documents) {
265
- const context = createContext(collections2, doc);
266
- try {
267
- docs.push({
268
- ...doc,
269
- document: await collection.transform(context, doc.document)
270
- });
271
- } catch (error) {
272
- if (error instanceof TransformError) {
273
- errorHandler(error);
274
- } else {
275
- errorHandler(new TransformError("Transform", String(error)));
276
- }
277
- }
278
- }
279
- return docs;
280
- }
281
- return collection.documents;
282
- }
283
- const promises = untransformedCollections.map(
284
- (collection) => parseCollection(collection)
285
- );
286
- const collections = await Promise.all(promises);
287
- for (const collection of collections) {
288
- collection.documents = await transformCollection(collections, collection);
289
- }
290
- return collections;
291
- }
292
-
293
- // src/run.ts
294
- function createArrayConstName(name) {
295
- let suffix = name.charAt(0).toUpperCase() + name.slice(1);
296
- return "all" + (0, import_pluralize.default)(suffix);
297
- }
298
- async function createDataFiles(collections, directory) {
299
- for (const collection of collections) {
300
- const dataPath = import_node_path2.default.join(
301
- directory,
302
- `${createArrayConstName(collection.name)}.json`
303
- );
304
- await import_promises3.default.writeFile(
305
- dataPath,
306
- JSON.stringify(
307
- collection.documents.map((doc) => doc.document),
308
- null,
309
- 2
310
- )
311
- );
312
- }
313
- }
314
- async function createJavaScriptFile(configuration, directory) {
315
- const collections = configuration.collections.map(
316
- ({ name }) => createArrayConstName(name)
317
- );
318
- let content = "";
319
- for (const name of collections) {
320
- content += `import ${name} from "./${name}.json";
321
- `;
322
- }
323
- content += "\n";
324
- content += "export { " + collections.join(", ") + " };\n";
325
- await import_promises3.default.writeFile(import_node_path2.default.join(directory, "index.js"), content, "utf-8");
326
- }
327
- async function createTypeDefinitionFile(configuration, directory) {
328
- const importPath = import_node_path2.default.relative(directory, configuration.path);
329
- let content = `import mdxConfiguration from "${importPath}";
330
- import { GetTypeByName } from "@mdx-collections/core";
331
- `;
332
- const collections = configuration.collections;
333
- for (const collection of collections) {
334
- content += `
335
- `;
336
- content += `export type ${collection.typeName} = GetTypeByName<typeof mdxConfiguration, "${collection.name}">;
337
- `;
338
- content += `export declare const ${createArrayConstName(
339
- collection.name
340
- )}: Array<${collection.typeName}>;
341
- `;
342
- }
343
- content += "\n";
344
- content += "export {};\n";
345
- await import_promises3.default.writeFile(import_node_path2.default.join(directory, "index.d.ts"), content, "utf-8");
346
- }
347
- async function createRunner(configuration, directory) {
348
- await import_promises3.default.mkdir(directory, { recursive: true });
349
- const resolved = await collect(configuration.collections);
350
- await createJavaScriptFile(configuration, directory);
351
- if (configuration.generateTypes) {
352
- await createTypeDefinitionFile(configuration, directory);
353
- }
354
- async function run() {
355
- const collections = await transform(resolved);
356
- await createDataFiles(collections, directory);
357
- for (const collection of collections) {
358
- if (collection.onSuccess) {
359
- await collection.onSuccess(
360
- collection.documents.map((doc) => doc.document)
361
- );
362
- }
363
- }
364
- }
365
- return {
366
- run,
367
- sync: async (event, path5) => {
368
- for (const collection of resolved) {
369
- if (isIncluded(collection, path5)) {
370
- await sync(collection, event, path5);
371
- await run();
372
- }
373
- }
374
- }
375
- };
376
- }
377
-
378
- // src/utils.ts
379
- var import_camelcase = __toESM(require("camelcase"), 1);
380
- var import_pluralize2 = __toESM(require("pluralize"), 1);
381
- function generateTypeName(name) {
382
- const singularName = import_pluralize2.default.singular(name);
383
- return (0, import_camelcase.default)(singularName, { pascalCase: true });
384
- }
385
-
386
- // src/config.ts
387
- function defineCollection(collection) {
388
- let typeName = collection.typeName;
389
- if (!typeName) {
390
- typeName = generateTypeName(collection.name);
391
- }
392
- return {
393
- ...collection,
394
- typeName
395
- };
396
- }
397
- function defineConfig(config) {
398
- return config;
399
- }
400
-
401
- // src/index.ts
402
- async function build2(config) {
403
- const configuration = await applyConfig(config);
404
- const baseDirectory = import_path2.default.dirname(config);
405
- const directory = import_path2.default.join(baseDirectory, ".mdx-collections", "generated");
406
- const runner = await createRunner(configuration, directory);
407
- await runner.run();
408
- }
409
- // Annotate the CommonJS export names for ESM import in node:
410
- 0 && (module.exports = {
411
- applyConfig,
412
- build,
413
- createRunner,
414
- defineCollection,
415
- defineConfig
416
- });
package/dist/index.d.cts DELETED
@@ -1,59 +0,0 @@
1
- import { ZodTypeAny, z } from 'zod';
2
-
3
- type Meta = {
4
- path: string;
5
- };
6
- type Document<TSchema extends ZodTypeAny> = z.infer<TSchema> & {
7
- _meta: Meta;
8
- };
9
- type Context = {
10
- content(): Promise<string>;
11
- documents<TCollection extends AnyCollection>(collection: TCollection): Array<Document<TCollection["schema"]>>;
12
- };
13
- type TransformFn<TSchema extends ZodTypeAny> = ((context: Context, data: Document<TSchema>) => any) | undefined;
14
- type CollectionRequest<TSchema extends ZodTypeAny, TName extends string, TTransform extends TransformFn<TSchema>, TDocument> = {
15
- name: TName;
16
- typeName?: string;
17
- schema: TSchema;
18
- transform?: TTransform;
19
- directory: string;
20
- include: string | string[];
21
- onSuccess?: (documents: Array<TDocument>) => void | Promise<void>;
22
- };
23
- type Collection<TSchema extends ZodTypeAny, TName extends string, TTransform extends TransformFn<TSchema>, TDocument> = CollectionRequest<TSchema, TName, TTransform, TDocument> & {
24
- typeName: string;
25
- };
26
- type AnyCollection = Collection<ZodTypeAny, any, any, any>;
27
- declare function defineCollection<TSchema extends ZodTypeAny, TName extends string, TTransform extends TransformFn<TSchema>, TDocument = [TTransform] extends [(...args: any) => any] ? Awaited<ReturnType<TTransform>> : Document<TSchema>>(collection: CollectionRequest<TSchema, TName, TTransform, TDocument>): Collection<TSchema, TName, TTransform, TDocument>;
28
- type Configuration<TCollections extends Array<AnyCollection>> = {
29
- collections: TCollections;
30
- };
31
- type AnyConfiguration = Configuration<Array<AnyCollection>>;
32
- declare function defineConfig<TConfig extends AnyConfiguration>(config: TConfig): TConfig;
33
-
34
- type InternalConfiguration = {
35
- collections: Array<AnyCollection>;
36
- path: string;
37
- generateTypes?: boolean;
38
- };
39
- type Options = {
40
- configName: string;
41
- cacheDir?: string;
42
- };
43
- declare function applyConfig(config: string, options?: Options): Promise<InternalConfiguration>;
44
-
45
- type Modification = "added" | "changed" | "removed";
46
- type CollectionByName<TConfiguration extends AnyConfiguration> = {
47
- [TCollection in TConfiguration["collections"][number] as TCollection["name"]]: TCollection;
48
- };
49
- type GetDocument<TCollection extends AnyCollection> = TCollection extends Collection<ZodTypeAny, any, any, infer TDocument> ? TDocument : never;
50
- type GetTypeByName<TConfiguration extends AnyConfiguration, TName extends keyof CollectionByName<TConfiguration>, TCollection = CollectionByName<TConfiguration>[TName]> = TCollection extends AnyCollection ? GetDocument<TCollection> : never;
51
-
52
- declare function createRunner(configuration: InternalConfiguration, directory: string): Promise<{
53
- run: () => Promise<void>;
54
- sync: (event: Modification, path: string) => Promise<void>;
55
- }>;
56
-
57
- declare function build(config: string): Promise<void>;
58
-
59
- export { AnyCollection, AnyConfiguration, Collection, CollectionRequest, Configuration, Context, Document, GetTypeByName, Meta, Modification, applyConfig, build, createRunner, defineCollection, defineConfig };