@mearie/codegen 0.0.1-next.3 → 0.0.1-next.4

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,42 +1,18 @@
1
- //#region rolldown:runtime
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 __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
- key = keys[i];
11
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
- get: ((k) => from[k]).bind(null, key),
13
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
- });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
- value: mod,
20
- enumerable: true
21
- }) : target, mod));
22
-
23
- //#endregion
1
+ const require_chunk = require('./chunk-DUogzOV2.cjs');
24
2
  let tinyglobby = require("tinyglobby");
25
- tinyglobby = __toESM(tinyglobby);
3
+ tinyglobby = require_chunk.__toESM(tinyglobby);
26
4
  let picomatch = require("picomatch");
27
- picomatch = __toESM(picomatch);
28
- let __mearie_native = require("@mearie/native");
29
- __mearie_native = __toESM(__mearie_native);
30
- let __mearie_core = require("@mearie/core");
31
- __mearie_core = __toESM(__mearie_core);
5
+ picomatch = require_chunk.__toESM(picomatch);
32
6
  let node_fs_promises = require("node:fs/promises");
33
- node_fs_promises = __toESM(node_fs_promises);
34
- let __mearie_extractor = require("@mearie/extractor");
35
- __mearie_extractor = __toESM(__mearie_extractor);
36
- let node_module = require("node:module");
37
- node_module = __toESM(node_module);
7
+ node_fs_promises = require_chunk.__toESM(node_fs_promises);
8
+ let __mearie_native = require("@mearie/native");
9
+ __mearie_native = require_chunk.__toESM(__mearie_native);
38
10
  let node_path = require("node:path");
39
- node_path = __toESM(node_path);
11
+ node_path = require_chunk.__toESM(node_path);
12
+ let __logtape_logtape = require("@logtape/logtape");
13
+ __logtape_logtape = require_chunk.__toESM(__logtape_logtape);
14
+ let picocolors = require("picocolors");
15
+ picocolors = require_chunk.__toESM(picocolors);
40
16
 
41
17
  //#region src/glob.ts
42
18
  /**
@@ -69,6 +45,265 @@ const createMatcher = (patterns) => {
69
45
  };
70
46
  };
71
47
 
48
+ //#endregion
49
+ //#region src/errors.ts
50
+ /**
51
+ * Custom error class for Mearie-specific errors.
52
+ */
53
+ var MearieError = class MearieError extends Error {
54
+ filePath;
55
+ line;
56
+ column;
57
+ constructor(message, filePath, line, column) {
58
+ super(message);
59
+ this.name = "MearieError";
60
+ this.filePath = filePath;
61
+ this.line = line;
62
+ this.column = column;
63
+ }
64
+ static fromNative(data) {
65
+ if (!data || typeof data !== "object") throw new TypeError("Invalid native error data");
66
+ const error = data;
67
+ const filePath = error.location?.file_path;
68
+ const line = error.location?.line;
69
+ const column = error.location?.column;
70
+ return new MearieError(error.message, filePath, line, column);
71
+ }
72
+ };
73
+ /**
74
+ * Aggregate error for multiple Mearie errors.
75
+ */
76
+ var MearieAggregateError = class extends Error {
77
+ errors;
78
+ constructor(errors, message) {
79
+ super(message ?? `${errors.length} error${errors.length > 1 ? "s" : ""} occurred`);
80
+ this.name = "MearieAggregateError";
81
+ this.errors = errors;
82
+ }
83
+ };
84
+ /**
85
+ * Error thrown when `@vue/compiler-sfc` is not installed.
86
+ */
87
+ var MissingVueCompilerError = class extends Error {
88
+ constructor() {
89
+ super(`
90
+ GraphQL operations cannot be extracted from Vue files without @vue/compiler-sfc.
91
+
92
+ Install it with:
93
+ npm install @vue/compiler-sfc
94
+ # or
95
+ pnpm add @vue/compiler-sfc
96
+ # or
97
+ yarn add @vue/compiler-sfc
98
+ `);
99
+ this.name = "MissingVueCompilerError";
100
+ }
101
+ };
102
+ /**
103
+ * Error thrown when svelte compiler is not installed.
104
+ */
105
+ var MissingSvelteCompilerError = class extends Error {
106
+ constructor() {
107
+ super(`
108
+ GraphQL operations cannot be extracted from Svelte files without svelte.
109
+
110
+ Install it with:
111
+ npm install svelte
112
+ # or
113
+ pnpm add svelte
114
+ # or
115
+ yarn add svelte
116
+ `);
117
+ this.name = "MissingSvelteCompilerError";
118
+ }
119
+ };
120
+ /**
121
+ * Error thrown when TypeScript is not installed.
122
+ */
123
+ var MissingTypeScriptError = class extends Error {
124
+ constructor() {
125
+ super(`
126
+ GraphQL operations cannot be extracted from Vue files without typescript.
127
+
128
+ Install it with:
129
+ npm install typescript
130
+ # or
131
+ pnpm add typescript
132
+ # or
133
+ yarn add typescript
134
+ `);
135
+ this.name = "MissingTypeScriptError";
136
+ }
137
+ };
138
+
139
+ //#endregion
140
+ //#region src/loaders.ts
141
+ /**
142
+ * Loads the Vue compiler dynamically.
143
+ * @returns The Vue compiler module.
144
+ * @throws {MissingVueCompilerError} If `@vue/compiler-sfc` is not installed.
145
+ */
146
+ const loadVueCompiler = async () => {
147
+ try {
148
+ return await import("@vue/compiler-sfc");
149
+ } catch {
150
+ throw new MissingVueCompilerError();
151
+ }
152
+ };
153
+ /**
154
+ * Loads TypeScript dynamically.
155
+ * @returns The TypeScript module.
156
+ * @throws {MissingTypeScriptError} If typescript is not installed.
157
+ */
158
+ const loadTypeScript = async () => {
159
+ try {
160
+ return await Promise.resolve().then(() => require_chunk.__toDynamicImportESM(1)(require("./typescript-ChH5VlJx.cjs")));
161
+ } catch {
162
+ throw new MissingTypeScriptError();
163
+ }
164
+ };
165
+ /**
166
+ * Loads the Svelte compiler dynamically.
167
+ * @returns The Svelte compiler module.
168
+ * @throws {MissingSvelteCompilerError} If svelte is not installed.
169
+ */
170
+ const loadSvelteCompiler = async () => {
171
+ try {
172
+ return await Promise.resolve().then(() => require("./compiler-wSZSa-gf.cjs"));
173
+ } catch {
174
+ throw new MissingSvelteCompilerError();
175
+ }
176
+ };
177
+
178
+ //#endregion
179
+ //#region src/parsers.ts
180
+ const extractVueScript = async (source) => {
181
+ const [vueCompiler, typescript] = await Promise.all([loadVueCompiler(), loadTypeScript()]);
182
+ vueCompiler.registerTS(() => typescript);
183
+ const { descriptor } = vueCompiler.parse(source.code, { filename: source.filePath });
184
+ const blocks = [];
185
+ if (descriptor.script) blocks.push({
186
+ code: descriptor.script.content,
187
+ filePath: source.filePath,
188
+ startLine: source.startLine + descriptor.script.loc.start.line - 1
189
+ });
190
+ if (descriptor.scriptSetup) blocks.push({
191
+ code: descriptor.scriptSetup.content,
192
+ filePath: source.filePath,
193
+ startLine: source.startLine + descriptor.scriptSetup.loc.start.line - 1
194
+ });
195
+ return blocks;
196
+ };
197
+ const extractSvelteScript = async (source) => {
198
+ const ast = (await loadSvelteCompiler()).parse(source.code);
199
+ const blocks = [];
200
+ if (ast.instance?.content) {
201
+ const code = source.code.slice(ast.instance.content.start, ast.instance.content.end);
202
+ const lineOffset = source.code.slice(0, ast.instance.content.start).split("\n").length - 1;
203
+ blocks.push({
204
+ code,
205
+ filePath: `${source.filePath}.instance.ts`,
206
+ startLine: source.startLine + lineOffset
207
+ });
208
+ }
209
+ if (ast.module?.content) {
210
+ const code = source.code.slice(ast.module.content.start, ast.module.content.end);
211
+ const lineOffset = source.code.slice(0, ast.module.content.start).split("\n").length - 1;
212
+ blocks.push({
213
+ code,
214
+ filePath: `${source.filePath}.module.ts`,
215
+ startLine: source.startLine + lineOffset
216
+ });
217
+ }
218
+ return blocks;
219
+ };
220
+ const extractAstroScripts = (source) => {
221
+ const blocks = [];
222
+ const frontmatterMatch = /^---\s*\n([\s\S]*?)\n---/.exec(source.code);
223
+ if (frontmatterMatch) {
224
+ const lineOffset = source.code.slice(0, frontmatterMatch.index).split("\n").length;
225
+ blocks.push({
226
+ code: frontmatterMatch[1],
227
+ filePath: `${source.filePath}.frontmatter.ts`,
228
+ startLine: source.startLine + lineOffset
229
+ });
230
+ }
231
+ const scriptMatches = source.code.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi);
232
+ let index = 0;
233
+ for (const match of scriptMatches) {
234
+ const lineOffset = source.code.slice(0, match.index).split("\n").length;
235
+ blocks.push({
236
+ code: match[1],
237
+ filePath: `${source.filePath}.${index}.ts`,
238
+ startLine: source.startLine + lineOffset
239
+ });
240
+ index++;
241
+ }
242
+ return blocks;
243
+ };
244
+ const extractMarkdownCodeBlocks = (source) => {
245
+ const codeBlocks = [];
246
+ const codeBlockRegex = /```(tsx|ts)[^\n]*mearie[^\n]*\n([\s\S]*?)```/g;
247
+ let match;
248
+ let index = 0;
249
+ while ((match = codeBlockRegex.exec(source.code)) !== null) {
250
+ const lineOffset = source.code.slice(0, match.index).split("\n").length;
251
+ codeBlocks.push({
252
+ code: match[2],
253
+ filePath: `${source.filePath}.${index}.${match[1]}`,
254
+ startLine: source.startLine + lineOffset
255
+ });
256
+ index++;
257
+ }
258
+ return codeBlocks;
259
+ };
260
+
261
+ //#endregion
262
+ //#region src/extractor.ts
263
+ const extractGraphQLSources = async (source) => {
264
+ const ext = source.filePath.split(".").pop()?.toLowerCase();
265
+ const sources = [];
266
+ const errors = [];
267
+ const blocks = [];
268
+ try {
269
+ switch (ext) {
270
+ case "vue":
271
+ blocks.push(...await extractVueScript(source));
272
+ break;
273
+ case "svelte":
274
+ blocks.push(...await extractSvelteScript(source));
275
+ break;
276
+ case "astro":
277
+ blocks.push(...extractAstroScripts(source));
278
+ break;
279
+ case "md":
280
+ blocks.push(...extractMarkdownCodeBlocks(source));
281
+ break;
282
+ case "js":
283
+ case "jsx":
284
+ case "ts":
285
+ case "tsx":
286
+ blocks.push(source);
287
+ break;
288
+ default: return {
289
+ sources,
290
+ errors
291
+ };
292
+ }
293
+ } catch (error) {
294
+ throw new MearieError(error instanceof Error ? error.message : String(error), source.filePath);
295
+ }
296
+ for (const block of blocks) {
297
+ const result = (0, __mearie_native.extractGraphQLSources)(block);
298
+ sources.push(...result.sources);
299
+ errors.push(...result.errors.map((error) => MearieError.fromNative(error)));
300
+ }
301
+ return {
302
+ sources,
303
+ errors
304
+ };
305
+ };
306
+
72
307
  //#endregion
73
308
  //#region src/generator.ts
74
309
  /**
@@ -78,22 +313,20 @@ const createMatcher = (patterns) => {
78
313
  * @throws {Error} If code generation fails.
79
314
  */
80
315
  const generate = (options) => {
81
- const { schemas, documents } = options;
82
- const { sources, errors } = (0, __mearie_native.generateCode)(schemas, documents);
316
+ const { schemas, documents, config } = options;
317
+ const { sources, errors } = (0, __mearie_native.generateCode)(schemas, documents, config);
83
318
  return {
84
319
  sources,
85
- errors: errors.map((error) => __mearie_core.MearieError.fromNative(error))
320
+ errors: errors.map((error) => MearieError.fromNative(error))
86
321
  };
87
322
  };
88
323
 
89
324
  //#endregion
90
325
  //#region src/writer.ts
91
- const writeFiles = async (sources) => {
92
- const clientPackageJsonPath = (0, node_module.createRequire)(node_path.default.resolve(process.cwd(), "package.json")).resolve("@mearie/client/package.json");
93
- const meariePackagePath = node_path.default.dirname(clientPackageJsonPath);
94
- const clientDir = node_path.default.resolve(meariePackagePath, ".mearie", "client");
95
- await (0, node_fs_promises.mkdir)(clientDir, { recursive: true });
96
- await Promise.all(sources.map((source) => (0, node_fs_promises.writeFile)(node_path.default.join(clientDir, source.filePath), source.code, "utf8")));
326
+ const writeFiles = async (cwd, sources) => {
327
+ const mearieDir = node_path.default.resolve(cwd, ".mearie");
328
+ await (0, node_fs_promises.mkdir)(mearieDir, { recursive: true });
329
+ await Promise.all(sources.map((source) => (0, node_fs_promises.writeFile)(node_path.default.join(mearieDir, source.filePath), source.code, "utf8")));
97
330
  };
98
331
 
99
332
  //#endregion
@@ -105,6 +338,14 @@ const writeFiles = async (sources) => {
105
338
  var CodegenContext = class {
106
339
  schemas = /* @__PURE__ */ new Map();
107
340
  documents = /* @__PURE__ */ new Map();
341
+ cwd;
342
+ config;
343
+ constructor(cwd = process.cwd()) {
344
+ this.cwd = cwd;
345
+ }
346
+ setConfig(config) {
347
+ this.config = config;
348
+ }
108
349
  /**
109
350
  * Adds a schema file by reading it.
110
351
  * @param filePath - Schema file path.
@@ -129,13 +370,13 @@ var CodegenContext = class {
129
370
  * @param filePath - Document file path.
130
371
  */
131
372
  async addDocument(filePath) {
132
- const { sources, errors } = await (0, __mearie_extractor.extractGraphQLSources)({
373
+ const { sources, errors } = await extractGraphQLSources({
133
374
  code: await (0, node_fs_promises.readFile)(filePath, "utf8"),
134
375
  filePath,
135
376
  startLine: 1
136
377
  });
137
378
  this.documents.set(filePath, sources);
138
- if (errors.length > 0) throw new __mearie_core.MearieAggregateError(errors);
379
+ if (errors.length > 0) throw new MearieAggregateError(errors);
139
380
  }
140
381
  /**
141
382
  * Removes a document file.
@@ -152,15 +393,58 @@ var CodegenContext = class {
152
393
  async generate() {
153
394
  const { sources, errors } = generate({
154
395
  schemas: [...this.schemas.values()],
155
- documents: [...this.documents.values()].flat()
396
+ documents: [...this.documents.values()].flat(),
397
+ config: this.config
156
398
  });
157
- await writeFiles(sources);
158
- if (errors.length > 0) throw new __mearie_core.MearieAggregateError(errors);
399
+ await writeFiles(this.cwd, sources);
400
+ if (errors.length > 0) throw new MearieAggregateError(errors);
159
401
  }
160
402
  };
161
403
 
404
+ //#endregion
405
+ //#region src/logger.ts
406
+ (0, __logtape_logtape.configureSync)({
407
+ reset: true,
408
+ sinks: { console: (0, __logtape_logtape.getConsoleSink)({ formatter: (0, __logtape_logtape.getAnsiColorFormatter)({
409
+ level: "FULL",
410
+ timestamp: "time",
411
+ category: (category) => `💬 ${category.join("·")}`
412
+ }) }) },
413
+ loggers: [{
414
+ category: "mearie",
415
+ lowestLevel: "info",
416
+ sinks: ["console"]
417
+ }, {
418
+ category: ["logtape", "meta"],
419
+ lowestLevel: "warning",
420
+ sinks: ["console"]
421
+ }]
422
+ });
423
+ const logger = (0, __logtape_logtape.getLogger)(["mearie"]);
424
+ const formatMearieError = (error) => {
425
+ const parts = [
426
+ error.filePath,
427
+ error.line,
428
+ error.column
429
+ ].filter((part) => part !== void 0 && part !== null).map(String);
430
+ const location = parts.length > 0 ? parts.join(":") : "";
431
+ if (location) return `${picocolors.default.bold(error.message)} ${picocolors.default.cyan(picocolors.default.underline(location))}`;
432
+ return picocolors.default.bold(error.message);
433
+ };
434
+ /**
435
+ * Reports an error using the provided logger.
436
+ * @param logger - The logger to use.
437
+ * @param error - The error to report.
438
+ */
439
+ const report = (logger$1, error) => {
440
+ if (error instanceof MearieAggregateError) for (const err of error.errors) logger$1.error(formatMearieError(err));
441
+ else if (error instanceof MearieError) logger$1.error(formatMearieError(error));
442
+ else logger$1.error("{error}", { error });
443
+ };
444
+
162
445
  //#endregion
163
446
  exports.CodegenContext = CodegenContext;
164
447
  exports.createMatcher = createMatcher;
165
448
  exports.findFiles = findFiles;
166
- exports.generate = generate;
449
+ exports.logger = logger;
450
+ exports.report = report;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { MearieError, Source } from "@mearie/core";
1
+ import { Logger } from "@logtape/logtape";
2
2
 
3
3
  //#region src/glob.d.ts
4
4
  type GlobPatterns = {
@@ -21,21 +21,9 @@ declare const findFiles: (cwd: string, patterns: GlobPatterns) => Promise<string
21
21
  declare const createMatcher: (patterns: GlobPatterns) => ((filePath: string) => boolean);
22
22
  //#endregion
23
23
  //#region src/generator.d.ts
24
- type GenerateOptions = {
25
- schemas: Source[];
26
- documents: Source[];
24
+ type GenerateConfig = {
25
+ scalars?: Record<string, string>;
27
26
  };
28
- type GenerateResult = {
29
- sources: Source[];
30
- errors: MearieError[];
31
- };
32
- /**
33
- * Generates code from GraphQL documents and schemas.
34
- * @param options - Generation options.
35
- * @returns Generated code.
36
- * @throws {Error} If code generation fails.
37
- */
38
- declare const generate: (options: GenerateOptions) => GenerateResult;
39
27
  //#endregion
40
28
  //#region src/context.d.ts
41
29
  /**
@@ -45,6 +33,10 @@ declare const generate: (options: GenerateOptions) => GenerateResult;
45
33
  declare class CodegenContext {
46
34
  private schemas;
47
35
  private documents;
36
+ private cwd;
37
+ private config?;
38
+ constructor(cwd?: string);
39
+ setConfig(config: GenerateConfig): void;
48
40
  /**
49
41
  * Adds a schema file by reading it.
50
42
  * @param filePath - Schema file path.
@@ -73,15 +65,13 @@ declare class CodegenContext {
73
65
  generate(): Promise<void>;
74
66
  }
75
67
  //#endregion
76
- //#region src/types.d.ts
68
+ //#region src/logger.d.ts
69
+ declare const logger: Logger;
77
70
  /**
78
- * Configuration for the code generator.
71
+ * Reports an error using the provided logger.
72
+ * @param logger - The logger to use.
73
+ * @param error - The error to report.
79
74
  */
80
- type CodegenConfig = {
81
- schemas: string;
82
- documents: string | string[];
83
- exclude?: string | string[];
84
- cwd: string;
85
- };
75
+ declare const report: (logger: Logger, error: unknown) => void;
86
76
  //#endregion
87
- export { type CodegenConfig, CodegenContext, type GenerateOptions, type GlobPatterns, createMatcher, findFiles, generate };
77
+ export { CodegenContext, createMatcher, findFiles, logger, report };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { MearieError, Source } from "@mearie/core";
1
+ import { Logger } from "@logtape/logtape";
2
2
 
3
3
  //#region src/glob.d.ts
4
4
  type GlobPatterns = {
@@ -21,21 +21,9 @@ declare const findFiles: (cwd: string, patterns: GlobPatterns) => Promise<string
21
21
  declare const createMatcher: (patterns: GlobPatterns) => ((filePath: string) => boolean);
22
22
  //#endregion
23
23
  //#region src/generator.d.ts
24
- type GenerateOptions = {
25
- schemas: Source[];
26
- documents: Source[];
24
+ type GenerateConfig = {
25
+ scalars?: Record<string, string>;
27
26
  };
28
- type GenerateResult = {
29
- sources: Source[];
30
- errors: MearieError[];
31
- };
32
- /**
33
- * Generates code from GraphQL documents and schemas.
34
- * @param options - Generation options.
35
- * @returns Generated code.
36
- * @throws {Error} If code generation fails.
37
- */
38
- declare const generate: (options: GenerateOptions) => GenerateResult;
39
27
  //#endregion
40
28
  //#region src/context.d.ts
41
29
  /**
@@ -45,6 +33,10 @@ declare const generate: (options: GenerateOptions) => GenerateResult;
45
33
  declare class CodegenContext {
46
34
  private schemas;
47
35
  private documents;
36
+ private cwd;
37
+ private config?;
38
+ constructor(cwd?: string);
39
+ setConfig(config: GenerateConfig): void;
48
40
  /**
49
41
  * Adds a schema file by reading it.
50
42
  * @param filePath - Schema file path.
@@ -73,15 +65,13 @@ declare class CodegenContext {
73
65
  generate(): Promise<void>;
74
66
  }
75
67
  //#endregion
76
- //#region src/types.d.ts
68
+ //#region src/logger.d.ts
69
+ declare const logger: Logger;
77
70
  /**
78
- * Configuration for the code generator.
71
+ * Reports an error using the provided logger.
72
+ * @param logger - The logger to use.
73
+ * @param error - The error to report.
79
74
  */
80
- type CodegenConfig = {
81
- schemas: string;
82
- documents: string | string[];
83
- exclude?: string | string[];
84
- cwd: string;
85
- };
75
+ declare const report: (logger: Logger, error: unknown) => void;
86
76
  //#endregion
87
- export { type CodegenConfig, CodegenContext, type GenerateOptions, type GlobPatterns, createMatcher, findFiles, generate };
77
+ export { CodegenContext, createMatcher, findFiles, logger, report };