@kubb/core 0.14.0 → 0.19.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/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- type WithPromise<T> = Promise<T> | T;
2
- declare const isPromise: <T>(result: WithPromise<T>) => result is Promise<T>;
3
-
4
- type WriteOptions = {
5
- format: boolean;
6
- };
7
- declare const write: (data: string, path: string, options?: WriteOptions) => Promise<void>;
1
+ interface Cache<TCache = any> {
2
+ delete(id: string): boolean;
3
+ get<T = TCache>(id: string): T;
4
+ has(id: string): boolean;
5
+ set<T = TCache>(id: string, value: T): void;
6
+ }
7
+ declare function createPluginCache(cache: any): Cache;
8
8
 
9
9
  type Listener<T> = (value?: T) => void;
10
10
  declare class Emitter<TValue = unknown, TTopics = unknown> {
@@ -51,87 +51,25 @@ declare class FileEmitter {
51
51
  getEmittedFile: (fileReferenceId?: string | null) => EmittedFile | undefined;
52
52
  }
53
53
 
54
- /**
55
- * Get the type of the first argument in a function.
56
- * @example Arg0<(a: string, b: number) => void> -> string
57
- */
58
- type Argument0<H extends keyof PluginLifecycle> = Parameters<PluginLifecycle[H]>[0];
59
- declare const hooks: [keyof PluginLifecycle];
60
- declare class PluginDriver {
61
- plugins: Plugin[];
62
- readonly fileEmitter: FileEmitter;
63
- private readonly logger?;
64
- private readonly config;
65
- readonly core: Plugin<CorePluginOptions> & {
66
- api: CorePluginOptions['api'];
67
- };
68
- constructor(config: Api['config'], options: {
69
- logger: BuildOptions['logger'];
70
- });
71
- emitFile(...params: Parameters<FileEmitter['emitFile']>): Promise<EmittedFile>;
72
- resolveId: (source: string, importer: string, meta: Record<string, any> | undefined) => Promise<string | null | undefined>;
73
- load: (id: string) => Promise<TransformResult>;
74
- hookFirst<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, skipped?: ReadonlySet<Plugin> | null): Promise<ReturnType<PluginLifecycle[H]> | null>;
75
- hookParallel<H extends PluginLifecycleHooks, TOuput = void>(hookName: H, parameters?: Parameters<PluginLifecycle[H]> | undefined): Promise<Awaited<TOuput>[]>;
76
- hookReduceArg0<H extends PluginLifecycleHooks>(hookName: H, [argument0, ...rest]: Parameters<PluginLifecycle[H]>, reduce: (reduction: Argument0<H>, result: ReturnType<PluginLifecycle[H]>, plugin: Plugin) => WithPromise<Argument0<H> | null>): Promise<Argument0<H>>;
77
- hookSeq<H extends PluginLifecycleHooks>(hookName: H, parameters?: Parameters<PluginLifecycle[H]>): Promise<void>;
78
- private getSortedPlugins;
79
- /**
80
- * Run an async plugin hook and return the result.
81
- * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
82
- * @param args Arguments passed to the plugin hook.
83
- * @param plugin The actual pluginObject to run.
84
- */
85
- private run;
54
+ type MaybePromise<T> = Promise<T> | T;
55
+ type KubbUserConfig = Omit<KubbConfig, 'root'> & {
86
56
  /**
87
- * Run a sync plugin hook and return the result.
88
- * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
89
- * @param args Arguments passed to the plugin hook.
90
- * @param plugin The acutal plugin
91
- * @param replaceContext When passed, the plugin context can be overridden.
57
+ * Project root directory. Can be an absolute path, or a path relative from
58
+ * the location of the config file itself.
59
+ * @default process.cwd()
92
60
  */
93
- private runSync;
94
- }
95
-
96
- interface Cache<TCache = any> {
97
- delete(id: string): boolean;
98
- get<T = TCache>(id: string): T;
99
- has(id: string): boolean;
100
- set<T = TCache>(id: string, value: T): void;
101
- }
102
- declare function createPluginCache(cache: any): Cache;
103
-
104
- declare const format: (text: string) => string;
105
-
106
- declare const getRelativePath: (from?: string | null, to?: string | null) => string;
107
-
108
- type PluginOptions<UserOptions = unknown, Nested extends boolean = false, Api = any> = {
109
- userOptions: UserOptions;
110
- nested: Nested;
111
- api: Api;
112
- };
113
- type Plugin<TOptions extends PluginOptions = PluginOptions> = {
114
- name: string;
115
- api?: TOptions['api'];
116
- } & Partial<PluginLifecycle>;
117
- type PluginFactory<TOptions extends PluginOptions = PluginOptions> = (options: TOptions['userOptions']) => TOptions['nested'] extends true ? Array<Plugin<TOptions>> : Plugin<TOptions>;
118
- declare function createPlugin<TOptions extends PluginOptions = PluginOptions>(factory: PluginFactory<TOptions>): (userOptions: TOptions['userOptions']) => TOptions["nested"] extends true ? Plugin<TOptions>[] : Plugin<TOptions>;
119
- type Options = {
120
- config: Api['config'];
121
- fileEmitter: FileEmitter;
122
- resolveId: Api['resolveId'];
123
- load: Api['load'];
61
+ root?: string;
124
62
  };
125
- type CorePluginOptions = PluginOptions<Options, false, Api>;
126
-
127
- interface UserConfig {
63
+ /**
64
+ * Global/internal config used through out the full generation.
65
+ */
66
+ type KubbConfig = {
128
67
  /**
129
68
  * Project root directory. Can be an absolute path, or a path relative from
130
69
  * the location of the config file itself.
131
70
  * @default process.cwd()
132
71
  */
133
72
  root: string;
134
- clear?: boolean;
135
73
  mode?: 'single';
136
74
  input: {
137
75
  /**
@@ -144,45 +82,58 @@ interface UserConfig {
144
82
  * Path to export folder
145
83
  */
146
84
  path: string;
85
+ clean?: boolean;
147
86
  };
148
87
  /**
149
88
  * Array of Kubb plugins to use.
150
89
  */
151
- plugins?: Plugin[];
90
+ plugins?: KubbPlugin[];
91
+ /**
92
+ * Hooks that can be called when a specific action is done in Kubb.
93
+ */
94
+ hooks?: {
95
+ /**
96
+ * Hook that will be called at the end of all executions.
97
+ */
98
+ done?: string | string[];
99
+ };
152
100
  /**
153
101
  * Log level to report when using the CLI
154
102
  */
155
103
  logLevel?: LogLevel;
156
- }
157
- type UserConfigFn = (options: BuildOptions) => WithPromise<UserConfig>;
158
- type UserConfigExport = WithPromise<UserConfig> | UserConfigFn;
159
- declare const defaultConfig: Partial<UserConfig>;
160
- /**
161
- * Type helper to make it easier to use kubb.config.ts
162
- * accepts a direct {@link UserConfig} object, or a function that returns it.
163
- * The function receives a {@link ConfigEnv} object that exposes two properties:
164
- */
165
- declare function defineConfig(config: UserConfigExport): UserConfigExport;
166
-
104
+ };
105
+ type CLIOptions = {
106
+ config?: string;
107
+ mode?: 'development' | 'production';
108
+ debug?: boolean;
109
+ };
110
+ type KubbPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
111
+ name: string;
112
+ api?: TOptions['api'];
113
+ } & Partial<PluginLifecycle>;
114
+ type PluginFactoryOptions<Options = unknown, Nested extends boolean = false, Api = any> = {
115
+ options: Options;
116
+ nested: Nested;
117
+ api: Api;
118
+ };
167
119
  type PluginLifecycle = {
168
- validate: (this: PluginContext, plugins: Plugin[]) => WithPromise<ValidationResult>;
169
- buildStart: (this: PluginContext) => WithPromise<void>;
120
+ validate: (this: PluginContext, plugins: KubbPlugin[]) => MaybePromise<ValidationResult>;
121
+ buildStart: (this: PluginContext, kubbConfig: KubbConfig) => MaybePromise<void>;
170
122
  resolveId: (this: PluginContext, importee: string, importer?: string, options?: Record<string, any>) => string | null | undefined;
171
- load: (this: PluginContext, id: string) => WithPromise<TransformResult | null>;
172
- transform: (this: PluginContext, code: string, id: string) => WithPromise<TransformResult>;
173
- writeFile: (this: PluginContext, code: string | undefined, id: string) => WithPromise<void>;
174
- buildEnd: (this: PluginContext) => WithPromise<void>;
123
+ load: (this: PluginContext, id: string) => MaybePromise<TransformResult | null>;
124
+ transform: (this: PluginContext, code: string, id: string) => MaybePromise<TransformResult>;
125
+ writeFile: (this: PluginContext, code: string | undefined, id: string) => MaybePromise<void>;
126
+ buildEnd: (this: PluginContext) => MaybePromise<void>;
175
127
  };
176
128
  type PluginLifecycleHooks = keyof PluginLifecycle;
177
- type Api = {
178
- config: UserConfig;
129
+ type PluginContext = {
130
+ config: KubbConfig;
179
131
  cache: Cache;
180
132
  emitFile: FileEmitter['emitFile'];
181
- resolveId: (importee: string, importer?: string, options?: Record<string, any>) => WithPromise<string | null | undefined>;
182
- load: (id: string) => WithPromise<TransformResult | void>;
183
- addToIndex: (emittedFile: EmittedFile) => void;
133
+ resolveId: (importee: string, importer?: string, options?: Record<string, any>) => MaybePromise<string | null | undefined>;
134
+ load: (id: string) => MaybePromise<TransformResult | void>;
135
+ addToRoot: (emittedFile: EmittedFile) => void;
184
136
  };
185
- type PluginContext = Api;
186
137
  type ValidationResult = true | {
187
138
  message: string;
188
139
  };
@@ -201,14 +152,85 @@ type Spinner = {
201
152
  text: string;
202
153
  info: (text: string) => Spinner;
203
154
  };
155
+ type Logger = {
156
+ log: (message: string, logLevel: LogLevel) => void;
157
+ spinner?: Spinner;
158
+ };
204
159
  type BuildOptions = {
205
- config: Api['config'];
160
+ config: PluginContext['config'];
206
161
  mode: 'development' | 'production';
207
- logger?: {
208
- log: (message: string, logLevel: LogLevel) => void;
209
- spinner?: Spinner;
210
- };
162
+ logger?: Logger;
211
163
  };
212
164
  declare function build(options: BuildOptions): Promise<BuildOutput>;
213
165
 
214
- export { Api, Argument0, BuildOptions, Cache, EmitFile, EmittedFile, Emitter, FileEmitter, Listener, LogLevel, LogType, Plugin, PluginContext, PluginDriver, PluginFactory, PluginLifecycle, PluginLifecycleHooks, PluginOptions, TransformResult, UserConfig, UserConfigExport, UserConfigFn, ValidationResult, WithPromise, build, createPlugin, createPluginCache, build as default, defaultConfig, defineConfig, format, getRelativePath, hooks, isPromise, write };
166
+ /**
167
+ * Type helper to make it easier to use kubb.config.ts
168
+ * accepts a direct {@link KubbConfig} object, or a function that returns it.
169
+ * The function receives a {@link ConfigEnv} object that exposes two properties:
170
+ */
171
+ declare const defineConfig: (options: MaybePromise<KubbUserConfig> | ((cliOptions: CLIOptions) => MaybePromise<KubbUserConfig>)) => MaybePromise<KubbUserConfig> | ((cliOptions: CLIOptions) => MaybePromise<KubbUserConfig>);
172
+
173
+ declare const isPromise: <T>(result: MaybePromise<T>) => result is Promise<T>;
174
+
175
+ type WriteOptions = {
176
+ format: boolean;
177
+ };
178
+ declare const write: (data: string, path: string, options?: WriteOptions) => Promise<void>;
179
+
180
+ /**
181
+ * Get the type of the first argument in a function.
182
+ * @example Arg0<(a: string, b: number) => void> -> string
183
+ */
184
+ type Argument0<H extends keyof PluginLifecycle> = Parameters<PluginLifecycle[H]>[0];
185
+ declare const hooks: [keyof PluginLifecycle];
186
+ declare class PluginDriver {
187
+ plugins: KubbPlugin[];
188
+ readonly fileEmitter: FileEmitter;
189
+ private readonly logger?;
190
+ private readonly config;
191
+ readonly core: KubbPlugin<CorePluginOptions> & {
192
+ api: CorePluginOptions['api'];
193
+ };
194
+ constructor(config: KubbConfig, options: {
195
+ logger?: Logger;
196
+ });
197
+ emitFile(...params: Parameters<FileEmitter['emitFile']>): Promise<EmittedFile>;
198
+ resolveId: (source: string, importer: string, meta: Record<string, any> | undefined) => Promise<string | null | undefined>;
199
+ load: (id: string) => Promise<TransformResult>;
200
+ hookFirst<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, skipped?: ReadonlySet<KubbPlugin> | null): Promise<ReturnType<PluginLifecycle[H]> | null>;
201
+ hookParallel<H extends PluginLifecycleHooks, TOuput = void>(hookName: H, parameters?: Parameters<PluginLifecycle[H]> | undefined): Promise<Awaited<TOuput>[]>;
202
+ hookReduceArg0<H extends PluginLifecycleHooks>(hookName: H, [argument0, ...rest]: Parameters<PluginLifecycle[H]>, reduce: (reduction: Argument0<H>, result: ReturnType<PluginLifecycle[H]>, plugin: KubbPlugin) => MaybePromise<Argument0<H> | null>): Promise<Argument0<H>>;
203
+ hookSeq<H extends PluginLifecycleHooks>(hookName: H, parameters?: Parameters<PluginLifecycle[H]>): Promise<void>;
204
+ private getSortedPlugins;
205
+ /**
206
+ * Run an async plugin hook and return the result.
207
+ * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
208
+ * @param args Arguments passed to the plugin hook.
209
+ * @param plugin The actual pluginObject to run.
210
+ */
211
+ private run;
212
+ /**
213
+ * Run a sync plugin hook and return the result.
214
+ * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
215
+ * @param args Arguments passed to the plugin hook.
216
+ * @param plugin The acutal plugin
217
+ * @param replaceContext When passed, the plugin context can be overridden.
218
+ */
219
+ private runSync;
220
+ }
221
+
222
+ declare const format: (text: string) => string;
223
+
224
+ declare const getRelativePath: (from?: string | null, to?: string | null) => string;
225
+
226
+ type KubbPluginFactory<T extends PluginFactoryOptions = PluginFactoryOptions> = (options: T['options']) => T['nested'] extends true ? Array<KubbPlugin<T>> : KubbPlugin<T>;
227
+ declare function createPlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(factory: KubbPluginFactory<T>): (options: T['options']) => T["nested"] extends true ? KubbPlugin<T>[] : KubbPlugin<T>;
228
+ type Options = {
229
+ config: PluginContext['config'];
230
+ fileEmitter: FileEmitter;
231
+ resolveId: PluginContext['resolveId'];
232
+ load: PluginContext['load'];
233
+ };
234
+ type CorePluginOptions = PluginFactoryOptions<Options, false, PluginContext>;
235
+
236
+ export { Argument0, CLIOptions, Cache, CorePluginOptions, EmitFile, EmittedFile, Emitter, FileEmitter, KubbConfig, KubbPlugin, KubbUserConfig, Listener, LogLevel, LogType, Logger, MaybePromise, PluginContext, PluginDriver, PluginFactoryOptions, PluginLifecycle, PluginLifecycleHooks, TransformResult, ValidationResult, build, createPlugin, createPluginCache, build as default, defineConfig, format, getRelativePath, hooks, isPromise, write };
package/dist/index.js CHANGED
@@ -160,8 +160,8 @@ var getRelativePath = (from, to) => {
160
160
 
161
161
  // src/plugin.ts
162
162
  function createPlugin(factory) {
163
- return (userOptions) => {
164
- const plugin = factory(userOptions);
163
+ return (options) => {
164
+ const plugin = factory(options);
165
165
  if (Array.isArray(plugin)) {
166
166
  throw new Error("Not implemented");
167
167
  }
@@ -189,7 +189,7 @@ var definePlugin = createPlugin((options) => {
189
189
  id
190
190
  });
191
191
  },
192
- addToIndex: (emittedFile) => {
192
+ addToRoot: (emittedFile) => {
193
193
  indexFiles.push(emittedFile);
194
194
  },
195
195
  resolveId,
@@ -340,16 +340,8 @@ var PluginDriver = class {
340
340
  function noReturn() {
341
341
  }
342
342
 
343
- // src/config.ts
344
- var defaultConfig = {
345
- root: process.cwd()
346
- };
347
- function defineConfig(config) {
348
- return config;
349
- }
350
-
351
343
  // src/build.ts
352
- async function transformReducer(previousCode, result, _plugin) {
344
+ async function transformReducer(_previousCode, result, _plugin) {
353
345
  if (result === null) {
354
346
  return null;
355
347
  }
@@ -357,16 +349,10 @@ async function transformReducer(previousCode, result, _plugin) {
357
349
  }
358
350
  async function buildImplementation(options, done) {
359
351
  const { config, logger } = options;
360
- if (config.clear) {
352
+ if (config.output.clean) {
361
353
  await fse.remove(config.output.path);
362
354
  }
363
- const pluginDriver = new PluginDriver(
364
- {
365
- ...defaultConfig,
366
- ...config
367
- },
368
- { logger }
369
- );
355
+ const pluginDriver = new PluginDriver(config, { logger });
370
356
  const input = fse.readFileSync(path2.resolve(config.root, config.input.path), "utf-8");
371
357
  const validations = await pluginDriver.hookParallel("validate", [pluginDriver.plugins]);
372
358
  const validationsWithMessage = validations.filter(Boolean);
@@ -397,7 +383,7 @@ async function buildImplementation(options, done) {
397
383
  pluginDriver.fileEmitter.delete(emittedFile.id);
398
384
  }
399
385
  });
400
- await pluginDriver.hookParallel("buildStart");
386
+ await pluginDriver.hookParallel("buildStart", [config]);
401
387
  pluginDriver.emitFile({
402
388
  id: config.input.path,
403
389
  name: void 0,
@@ -405,7 +391,9 @@ async function buildImplementation(options, done) {
405
391
  });
406
392
  pluginDriver.fileEmitter.on("end", async () => {
407
393
  await pluginDriver.hookParallel("buildEnd");
408
- done();
394
+ setTimeout(() => {
395
+ done();
396
+ }, 1e3);
409
397
  });
410
398
  }
411
399
  function build(options) {
@@ -418,6 +406,9 @@ function build(options) {
418
406
  });
419
407
  }
420
408
 
409
+ // src/config.ts
410
+ var defineConfig = (options) => options;
411
+
421
412
  // src/index.ts
422
413
  var src_default = build;
423
414
 
@@ -428,7 +419,6 @@ exports.build = build;
428
419
  exports.createPlugin = createPlugin;
429
420
  exports.createPluginCache = createPluginCache;
430
421
  exports.default = src_default;
431
- exports.defaultConfig = defaultConfig;
432
422
  exports.defineConfig = defineConfig;
433
423
  exports.format = format;
434
424
  exports.getRelativePath = getRelativePath;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/build.ts","../src/utils/Emitter.ts","../src/utils/FileEmitter.ts","../src/plugin.ts","../src/utils/isPromise.ts","../src/utils/write.ts","../src/utils/format.ts","../src/utils/cache.ts","../src/utils/read.ts","../src/utils/PluginDriver.ts","../src/config.ts","../src/index.ts"],"names":["path","fse","argument0"],"mappings":";AAIA,OAAOA,WAAU;AAEjB,OAAOC,UAAS;;;ACJT,IAAM,UAAN,MAAmD;AAAA,EACvC,YAGZ,oBAAI,IAAI;AAAA,EAEI;AAAA,EAEjB,YAAY,QAAoB;AAC9B,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,QAAQ,QAA6D;AACnE,UAAM,UAAU,CAAC,UAAiC,CAAC,CAAC,KAAK,QAAQ,SAAS,KAAK;AAE/E,QAAI,QAAQ,OAAO,EAAE,GAAG;AACtB,WAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,YAAI,SAAS,UAAU,OAAO,IAAI;AAChC,mBAAS,GAAG,OAAO,EAAE;AAAA,QACvB;AAAA,MACF,CAAC;AACD;AAAA,IACF;AACA,SAAK,UAAU,QAAQ,CAAC,aAAa,SAAS,GAAG,OAAO,EAAY,CAAC;AAAA,EACvE;AAAA,EAEA,YAAkD,CAAC,OAAO;AACxD,UAAM,WAAW;AAAA,MACf,OAAO;AAAA,MACP;AAAA,IACF;AACA,SAAK,UAAU,IAAI,QAAQ;AAE3B,WAAO,MAAM,KAAK,UAAU,OAAO,QAAQ;AAAA,EAC7C;AAAA,EAEA,GAAG,OAAgB,IAAsB;AACvC,UAAM,WAAW;AAAA,MACf;AAAA,MACA;AAAA,IACF;AACA,SAAK,UAAU,IAAI,QAAQ;AAC3B,WAAO,MAAM,KAAK,UAAU,OAAO,QAAQ;AAAA,EAC7C;AAAA,EAEA,UAAsB,MAAM,KAAK,UAAU,MAAM;AACnD;;;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AAa,UAAU,QAAQ,CAAC,EAAE,CAAC;AAC9D,QAAI,cAAc;AAChB,aAAO;AAAA,IACT;AAEA,QAAI,MAAM;AACR,YAAM,kBAAkB,MAAM,aAAa,eAAe,aAAa,CAAC,MAAM,EAAE,GAAG,gBAAgB;AAEnG,YAAM,aAAa,aAAa,aAAa,CAAC,iBAAiB,EAAE,CAAC;AAClE,mBAAa,YAAY,OAAO,YAAY,EAAE;AAAA,IAChD;AAAA,EACF,CAAC;AAED,QAAM,aAAa,aAAa,YAAY;AAE5C,eAAa,SAAS;AAAA,IACpB,IAAI,OAAO,MAAM;AAAA,IACjB,MAAM;AAAA,IACN,QAAQ;AAAA,EACV,CAAC;AAED,eAAa,YAAY,GAAG,OAAO,YAAY;AAC7C,UAAM,aAAa,aAAa,UAAU;AAC1C,SAAK;AAAA,EACP,CAAC;AACH;AAEO,SAAS,MAAM,SAA6C;AACjE,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI;AACF,0BAAoB,SAAS,OAAO;AAAA,IACtC,SAAS,GAAP;AACA,aAAO,CAAC;AAAA,IACV;AAAA,EACF,CAAC;AACH;;;AW7GA,IAAO,cAAQ","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-empty-function */\n/* eslint-disable no-console */\n\nimport path from 'path'\n\nimport fse from 'fs-extra'\n\nimport { PluginDriver } from './utils/PluginDriver'\nimport { defaultConfig } from './config'\n\nimport type { Api, PluginContext, TransformResult, ValidationResult, LogLevel } from './types'\nimport type { Plugin } from './plugin'\n\ntype BuildOutput = void\n\n// Same type as ora\ntype Spinner = {\n start: (text?: string) => Spinner\n succeed: (text: string) => Spinner\n stopAndPersist: (options: { text: string }) => Spinner\n render: () => Spinner\n text: string\n info: (text: string) => Spinner\n}\n\nexport type BuildOptions = {\n config: Api['config']\n mode: 'development' | 'production'\n logger?: {\n log: (message: string, logLevel: LogLevel) => void\n spinner?: Spinner\n }\n}\n\nasync function transformReducer(this: PluginContext, previousCode: string, result: TransformResult, _plugin: Plugin) {\n if (result === null) {\n return null\n }\n return result\n}\n\nasync function buildImplementation(options: BuildOptions, done: (output: BuildOutput) => void) {\n const { config, logger } = options\n\n if (config.clear) {\n await fse.remove(config.output.path)\n }\n\n const pluginDriver = new PluginDriver(\n {\n ...defaultConfig,\n ...config,\n },\n { logger }\n )\n const input = fse.readFileSync(path.resolve(config.root, config.input.path), 'utf-8')\n\n const validations = await pluginDriver.hookParallel<'validate', ValidationResult>('validate', [pluginDriver.plugins])\n const validationsWithMessage = validations.filter(Boolean)\n\n if (validationsWithMessage.some((validation) => typeof validation !== 'boolean')) {\n validationsWithMessage.forEach((validation) => {\n if (validation && typeof validation !== 'boolean' && validation?.message) {\n logger?.log(validation.message, 'warn')\n }\n })\n\n return\n }\n\n pluginDriver.fileEmitter.on('new', async (emittedFile) => {\n if (!emittedFile) {\n return\n }\n const { id } = emittedFile\n\n if (!id) {\n throw new Error('No id could be transformed, please add id to emitFile or use resolveId')\n }\n\n let { source: code } = emittedFile\n\n const loadedResult = await pluginDriver.hookFirst('load', [id])\n if (loadedResult) {\n code = loadedResult\n }\n\n if (code) {\n const transformedCode = await pluginDriver.hookReduceArg0('transform', [code, id], transformReducer)\n\n await pluginDriver.hookParallel('writeFile', [transformedCode, id])\n pluginDriver.fileEmitter.delete(emittedFile.id)\n }\n })\n\n await pluginDriver.hookParallel('buildStart')\n\n pluginDriver.emitFile({\n id: config.input.path,\n name: undefined,\n source: input,\n })\n\n pluginDriver.fileEmitter.on('end', async () => {\n await pluginDriver.hookParallel('buildEnd')\n done()\n })\n}\n\nexport function build(options: BuildOptions): Promise<BuildOutput> {\n return new Promise((resolve, reject) => {\n try {\n buildImplementation(options, resolve)\n } catch (e) {\n reject(e)\n }\n })\n}\n","export type Listener<T> = (value?: T) => void\n\nexport class Emitter<TValue = unknown, TTopics = unknown> {\n private readonly listeners: Set<{\n topic?: TTopics\n cb: Listener<TValue>\n }> = new Set()\n\n private readonly topics?: TTopics[]\n\n constructor(topics?: TTopics[]) {\n this.topics = topics\n }\n\n emit(...params: [topic: TTopics, value?: TValue] | [value?: TValue]) {\n const isTopic = (value: any): value is TTopics => !!this.topics?.includes(value)\n\n if (isTopic(params[0])) {\n this.listeners.forEach((listener) => {\n if (listener.topic === params[0]) {\n listener.cb(params[1])\n }\n })\n return\n }\n this.listeners.forEach((listener) => listener.cb(params[0] as TValue))\n }\n\n subscribe: (cb: Listener<TValue>) => () => void = (cb) => {\n const listener = {\n topic: undefined,\n cb,\n }\n this.listeners.add(listener)\n // Unsubscribe\n return () => this.listeners.delete(listener)\n }\n\n on(topic: TTopics, cb: Listener<TValue>) {\n const listener = {\n topic,\n cb,\n }\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n destroy: () => void = () => this.listeners.clear()\n}\n","import { Emitter } from './Emitter'\n\nexport interface EmittedFile {\n /**\n * equal to importee when getting passed through resolveId\n */\n id: string\n /**\n * The importer is the fully resolved id of the importing module.\n */\n importer?: string\n /**\n * Name to be used to dynamicly create the fileName(based on input.path)\n */\n name?: string\n /**\n * FileName will be the end result so no input.path will not be added\n */\n fileName?: string\n source?: string\n options?: Record<string, any>\n}\n\nexport type EmitFile = (emittedFile: EmittedFile) => void\n\ntype Topics = 'new' | 'delete' | 'end'\nexport class FileEmitter {\n private readonly emitter: Emitter<EmittedFile, Topics>\n\n private readonly filesByReferenceId: Map<string, EmittedFile> = new Map()\n\n constructor(emitter: Emitter<EmittedFile, Topics> = new Emitter<EmittedFile, Topics>(['delete', 'end', 'new'])) {\n this.emitter = emitter\n }\n\n // TODO add default resolveId in core that takes name or fileName to resolve the correct files\n emitFile(emitedFile: EmittedFile) {\n // save locally in this class\n this.assignReferenceId(emitedFile, emitedFile.id)\n this.emitter.emit('new', emitedFile)\n return new Promise<EmittedFile>((resolve) => {\n const subscribe = this.emitter.on('delete', (deletedFile) => {\n if (deletedFile?.id && deletedFile?.id === emitedFile.id) {\n resolve(deletedFile)\n return subscribe()\n }\n return undefined\n })\n })\n }\n\n delete(fileReferenceId: string) {\n const deletedFile = this.filesByReferenceId.get(fileReferenceId)\n this.filesByReferenceId.delete(fileReferenceId)\n if (this.filesByReferenceId.size === 0) {\n this.emitter.emit('end')\n }\n return this.emitter.emit('delete', deletedFile)\n }\n\n subscribe(...params: Parameters<typeof this.emitter['subscribe']>) {\n this.emitter.subscribe(...params)\n }\n\n on(...params: Parameters<typeof this.emitter['on']>) {\n this.emitter.on(...params)\n }\n\n private assignReferenceId(emittedFile: EmittedFile, fileReferenceId: string | undefined) {\n if (fileReferenceId) {\n this.filesByReferenceId.set(fileReferenceId, emittedFile)\n }\n }\n\n getEmittedFile = (fileReferenceId?: string | null): EmittedFile | undefined => {\n if (!fileReferenceId) {\n return undefined\n }\n return this.filesByReferenceId.get(fileReferenceId)\n }\n}\n","import path from 'path'\n\nimport { createPluginCache, getRelativePath, write } from './utils'\n\nimport type { EmittedFile } from './utils/FileEmitter'\nimport type { FileEmitter } from './utils'\nimport type { PluginLifecycle, Api } from './types'\n\n// use of type objects\nexport type PluginOptions<UserOptions = unknown, Nested extends boolean = false, Api = any> = {\n userOptions: UserOptions\n nested: Nested\n api: Api\n}\n\nexport type Plugin<TOptions extends PluginOptions = PluginOptions> = {\n name: string\n api?: TOptions['api']\n} & Partial<PluginLifecycle>\n\nexport type PluginFactory<TOptions extends PluginOptions = PluginOptions> = (\n options: TOptions['userOptions']\n) => TOptions['nested'] extends true ? Array<Plugin<TOptions>> : Plugin<TOptions>\n\nexport function createPlugin<TOptions extends PluginOptions = PluginOptions>(factory: PluginFactory<TOptions>) {\n return (userOptions: TOptions['userOptions']) => {\n const plugin = factory(userOptions)\n if (Array.isArray(plugin)) {\n throw new Error('Not implemented')\n }\n\n // default transform\n if (!plugin.transform) {\n plugin.transform = function transform(code) {\n return code\n }\n }\n\n return plugin\n }\n}\n\ntype Options = {\n // root will be filled in with a default value in build(process.cwd)\n config: Api['config']\n fileEmitter: FileEmitter\n resolveId: Api['resolveId']\n load: Api['load']\n}\n\n// not publicly exported\nexport type CorePluginOptions = PluginOptions<Options, false, Api>\n\nexport const name = 'core' as const\n\nexport const definePlugin = createPlugin<CorePluginOptions>((options) => {\n const { fileEmitter, resolveId, load } = options\n const indexFiles: EmittedFile[] = []\n\n const api: Api = {\n get config() {\n return options.config\n },\n async emitFile(emittedFile) {\n const resolvedId = await resolveId(emittedFile.id, emittedFile.importer, emittedFile.options)\n const id = resolvedId || emittedFile.importer || emittedFile.id\n\n return fileEmitter.emitFile({\n ...emittedFile,\n id,\n })\n },\n addToIndex: (emittedFile: EmittedFile) => {\n indexFiles.push(emittedFile)\n },\n resolveId,\n load,\n cache: createPluginCache(Object.create(null)),\n }\n\n return {\n name,\n api,\n async buildEnd() {\n if (!indexFiles.length) {\n return\n }\n\n let index = ``\n\n indexFiles.forEach((item) => {\n index += `export * from \"${getRelativePath(path.resolve(this.config.root, this.config.output.path), item.id)}\";\\n`\n })\n\n await write(index, path.resolve(this.config.root, this.config.output.path, 'index.ts'), { format: true })\n },\n resolveId(importee, importer) {\n if (!importer) {\n return null\n }\n return path.resolve(importer, importee)\n },\n }\n})\n","export type WithPromise<T> = Promise<T> | T\n\nexport const isPromise = <T>(result: WithPromise<T>): result is Promise<T> => {\n return typeof (result as any)?.then === 'function'\n}\n","/* eslint-disable consistent-return */\nimport fse from 'fs-extra'\n\nimport { format } from './format'\n\ntype WriteOptions = {\n format: boolean\n}\n\nexport const write = async (data: string, path: string, options: WriteOptions = { format: false }) => {\n const formattedData = options.format ? format(data) : data\n\n try {\n await fse.stat(path)\n const oldContent = await fse.readFile(path, { encoding: 'utf-8' })\n if (oldContent?.toString() === formattedData) {\n return\n }\n } catch (_err) {\n return fse.outputFile(path, formattedData)\n }\n\n return fse.outputFile(path, formattedData)\n}\n","import { format as prettierFormat } from 'prettier'\n\nimport type { Options } from 'prettier'\n\nconst formatOptions: Options = {\n tabWidth: 2,\n printWidth: 160,\n parser: 'typescript',\n singleQuote: true,\n semi: false,\n bracketSameLine: false,\n endOfLine: 'auto',\n}\nexport const format = (text: string) => {\n return prettierFormat(text, formatOptions)\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable consistent-return */\n\nexport interface Cache<TCache = any> {\n delete(id: string): boolean\n get<T = TCache>(id: string): T\n has(id: string): boolean\n set<T = TCache>(id: string, value: T): void\n}\n\nexport function createPluginCache(cache: any): Cache {\n return {\n delete(id: string) {\n return delete cache[id]\n },\n get(id: string) {\n const item = cache[id]\n if (!item) return\n item[0] = 0\n return item[1]\n },\n has(id: string) {\n const item = cache[id]\n if (!item) return false\n item[0] = 0\n return true\n },\n set(id: string, value: any) {\n cache[id] = [0, value]\n },\n }\n}\n","import path from 'path'\n\n// TODO check for a better way or resolving the relative path\nexport const getRelativePath = (from?: string | null, to?: string | null) => {\n if (!from || !to) {\n throw new Error('From and to should be filled in when retrieving the relativePath')\n }\n const newPath = path.relative(from, to).replace('../', '').replace('.ts', '').trimEnd()\n\n return `./${newPath}`\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-restricted-syntax */\n/* eslint-disable no-await-in-loop */\n/* eslint-disable no-undef */\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n\nimport { FileEmitter } from './FileEmitter'\n\nimport { definePlugin } from '../plugin'\n\nimport type { WithPromise } from './isPromise'\nimport type { BuildOptions } from '../build'\nimport type { Plugin, CorePluginOptions } from '../plugin'\nimport type { PluginLifecycleHooks, PluginLifecycle, Api } from '../types'\n\n/**\n * Get the type of the first argument in a function.\n * @example Arg0<(a: string, b: number) => void> -> string\n */\nexport type Argument0<H extends keyof PluginLifecycle> = Parameters<PluginLifecycle[H]>[0]\n\ntype Strategy = 'hookFirst' | 'hookParallel' | 'hookReduceArg0' | 'hookSeq'\n\n// This will make sure no input hook is omitted\nconst hookNames: {\n [P in PluginLifecycleHooks]: 1\n} = {\n validate: 1,\n buildStart: 1,\n resolveId: 1,\n load: 1,\n transform: 1,\n writeFile: 1,\n buildEnd: 1,\n}\nexport const hooks = Object.keys(hookNames) as [PluginLifecycleHooks]\n\nexport class PluginDriver {\n public plugins: Plugin[]\n\n public readonly fileEmitter: FileEmitter = new FileEmitter()\n\n private readonly logger?: BuildOptions['logger']\n\n private readonly config: Api['config']\n\n public readonly core: Plugin<CorePluginOptions> & { api: CorePluginOptions['api'] }\n\n constructor(config: Api['config'], options: { logger: BuildOptions['logger'] }) {\n this.logger = options.logger\n this.config = config\n this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter)\n\n this.core = definePlugin({ config, fileEmitter: this.fileEmitter, load: this.load, resolveId: this.resolveId }) as Plugin<CorePluginOptions> & {\n api: CorePluginOptions['api']\n }\n this.plugins = [this.core, ...(config.plugins || [])]\n }\n\n emitFile(...params: Parameters<FileEmitter['emitFile']>) {\n return this.fileEmitter.emitFile(...params)\n }\n\n resolveId = (source: string, importer: string, meta: Record<string, any> | undefined) => {\n return this.hookFirst('resolveId', [source, importer, meta])\n }\n\n load = async (id: string) => {\n const result = await this.hookFirst('load', [id])\n return result\n }\n\n // chains, first non-null result stops and returns\n hookFirst<H extends PluginLifecycleHooks>(\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<Plugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // parallel\n async hookParallel<H extends PluginLifecycleHooks, TOuput = void>(hookName: H, parameters?: Parameters<PluginLifecycle[H]> | undefined) {\n const parallelPromises: Promise<TOuput>[] = []\n\n for (const plugin of this.getSortedPlugins(hookName)) {\n if ((plugin[hookName] as { sequential?: boolean })?.sequential) {\n await Promise.all(parallelPromises)\n parallelPromises.length = 0\n await this.run('hookParallel', hookName, parameters, plugin)\n } else {\n const promise: Promise<TOuput> = this.run('hookParallel', hookName, parameters, plugin)\n\n parallelPromises.push(promise)\n }\n }\n return Promise.all(parallelPromises)\n }\n\n // chains, reduces returned value, handling the reduced value as the first hook argument\n hookReduceArg0<H extends PluginLifecycleHooks>(\n hookName: H,\n [argument0, ...rest]: Parameters<PluginLifecycle[H]>,\n reduce: (reduction: Argument0<H>, result: ReturnType<PluginLifecycle[H]>, plugin: Plugin) => WithPromise<Argument0<H> | null>\n ): Promise<Argument0<H>> {\n let promise = Promise.resolve(argument0)\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then((argument0) =>\n this.run('hookReduceArg0', hookName, [argument0, ...rest] as Parameters<PluginLifecycle[H]>, plugin).then((result) =>\n reduce.call(this.core.api, argument0, result, plugin)\n )\n )\n }\n return promise\n }\n\n // chains\n\n hookSeq<H extends PluginLifecycleHooks>(hookName: H, parameters?: Parameters<PluginLifecycle[H]>) {\n let promise: Promise<void> = Promise.resolve()\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then(() => this.run('hookSeq', hookName, parameters, plugin))\n }\n return promise.then(noReturn)\n }\n\n private getSortedPlugins(_hookName: keyof PluginLifecycle): Plugin[] {\n return [...this.plugins]\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n // Implementation signature\n private run<H extends PluginLifecycleHooks, TResult = void>(\n strategy: Strategy,\n hookName: H,\n parameters: unknown[] | undefined,\n plugin: Plugin\n ): Promise<TResult> {\n // We always filter for plugins that support the hook before running it\n const hook = plugin[hookName]!\n // const context = this.pluginContexts.get(plugin) || {};\n\n return Promise.resolve().then(() => {\n if (typeof hook !== 'function') {\n return hook\n }\n\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`\n }\n\n const hookResult = (hook as any).apply(this.core.api, parameters)\n\n if (!hookResult?.then) {\n // short circuit for non-thenables and non-Promises\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return hookResult\n }\n\n return Promise.resolve(hookResult).then((result) => {\n // action was fulfilled\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return result\n })\n })\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The acutal plugin\n * @param replaceContext When passed, the plugin context can be overridden.\n */\n private runSync<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, plugin: Plugin): ReturnType<PluginLifecycle[H]> {\n const hook = plugin[hookName]!\n\n // const context = this.pluginContexts.get(plugin)!;\n\n try {\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (hook as Function).apply(this.core.api, parameters)\n } catch (error: any) {\n return error\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noReturn() {}\n","import type { BuildOptions } from './build'\nimport type { WithPromise } from './utils/isPromise'\nimport type { LogLevel } from './types'\nimport type { Plugin } from './plugin'\n\n// TODO revert to this to have multiple options like async, object, ...\n// export type PluginOption = PluginOptions | false | null | undefined | PluginOption[] | Promise<PluginOptions | false | null | undefined | PluginOption[]>;\n\nexport interface UserConfig {\n /**\n * Project root directory. Can be an absolute path, or a path relative from\n * the location of the config file itself.\n * @default process.cwd()\n */\n root: string\n clear?: boolean\n mode?: 'single'\n input: {\n /**\n * Path or link to the input file\n */\n path: string\n }\n output: {\n /**\n * Path to export folder\n */\n path: string\n }\n /**\n * Array of Kubb plugins to use.\n */\n plugins?: Plugin[]\n /**\n * Log level to report when using the CLI\n */\n\n logLevel?: LogLevel\n}\n\nexport type UserConfigFn = (options: BuildOptions) => WithPromise<UserConfig>\nexport type UserConfigExport = WithPromise<UserConfig> | UserConfigFn\n\nexport const defaultConfig: Partial<UserConfig> = {\n root: process.cwd(),\n}\n\n/**\n * Type helper to make it easier to use kubb.config.ts\n * accepts a direct {@link UserConfig} object, or a function that returns it.\n * The function receives a {@link ConfigEnv} object that exposes two properties:\n */\nexport function defineConfig(config: UserConfigExport): UserConfigExport {\n return config\n}\n","/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { build } from './build'\n\nexport * from './config'\nexport * from './build'\nexport { Plugin, PluginOptions, PluginFactory, createPlugin } from './plugin'\nexport * from './utils'\nexport * from './types'\n\nexport default build\n"]}
1
+ {"version":3,"sources":["../src/build.ts","../src/utils/Emitter.ts","../src/utils/FileEmitter.ts","../src/plugin.ts","../src/utils/isPromise.ts","../src/utils/write.ts","../src/utils/format.ts","../src/utils/cache.ts","../src/utils/read.ts","../src/utils/PluginDriver.ts","../src/config.ts","../src/index.ts"],"names":["path","fse","argument0"],"mappings":";AAAA,OAAOA,WAAU;AAEjB,OAAOC,UAAS;;;ACAT,IAAM,UAAN,MAAmD;AAAA,EACvC,YAGZ,oBAAI,IAAI;AAAA,EAEI;AAAA,EAEjB,YAAY,QAAoB;AAC9B,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,QAAQ,QAA6D;AACnE,UAAM,UAAU,CAAC,UAAiC,CAAC,CAAC,KAAK,QAAQ,SAAS,KAAK;AAE/E,QAAI,QAAQ,OAAO,EAAE,GAAG;AACtB,WAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,YAAI,SAAS,UAAU,OAAO,IAAI;AAChC,mBAAS,GAAG,OAAO,EAAE;AAAA,QACvB;AAAA,MACF,CAAC;AACD;AAAA,IACF;AACA,SAAK,UAAU,QAAQ,CAAC,aAAa,SAAS,GAAG,OAAO,EAAY,C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AED;AAAA,EACF;AAEA,eAAa,YAAY,GAAG,OAAO,OAAO,gBAAgB;AACxD,QAAI,CAAC,aAAa;AAChB;AAAA,IACF;AACA,UAAM,EAAE,GAAG,IAAI;AAEf,QAAI,CAAC,IAAI;AACP,YAAM,IAAI,MAAM,wEAAwE;AAAA,IAC1F;AAEA,QAAI,EAAE,QAAQ,KAAK,IAAI;AAEvB,UAAM,eAAe,MAAM,aAAa,UAAU,QAAQ,CAAC,EAAE,CAAC;AAC9D,QAAI,cAAc;AAChB,aAAO;AAAA,IACT;AAEA,QAAI,MAAM;AACR,YAAM,kBAAkB,MAAM,aAAa,eAAe,aAAa,CAAC,MAAM,EAAE,GAAG,gBAAgB;AAEnG,YAAM,aAAa,aAAa,aAAa,CAAC,iBAAiB,EAAE,CAAC;AAClE,mBAAa,YAAY,OAAO,YAAY,EAAE;AAAA,IAChD;AAAA,EACF,CAAC;AAED,QAAM,aAAa,aAAa,cAAc,CAAC,MAAM,CAAC;AAEtD,eAAa,SAAS;AAAA,IACpB,IAAI,OAAO,MAAM;AAAA,IACjB,MAAM;AAAA,IACN,QAAQ;AAAA,EACV,CAAC;AAED,eAAa,YAAY,GAAG,OAAO,YAAY;AAC7C,UAAM,aAAa,aAAa,UAAU;AAC1C,eAAW,MAAM;AACf,WAAK;AAAA,IACP,GAAG,GAAI;AAAA,EACT,CAAC;AACH;AAEO,SAAS,MAAM,SAA6C;AACjE,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI;AACF,0BAAoB,SAAS,OAAO;AAAA,IACtC,SAAS,GAAP;AACA,aAAO,CAAC;AAAA,IACV;AAAA,EACF,CAAC;AACH;;;AUtGO,IAAM,eAAe,CAC1B,YAMG;;;ACLL,IAAO,cAAQ","sourcesContent":["import path from 'path'\n\nimport fse from 'fs-extra'\n\nimport { PluginDriver } from './utils/PluginDriver'\n\nimport type { PluginContext, TransformResult, ValidationResult, LogLevel, KubbPlugin } from './types'\n\ntype BuildOutput = void\n\n// Same type as ora\ntype Spinner = {\n start: (text?: string) => Spinner\n succeed: (text: string) => Spinner\n stopAndPersist: (options: { text: string }) => Spinner\n render: () => Spinner\n text: string\n info: (text: string) => Spinner\n}\n\nexport type Logger = {\n log: (message: string, logLevel: LogLevel) => void\n spinner?: Spinner\n}\ntype BuildOptions = {\n config: PluginContext['config']\n mode: 'development' | 'production'\n logger?: Logger\n}\n\nasync function transformReducer(this: PluginContext, _previousCode: string, result: TransformResult, _plugin: KubbPlugin) {\n if (result === null) {\n return null\n }\n return result\n}\n\nasync function buildImplementation(options: BuildOptions, done: (output: BuildOutput) => void) {\n const { config, logger } = options\n\n if (config.output.clean) {\n await fse.remove(config.output.path)\n }\n\n const pluginDriver = new PluginDriver(config, { logger })\n const input = fse.readFileSync(path.resolve(config.root, config.input.path), 'utf-8')\n\n const validations = await pluginDriver.hookParallel<'validate', ValidationResult>('validate', [pluginDriver.plugins])\n const validationsWithMessage = validations.filter(Boolean)\n\n if (validationsWithMessage.some((validation) => typeof validation !== 'boolean')) {\n validationsWithMessage.forEach((validation) => {\n if (validation && typeof validation !== 'boolean' && validation?.message) {\n logger?.log(validation.message, 'warn')\n }\n })\n\n return\n }\n\n pluginDriver.fileEmitter.on('new', async (emittedFile) => {\n if (!emittedFile) {\n return\n }\n const { id } = emittedFile\n\n if (!id) {\n throw new Error('No id could be transformed, please add id to emitFile or use resolveId')\n }\n\n let { source: code } = emittedFile\n\n const loadedResult = await pluginDriver.hookFirst('load', [id])\n if (loadedResult) {\n code = loadedResult\n }\n\n if (code) {\n const transformedCode = await pluginDriver.hookReduceArg0('transform', [code, id], transformReducer)\n\n await pluginDriver.hookParallel('writeFile', [transformedCode, id])\n pluginDriver.fileEmitter.delete(emittedFile.id)\n }\n })\n\n await pluginDriver.hookParallel('buildStart', [config])\n\n pluginDriver.emitFile({\n id: config.input.path,\n name: undefined,\n source: input,\n })\n\n pluginDriver.fileEmitter.on('end', async () => {\n await pluginDriver.hookParallel('buildEnd')\n setTimeout(() => {\n done()\n }, 1000)\n })\n}\n\nexport function build(options: BuildOptions): Promise<BuildOutput> {\n return new Promise((resolve, reject) => {\n try {\n buildImplementation(options, resolve)\n } catch (e) {\n reject(e)\n }\n })\n}\n","export type Listener<T> = (value?: T) => void\n\nexport class Emitter<TValue = unknown, TTopics = unknown> {\n private readonly listeners: Set<{\n topic?: TTopics\n cb: Listener<TValue>\n }> = new Set()\n\n private readonly topics?: TTopics[]\n\n constructor(topics?: TTopics[]) {\n this.topics = topics\n }\n\n emit(...params: [topic: TTopics, value?: TValue] | [value?: TValue]) {\n const isTopic = (value: any): value is TTopics => !!this.topics?.includes(value)\n\n if (isTopic(params[0])) {\n this.listeners.forEach((listener) => {\n if (listener.topic === params[0]) {\n listener.cb(params[1])\n }\n })\n return\n }\n this.listeners.forEach((listener) => listener.cb(params[0] as TValue))\n }\n\n subscribe: (cb: Listener<TValue>) => () => void = (cb) => {\n const listener = {\n topic: undefined,\n cb,\n }\n this.listeners.add(listener)\n // Unsubscribe\n return () => this.listeners.delete(listener)\n }\n\n on(topic: TTopics, cb: Listener<TValue>) {\n const listener = {\n topic,\n cb,\n }\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n destroy: () => void = () => this.listeners.clear()\n}\n","import { Emitter } from './Emitter'\n\nexport interface EmittedFile {\n /**\n * equal to importee when getting passed through resolveId\n */\n id: string\n /**\n * The importer is the fully resolved id of the importing module.\n */\n importer?: string\n /**\n * Name to be used to dynamicly create the fileName(based on input.path)\n */\n name?: string\n /**\n * FileName will be the end result so no input.path will not be added\n */\n fileName?: string\n source?: string\n options?: Record<string, any>\n}\n\nexport type EmitFile = (emittedFile: EmittedFile) => void\n\ntype Topics = 'new' | 'delete' | 'end'\nexport class FileEmitter {\n private readonly emitter: Emitter<EmittedFile, Topics>\n\n private readonly filesByReferenceId: Map<string, EmittedFile> = new Map()\n\n constructor(emitter: Emitter<EmittedFile, Topics> = new Emitter<EmittedFile, Topics>(['delete', 'end', 'new'])) {\n this.emitter = emitter\n }\n\n // TODO add default resolveId in core that takes name or fileName to resolve the correct files\n emitFile(emitedFile: EmittedFile) {\n // save locally in this class\n this.assignReferenceId(emitedFile, emitedFile.id)\n this.emitter.emit('new', emitedFile)\n return new Promise<EmittedFile>((resolve) => {\n const subscribe = this.emitter.on('delete', (deletedFile) => {\n if (deletedFile?.id && deletedFile?.id === emitedFile.id) {\n resolve(deletedFile)\n return subscribe()\n }\n return undefined\n })\n })\n }\n\n delete(fileReferenceId: string) {\n const deletedFile = this.filesByReferenceId.get(fileReferenceId)\n this.filesByReferenceId.delete(fileReferenceId)\n if (this.filesByReferenceId.size === 0) {\n this.emitter.emit('end')\n }\n return this.emitter.emit('delete', deletedFile)\n }\n\n subscribe(...params: Parameters<typeof this.emitter['subscribe']>) {\n this.emitter.subscribe(...params)\n }\n\n on(...params: Parameters<typeof this.emitter['on']>) {\n this.emitter.on(...params)\n }\n\n private assignReferenceId(emittedFile: EmittedFile, fileReferenceId: string | undefined) {\n if (fileReferenceId) {\n this.filesByReferenceId.set(fileReferenceId, emittedFile)\n }\n }\n\n getEmittedFile = (fileReferenceId?: string | null): EmittedFile | undefined => {\n if (!fileReferenceId) {\n return undefined\n }\n return this.filesByReferenceId.get(fileReferenceId)\n }\n}\n","import path from 'path'\n\nimport { createPluginCache, getRelativePath, write } from './utils'\n\nimport type { FileEmitter, EmittedFile } from './utils'\nimport type { PluginContext, KubbPlugin, PluginFactoryOptions } from './types'\n\ntype KubbPluginFactory<T extends PluginFactoryOptions = PluginFactoryOptions> = (\n options: T['options']\n) => T['nested'] extends true ? Array<KubbPlugin<T>> : KubbPlugin<T>\n\nexport function createPlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(factory: KubbPluginFactory<T>) {\n return (options: T['options']) => {\n const plugin = factory(options)\n if (Array.isArray(plugin)) {\n throw new Error('Not implemented')\n }\n\n // default transform\n if (!plugin.transform) {\n plugin.transform = function transform(code) {\n return code\n }\n }\n\n return plugin\n }\n}\n\ntype Options = {\n config: PluginContext['config']\n fileEmitter: FileEmitter\n resolveId: PluginContext['resolveId']\n load: PluginContext['load']\n}\n\n// not publicly exported\nexport type CorePluginOptions = PluginFactoryOptions<Options, false, PluginContext>\n\nexport const name = 'core' as const\n\nexport const definePlugin = createPlugin<CorePluginOptions>((options) => {\n const { fileEmitter, resolveId, load } = options\n const indexFiles: EmittedFile[] = []\n\n const api: PluginContext = {\n get config() {\n return options.config\n },\n async emitFile(emittedFile) {\n const resolvedId = await resolveId(emittedFile.id, emittedFile.importer, emittedFile.options)\n const id = resolvedId || emittedFile.importer || emittedFile.id\n\n return fileEmitter.emitFile({\n ...emittedFile,\n id,\n })\n },\n addToRoot: (emittedFile: EmittedFile) => {\n indexFiles.push(emittedFile)\n },\n resolveId,\n load,\n cache: createPluginCache(Object.create(null)),\n }\n\n return {\n name,\n api,\n async buildEnd() {\n if (!indexFiles.length) {\n return\n }\n\n let index = ``\n\n indexFiles.forEach((item) => {\n index += `export * from \"${getRelativePath(path.resolve(this.config.root, this.config.output.path), item.id)}\";\\n`\n })\n\n await write(index, path.resolve(this.config.root, this.config.output.path, 'index.ts'), { format: true })\n },\n resolveId(importee, importer) {\n if (!importer) {\n return null\n }\n return path.resolve(importer, importee)\n },\n }\n})\n","import type { MaybePromise } from '../types'\n\nexport const isPromise = <T>(result: MaybePromise<T>): result is Promise<T> => {\n return typeof (result as any)?.then === 'function'\n}\n","/* eslint-disable consistent-return */\nimport fse from 'fs-extra'\n\nimport { format } from './format'\n\ntype WriteOptions = {\n format: boolean\n}\n\nexport const write = async (data: string, path: string, options: WriteOptions = { format: false }) => {\n const formattedData = options.format ? format(data) : data\n\n try {\n await fse.stat(path)\n const oldContent = await fse.readFile(path, { encoding: 'utf-8' })\n if (oldContent?.toString() === formattedData) {\n return\n }\n } catch (_err) {\n return fse.outputFile(path, formattedData)\n }\n\n return fse.outputFile(path, formattedData)\n}\n","import { format as prettierFormat } from 'prettier'\n\nimport type { Options } from 'prettier'\n\nconst formatOptions: Options = {\n tabWidth: 2,\n printWidth: 160,\n parser: 'typescript',\n singleQuote: true,\n semi: false,\n bracketSameLine: false,\n endOfLine: 'auto',\n}\nexport const format = (text: string) => {\n return prettierFormat(text, formatOptions)\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable consistent-return */\n\nexport interface Cache<TCache = any> {\n delete(id: string): boolean\n get<T = TCache>(id: string): T\n has(id: string): boolean\n set<T = TCache>(id: string, value: T): void\n}\n\nexport function createPluginCache(cache: any): Cache {\n return {\n delete(id: string) {\n return delete cache[id]\n },\n get(id: string) {\n const item = cache[id]\n if (!item) return\n item[0] = 0\n return item[1]\n },\n has(id: string) {\n const item = cache[id]\n if (!item) return false\n item[0] = 0\n return true\n },\n set(id: string, value: any) {\n cache[id] = [0, value]\n },\n }\n}\n","import path from 'path'\n\n// TODO check for a better way or resolving the relative path\nexport const getRelativePath = (from?: string | null, to?: string | null) => {\n if (!from || !to) {\n throw new Error('From and to should be filled in when retrieving the relativePath')\n }\n const newPath = path.relative(from, to).replace('../', '').replace('.ts', '').trimEnd()\n\n return `./${newPath}`\n}\n","/* eslint-disable no-await-in-loop */\n/* eslint-disable no-restricted-syntax */\nimport { FileEmitter } from './FileEmitter'\n\nimport { definePlugin } from '../plugin'\n\nimport type { KubbConfig, KubbPlugin, PluginLifecycleHooks, PluginLifecycle, MaybePromise } from '../types'\nimport type { Logger } from '../build'\nimport type { CorePluginOptions } from '../plugin'\n\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n/**\n * Get the type of the first argument in a function.\n * @example Arg0<(a: string, b: number) => void> -> string\n */\nexport type Argument0<H extends keyof PluginLifecycle> = Parameters<PluginLifecycle[H]>[0]\n\ntype Strategy = 'hookFirst' | 'hookParallel' | 'hookReduceArg0' | 'hookSeq'\n\n// This will make sure no input hook is omitted\nconst hookNames: {\n [P in PluginLifecycleHooks]: 1\n} = {\n validate: 1,\n buildStart: 1,\n resolveId: 1,\n load: 1,\n transform: 1,\n writeFile: 1,\n buildEnd: 1,\n}\nexport const hooks = Object.keys(hookNames) as [PluginLifecycleHooks]\n\nexport class PluginDriver {\n public plugins: KubbPlugin[]\n\n public readonly fileEmitter: FileEmitter = new FileEmitter()\n\n private readonly logger?: Logger\n\n private readonly config: KubbConfig\n\n public readonly core: KubbPlugin<CorePluginOptions> & { api: CorePluginOptions['api'] }\n\n constructor(config: KubbConfig, options: { logger?: Logger }) {\n this.logger = options.logger\n this.config = config\n this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter)\n\n this.core = definePlugin({ config, fileEmitter: this.fileEmitter, load: this.load, resolveId: this.resolveId }) as KubbPlugin<CorePluginOptions> & {\n api: CorePluginOptions['api']\n }\n this.plugins = [this.core, ...(config.plugins || [])]\n }\n\n emitFile(...params: Parameters<FileEmitter['emitFile']>) {\n return this.fileEmitter.emitFile(...params)\n }\n\n resolveId = (source: string, importer: string, meta: Record<string, any> | undefined) => {\n return this.hookFirst('resolveId', [source, importer, meta])\n }\n\n load = async (id: string) => {\n const result = await this.hookFirst('load', [id])\n return result\n }\n\n // chains, first non-null result stops and returns\n hookFirst<H extends PluginLifecycleHooks>(\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<KubbPlugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // parallel\n async hookParallel<H extends PluginLifecycleHooks, TOuput = void>(hookName: H, parameters?: Parameters<PluginLifecycle[H]> | undefined) {\n const parallelPromises: Promise<TOuput>[] = []\n\n for (const plugin of this.getSortedPlugins(hookName)) {\n if ((plugin[hookName] as { sequential?: boolean })?.sequential) {\n await Promise.all(parallelPromises)\n parallelPromises.length = 0\n await this.run('hookParallel', hookName, parameters, plugin)\n } else {\n const promise: Promise<TOuput> = this.run('hookParallel', hookName, parameters, plugin)\n\n parallelPromises.push(promise)\n }\n }\n return Promise.all(parallelPromises)\n }\n\n // chains, reduces returned value, handling the reduced value as the first hook argument\n hookReduceArg0<H extends PluginLifecycleHooks>(\n hookName: H,\n [argument0, ...rest]: Parameters<PluginLifecycle[H]>,\n reduce: (reduction: Argument0<H>, result: ReturnType<PluginLifecycle[H]>, plugin: KubbPlugin) => MaybePromise<Argument0<H> | null>\n ): Promise<Argument0<H>> {\n let promise = Promise.resolve(argument0)\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then((argument0) =>\n this.run('hookReduceArg0', hookName, [argument0, ...rest] as Parameters<PluginLifecycle[H]>, plugin).then((result) =>\n reduce.call(this.core.api, argument0, result, plugin)\n )\n )\n }\n return promise\n }\n\n // chains\n\n hookSeq<H extends PluginLifecycleHooks>(hookName: H, parameters?: Parameters<PluginLifecycle[H]>) {\n let promise: Promise<void> = Promise.resolve()\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then(() => this.run('hookSeq', hookName, parameters, plugin))\n }\n return promise.then(noReturn)\n }\n\n private getSortedPlugins(_hookName: keyof PluginLifecycle): KubbPlugin[] {\n return [...this.plugins]\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n // Implementation signature\n private run<H extends PluginLifecycleHooks, TResult = void>(\n strategy: Strategy,\n hookName: H,\n parameters: unknown[] | undefined,\n plugin: KubbPlugin\n ): Promise<TResult> {\n const hook = plugin[hookName]!\n\n return Promise.resolve().then(() => {\n if (typeof hook !== 'function') {\n return hook\n }\n\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`\n }\n\n const hookResult = (hook as any).apply(this.core.api, parameters)\n\n if (!hookResult?.then) {\n // short circuit for non-thenables and non-Promises\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return hookResult\n }\n\n return Promise.resolve(hookResult).then((result) => {\n // action was fulfilled\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return result\n })\n })\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The acutal plugin\n * @param replaceContext When passed, the plugin context can be overridden.\n */\n private runSync<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, plugin: KubbPlugin): ReturnType<PluginLifecycle[H]> {\n const hook = plugin[hookName]!\n\n // const context = this.pluginContexts.get(plugin)!;\n\n try {\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (hook as Function).apply(this.core.api, parameters)\n } catch (error: any) {\n return error\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noReturn() {}\n","import type { MaybePromise, KubbUserConfig, CLIOptions } from './types'\n\n/**\n * Type helper to make it easier to use kubb.config.ts\n * accepts a direct {@link KubbConfig} object, or a function that returns it.\n * The function receives a {@link ConfigEnv} object that exposes two properties:\n */\nexport const defineConfig = (\n options:\n | MaybePromise<KubbUserConfig>\n | ((\n /** The options derived from CLI flags */\n cliOptions: CLIOptions\n ) => MaybePromise<KubbUserConfig>)\n) => options\n","/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { build } from './build'\n\nexport * from './config'\nexport * from './build'\nexport { CorePluginOptions, createPlugin } from './plugin'\nexport * from './utils'\nexport * from './types'\n\nexport default build\n"]}
package/dist/index.mjs CHANGED
@@ -156,8 +156,8 @@ var getRelativePath = (from, to) => {
156
156
 
157
157
  // src/plugin.ts
158
158
  function createPlugin(factory) {
159
- return (userOptions) => {
160
- const plugin = factory(userOptions);
159
+ return (options) => {
160
+ const plugin = factory(options);
161
161
  if (Array.isArray(plugin)) {
162
162
  throw new Error("Not implemented");
163
163
  }
@@ -185,7 +185,7 @@ var definePlugin = createPlugin((options) => {
185
185
  id
186
186
  });
187
187
  },
188
- addToIndex: (emittedFile) => {
188
+ addToRoot: (emittedFile) => {
189
189
  indexFiles.push(emittedFile);
190
190
  },
191
191
  resolveId,
@@ -336,16 +336,8 @@ var PluginDriver = class {
336
336
  function noReturn() {
337
337
  }
338
338
 
339
- // src/config.ts
340
- var defaultConfig = {
341
- root: process.cwd()
342
- };
343
- function defineConfig(config) {
344
- return config;
345
- }
346
-
347
339
  // src/build.ts
348
- async function transformReducer(previousCode, result, _plugin) {
340
+ async function transformReducer(_previousCode, result, _plugin) {
349
341
  if (result === null) {
350
342
  return null;
351
343
  }
@@ -353,16 +345,10 @@ async function transformReducer(previousCode, result, _plugin) {
353
345
  }
354
346
  async function buildImplementation(options, done) {
355
347
  const { config, logger } = options;
356
- if (config.clear) {
348
+ if (config.output.clean) {
357
349
  await fse.remove(config.output.path);
358
350
  }
359
- const pluginDriver = new PluginDriver(
360
- {
361
- ...defaultConfig,
362
- ...config
363
- },
364
- { logger }
365
- );
351
+ const pluginDriver = new PluginDriver(config, { logger });
366
352
  const input = fse.readFileSync(path2.resolve(config.root, config.input.path), "utf-8");
367
353
  const validations = await pluginDriver.hookParallel("validate", [pluginDriver.plugins]);
368
354
  const validationsWithMessage = validations.filter(Boolean);
@@ -393,7 +379,7 @@ async function buildImplementation(options, done) {
393
379
  pluginDriver.fileEmitter.delete(emittedFile.id);
394
380
  }
395
381
  });
396
- await pluginDriver.hookParallel("buildStart");
382
+ await pluginDriver.hookParallel("buildStart", [config]);
397
383
  pluginDriver.emitFile({
398
384
  id: config.input.path,
399
385
  name: void 0,
@@ -401,7 +387,9 @@ async function buildImplementation(options, done) {
401
387
  });
402
388
  pluginDriver.fileEmitter.on("end", async () => {
403
389
  await pluginDriver.hookParallel("buildEnd");
404
- done();
390
+ setTimeout(() => {
391
+ done();
392
+ }, 1e3);
405
393
  });
406
394
  }
407
395
  function build(options) {
@@ -414,9 +402,12 @@ function build(options) {
414
402
  });
415
403
  }
416
404
 
405
+ // src/config.ts
406
+ var defineConfig = (options) => options;
407
+
417
408
  // src/index.ts
418
409
  var src_default = build;
419
410
 
420
- export { Emitter, FileEmitter, PluginDriver, build, createPlugin, createPluginCache, src_default as default, defaultConfig, defineConfig, format, getRelativePath, hooks, isPromise, write };
411
+ export { Emitter, FileEmitter, PluginDriver, build, createPlugin, createPluginCache, src_default as default, defineConfig, format, getRelativePath, hooks, isPromise, write };
421
412
  //# sourceMappingURL=out.js.map
422
413
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/build.ts","../src/utils/Emitter.ts","../src/utils/FileEmitter.ts","../src/plugin.ts","../src/utils/isPromise.ts","../src/utils/write.ts","../src/utils/format.ts","../src/utils/cache.ts","../src/utils/read.ts","../src/utils/PluginDriver.ts","../src/config.ts","../src/index.ts"],"names":["path","fse","argument0"],"mappings":";AAIA,OAAOA,WAAU;AAEjB,OAAOC,UAAS;;;ACJT,IAAM,UAAN,MAAmD;AAAA,EACvC,YAGZ,oBAAI,IAAI;AAAA,EAEI;AAAA,EAEjB,YAAY,QAAoB;AAC9B,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,QAAQ,QAA6D;AACnE,UAAM,UAAU,CAAC,UAAiC,CAAC,CAAC,KAAK,QAAQ,SAAS,KAAK;AAE/E,QAAI,QAAQ,OAAO,EAAE,GAAG;AACtB,WAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,YAAI,SAAS,UAAU,OAAO,IAAI;AAChC,mBAAS,GAAG,OAAO,EAAE;AAAA,QACvB;AAAA,MACF,CAAC;AACD;AAAA,IACF;AACA,SAAK,UAAU,QAAQ,CAAC,aAAa,SAAS,GAAG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\n/* eslint-disable no-console */\n\nimport path from 'path'\n\nimport fse from 'fs-extra'\n\nimport { PluginDriver } from './utils/PluginDriver'\nimport { defaultConfig } from './config'\n\nimport type { Api, PluginContext, TransformResult, ValidationResult, LogLevel } from './types'\nimport type { Plugin } from './plugin'\n\ntype BuildOutput = void\n\n// Same type as ora\ntype Spinner = {\n start: (text?: string) => Spinner\n succeed: (text: string) => Spinner\n stopAndPersist: (options: { text: string }) => Spinner\n render: () => Spinner\n text: string\n info: (text: string) => Spinner\n}\n\nexport type BuildOptions = {\n config: Api['config']\n mode: 'development' | 'production'\n logger?: {\n log: (message: string, logLevel: LogLevel) => void\n spinner?: Spinner\n }\n}\n\nasync function transformReducer(this: PluginContext, previousCode: string, result: TransformResult, _plugin: Plugin) {\n if (result === null) {\n return null\n }\n return result\n}\n\nasync function buildImplementation(options: BuildOptions, done: (output: BuildOutput) => void) {\n const { config, logger } = options\n\n if (config.clear) {\n await fse.remove(config.output.path)\n }\n\n const pluginDriver = new PluginDriver(\n {\n ...defaultConfig,\n ...config,\n },\n { logger }\n )\n const input = fse.readFileSync(path.resolve(config.root, config.input.path), 'utf-8')\n\n const validations = await pluginDriver.hookParallel<'validate', ValidationResult>('validate', [pluginDriver.plugins])\n const validationsWithMessage = validations.filter(Boolean)\n\n if (validationsWithMessage.some((validation) => typeof validation !== 'boolean')) {\n validationsWithMessage.forEach((validation) => {\n if (validation && typeof validation !== 'boolean' && validation?.message) {\n logger?.log(validation.message, 'warn')\n }\n })\n\n return\n }\n\n pluginDriver.fileEmitter.on('new', async (emittedFile) => {\n if (!emittedFile) {\n return\n }\n const { id } = emittedFile\n\n if (!id) {\n throw new Error('No id could be transformed, please add id to emitFile or use resolveId')\n }\n\n let { source: code } = emittedFile\n\n const loadedResult = await pluginDriver.hookFirst('load', [id])\n if (loadedResult) {\n code = loadedResult\n }\n\n if (code) {\n const transformedCode = await pluginDriver.hookReduceArg0('transform', [code, id], transformReducer)\n\n await pluginDriver.hookParallel('writeFile', [transformedCode, id])\n pluginDriver.fileEmitter.delete(emittedFile.id)\n }\n })\n\n await pluginDriver.hookParallel('buildStart')\n\n pluginDriver.emitFile({\n id: config.input.path,\n name: undefined,\n source: input,\n })\n\n pluginDriver.fileEmitter.on('end', async () => {\n await pluginDriver.hookParallel('buildEnd')\n done()\n })\n}\n\nexport function build(options: BuildOptions): Promise<BuildOutput> {\n return new Promise((resolve, reject) => {\n try {\n buildImplementation(options, resolve)\n } catch (e) {\n reject(e)\n }\n })\n}\n","export type Listener<T> = (value?: T) => void\n\nexport class Emitter<TValue = unknown, TTopics = unknown> {\n private readonly listeners: Set<{\n topic?: TTopics\n cb: Listener<TValue>\n }> = new Set()\n\n private readonly topics?: TTopics[]\n\n constructor(topics?: TTopics[]) {\n this.topics = topics\n }\n\n emit(...params: [topic: TTopics, value?: TValue] | [value?: TValue]) {\n const isTopic = (value: any): value is TTopics => !!this.topics?.includes(value)\n\n if (isTopic(params[0])) {\n this.listeners.forEach((listener) => {\n if (listener.topic === params[0]) {\n listener.cb(params[1])\n }\n })\n return\n }\n this.listeners.forEach((listener) => listener.cb(params[0] as TValue))\n }\n\n subscribe: (cb: Listener<TValue>) => () => void = (cb) => {\n const listener = {\n topic: undefined,\n cb,\n }\n this.listeners.add(listener)\n // Unsubscribe\n return () => this.listeners.delete(listener)\n }\n\n on(topic: TTopics, cb: Listener<TValue>) {\n const listener = {\n topic,\n cb,\n }\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n destroy: () => void = () => this.listeners.clear()\n}\n","import { Emitter } from './Emitter'\n\nexport interface EmittedFile {\n /**\n * equal to importee when getting passed through resolveId\n */\n id: string\n /**\n * The importer is the fully resolved id of the importing module.\n */\n importer?: string\n /**\n * Name to be used to dynamicly create the fileName(based on input.path)\n */\n name?: string\n /**\n * FileName will be the end result so no input.path will not be added\n */\n fileName?: string\n source?: string\n options?: Record<string, any>\n}\n\nexport type EmitFile = (emittedFile: EmittedFile) => void\n\ntype Topics = 'new' | 'delete' | 'end'\nexport class FileEmitter {\n private readonly emitter: Emitter<EmittedFile, Topics>\n\n private readonly filesByReferenceId: Map<string, EmittedFile> = new Map()\n\n constructor(emitter: Emitter<EmittedFile, Topics> = new Emitter<EmittedFile, Topics>(['delete', 'end', 'new'])) {\n this.emitter = emitter\n }\n\n // TODO add default resolveId in core that takes name or fileName to resolve the correct files\n emitFile(emitedFile: EmittedFile) {\n // save locally in this class\n this.assignReferenceId(emitedFile, emitedFile.id)\n this.emitter.emit('new', emitedFile)\n return new Promise<EmittedFile>((resolve) => {\n const subscribe = this.emitter.on('delete', (deletedFile) => {\n if (deletedFile?.id && deletedFile?.id === emitedFile.id) {\n resolve(deletedFile)\n return subscribe()\n }\n return undefined\n })\n })\n }\n\n delete(fileReferenceId: string) {\n const deletedFile = this.filesByReferenceId.get(fileReferenceId)\n this.filesByReferenceId.delete(fileReferenceId)\n if (this.filesByReferenceId.size === 0) {\n this.emitter.emit('end')\n }\n return this.emitter.emit('delete', deletedFile)\n }\n\n subscribe(...params: Parameters<typeof this.emitter['subscribe']>) {\n this.emitter.subscribe(...params)\n }\n\n on(...params: Parameters<typeof this.emitter['on']>) {\n this.emitter.on(...params)\n }\n\n private assignReferenceId(emittedFile: EmittedFile, fileReferenceId: string | undefined) {\n if (fileReferenceId) {\n this.filesByReferenceId.set(fileReferenceId, emittedFile)\n }\n }\n\n getEmittedFile = (fileReferenceId?: string | null): EmittedFile | undefined => {\n if (!fileReferenceId) {\n return undefined\n }\n return this.filesByReferenceId.get(fileReferenceId)\n }\n}\n","import path from 'path'\n\nimport { createPluginCache, getRelativePath, write } from './utils'\n\nimport type { EmittedFile } from './utils/FileEmitter'\nimport type { FileEmitter } from './utils'\nimport type { PluginLifecycle, Api } from './types'\n\n// use of type objects\nexport type PluginOptions<UserOptions = unknown, Nested extends boolean = false, Api = any> = {\n userOptions: UserOptions\n nested: Nested\n api: Api\n}\n\nexport type Plugin<TOptions extends PluginOptions = PluginOptions> = {\n name: string\n api?: TOptions['api']\n} & Partial<PluginLifecycle>\n\nexport type PluginFactory<TOptions extends PluginOptions = PluginOptions> = (\n options: TOptions['userOptions']\n) => TOptions['nested'] extends true ? Array<Plugin<TOptions>> : Plugin<TOptions>\n\nexport function createPlugin<TOptions extends PluginOptions = PluginOptions>(factory: PluginFactory<TOptions>) {\n return (userOptions: TOptions['userOptions']) => {\n const plugin = factory(userOptions)\n if (Array.isArray(plugin)) {\n throw new Error('Not implemented')\n }\n\n // default transform\n if (!plugin.transform) {\n plugin.transform = function transform(code) {\n return code\n }\n }\n\n return plugin\n }\n}\n\ntype Options = {\n // root will be filled in with a default value in build(process.cwd)\n config: Api['config']\n fileEmitter: FileEmitter\n resolveId: Api['resolveId']\n load: Api['load']\n}\n\n// not publicly exported\nexport type CorePluginOptions = PluginOptions<Options, false, Api>\n\nexport const name = 'core' as const\n\nexport const definePlugin = createPlugin<CorePluginOptions>((options) => {\n const { fileEmitter, resolveId, load } = options\n const indexFiles: EmittedFile[] = []\n\n const api: Api = {\n get config() {\n return options.config\n },\n async emitFile(emittedFile) {\n const resolvedId = await resolveId(emittedFile.id, emittedFile.importer, emittedFile.options)\n const id = resolvedId || emittedFile.importer || emittedFile.id\n\n return fileEmitter.emitFile({\n ...emittedFile,\n id,\n })\n },\n addToIndex: (emittedFile: EmittedFile) => {\n indexFiles.push(emittedFile)\n },\n resolveId,\n load,\n cache: createPluginCache(Object.create(null)),\n }\n\n return {\n name,\n api,\n async buildEnd() {\n if (!indexFiles.length) {\n return\n }\n\n let index = ``\n\n indexFiles.forEach((item) => {\n index += `export * from \"${getRelativePath(path.resolve(this.config.root, this.config.output.path), item.id)}\";\\n`\n })\n\n await write(index, path.resolve(this.config.root, this.config.output.path, 'index.ts'), { format: true })\n },\n resolveId(importee, importer) {\n if (!importer) {\n return null\n }\n return path.resolve(importer, importee)\n },\n }\n})\n","export type WithPromise<T> = Promise<T> | T\n\nexport const isPromise = <T>(result: WithPromise<T>): result is Promise<T> => {\n return typeof (result as any)?.then === 'function'\n}\n","/* eslint-disable consistent-return */\nimport fse from 'fs-extra'\n\nimport { format } from './format'\n\ntype WriteOptions = {\n format: boolean\n}\n\nexport const write = async (data: string, path: string, options: WriteOptions = { format: false }) => {\n const formattedData = options.format ? format(data) : data\n\n try {\n await fse.stat(path)\n const oldContent = await fse.readFile(path, { encoding: 'utf-8' })\n if (oldContent?.toString() === formattedData) {\n return\n }\n } catch (_err) {\n return fse.outputFile(path, formattedData)\n }\n\n return fse.outputFile(path, formattedData)\n}\n","import { format as prettierFormat } from 'prettier'\n\nimport type { Options } from 'prettier'\n\nconst formatOptions: Options = {\n tabWidth: 2,\n printWidth: 160,\n parser: 'typescript',\n singleQuote: true,\n semi: false,\n bracketSameLine: false,\n endOfLine: 'auto',\n}\nexport const format = (text: string) => {\n return prettierFormat(text, formatOptions)\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable consistent-return */\n\nexport interface Cache<TCache = any> {\n delete(id: string): boolean\n get<T = TCache>(id: string): T\n has(id: string): boolean\n set<T = TCache>(id: string, value: T): void\n}\n\nexport function createPluginCache(cache: any): Cache {\n return {\n delete(id: string) {\n return delete cache[id]\n },\n get(id: string) {\n const item = cache[id]\n if (!item) return\n item[0] = 0\n return item[1]\n },\n has(id: string) {\n const item = cache[id]\n if (!item) return false\n item[0] = 0\n return true\n },\n set(id: string, value: any) {\n cache[id] = [0, value]\n },\n }\n}\n","import path from 'path'\n\n// TODO check for a better way or resolving the relative path\nexport const getRelativePath = (from?: string | null, to?: string | null) => {\n if (!from || !to) {\n throw new Error('From and to should be filled in when retrieving the relativePath')\n }\n const newPath = path.relative(from, to).replace('../', '').replace('.ts', '').trimEnd()\n\n return `./${newPath}`\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-restricted-syntax */\n/* eslint-disable no-await-in-loop */\n/* eslint-disable no-undef */\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n\nimport { FileEmitter } from './FileEmitter'\n\nimport { definePlugin } from '../plugin'\n\nimport type { WithPromise } from './isPromise'\nimport type { BuildOptions } from '../build'\nimport type { Plugin, CorePluginOptions } from '../plugin'\nimport type { PluginLifecycleHooks, PluginLifecycle, Api } from '../types'\n\n/**\n * Get the type of the first argument in a function.\n * @example Arg0<(a: string, b: number) => void> -> string\n */\nexport type Argument0<H extends keyof PluginLifecycle> = Parameters<PluginLifecycle[H]>[0]\n\ntype Strategy = 'hookFirst' | 'hookParallel' | 'hookReduceArg0' | 'hookSeq'\n\n// This will make sure no input hook is omitted\nconst hookNames: {\n [P in PluginLifecycleHooks]: 1\n} = {\n validate: 1,\n buildStart: 1,\n resolveId: 1,\n load: 1,\n transform: 1,\n writeFile: 1,\n buildEnd: 1,\n}\nexport const hooks = Object.keys(hookNames) as [PluginLifecycleHooks]\n\nexport class PluginDriver {\n public plugins: Plugin[]\n\n public readonly fileEmitter: FileEmitter = new FileEmitter()\n\n private readonly logger?: BuildOptions['logger']\n\n private readonly config: Api['config']\n\n public readonly core: Plugin<CorePluginOptions> & { api: CorePluginOptions['api'] }\n\n constructor(config: Api['config'], options: { logger: BuildOptions['logger'] }) {\n this.logger = options.logger\n this.config = config\n this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter)\n\n this.core = definePlugin({ config, fileEmitter: this.fileEmitter, load: this.load, resolveId: this.resolveId }) as Plugin<CorePluginOptions> & {\n api: CorePluginOptions['api']\n }\n this.plugins = [this.core, ...(config.plugins || [])]\n }\n\n emitFile(...params: Parameters<FileEmitter['emitFile']>) {\n return this.fileEmitter.emitFile(...params)\n }\n\n resolveId = (source: string, importer: string, meta: Record<string, any> | undefined) => {\n return this.hookFirst('resolveId', [source, importer, meta])\n }\n\n load = async (id: string) => {\n const result = await this.hookFirst('load', [id])\n return result\n }\n\n // chains, first non-null result stops and returns\n hookFirst<H extends PluginLifecycleHooks>(\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<Plugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // parallel\n async hookParallel<H extends PluginLifecycleHooks, TOuput = void>(hookName: H, parameters?: Parameters<PluginLifecycle[H]> | undefined) {\n const parallelPromises: Promise<TOuput>[] = []\n\n for (const plugin of this.getSortedPlugins(hookName)) {\n if ((plugin[hookName] as { sequential?: boolean })?.sequential) {\n await Promise.all(parallelPromises)\n parallelPromises.length = 0\n await this.run('hookParallel', hookName, parameters, plugin)\n } else {\n const promise: Promise<TOuput> = this.run('hookParallel', hookName, parameters, plugin)\n\n parallelPromises.push(promise)\n }\n }\n return Promise.all(parallelPromises)\n }\n\n // chains, reduces returned value, handling the reduced value as the first hook argument\n hookReduceArg0<H extends PluginLifecycleHooks>(\n hookName: H,\n [argument0, ...rest]: Parameters<PluginLifecycle[H]>,\n reduce: (reduction: Argument0<H>, result: ReturnType<PluginLifecycle[H]>, plugin: Plugin) => WithPromise<Argument0<H> | null>\n ): Promise<Argument0<H>> {\n let promise = Promise.resolve(argument0)\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then((argument0) =>\n this.run('hookReduceArg0', hookName, [argument0, ...rest] as Parameters<PluginLifecycle[H]>, plugin).then((result) =>\n reduce.call(this.core.api, argument0, result, plugin)\n )\n )\n }\n return promise\n }\n\n // chains\n\n hookSeq<H extends PluginLifecycleHooks>(hookName: H, parameters?: Parameters<PluginLifecycle[H]>) {\n let promise: Promise<void> = Promise.resolve()\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then(() => this.run('hookSeq', hookName, parameters, plugin))\n }\n return promise.then(noReturn)\n }\n\n private getSortedPlugins(_hookName: keyof PluginLifecycle): Plugin[] {\n return [...this.plugins]\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n // Implementation signature\n private run<H extends PluginLifecycleHooks, TResult = void>(\n strategy: Strategy,\n hookName: H,\n parameters: unknown[] | undefined,\n plugin: Plugin\n ): Promise<TResult> {\n // We always filter for plugins that support the hook before running it\n const hook = plugin[hookName]!\n // const context = this.pluginContexts.get(plugin) || {};\n\n return Promise.resolve().then(() => {\n if (typeof hook !== 'function') {\n return hook\n }\n\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`\n }\n\n const hookResult = (hook as any).apply(this.core.api, parameters)\n\n if (!hookResult?.then) {\n // short circuit for non-thenables and non-Promises\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return hookResult\n }\n\n return Promise.resolve(hookResult).then((result) => {\n // action was fulfilled\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return result\n })\n })\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The acutal plugin\n * @param replaceContext When passed, the plugin context can be overridden.\n */\n private runSync<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, plugin: Plugin): ReturnType<PluginLifecycle[H]> {\n const hook = plugin[hookName]!\n\n // const context = this.pluginContexts.get(plugin)!;\n\n try {\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (hook as Function).apply(this.core.api, parameters)\n } catch (error: any) {\n return error\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noReturn() {}\n","import type { BuildOptions } from './build'\nimport type { WithPromise } from './utils/isPromise'\nimport type { LogLevel } from './types'\nimport type { Plugin } from './plugin'\n\n// TODO revert to this to have multiple options like async, object, ...\n// export type PluginOption = PluginOptions | false | null | undefined | PluginOption[] | Promise<PluginOptions | false | null | undefined | PluginOption[]>;\n\nexport interface UserConfig {\n /**\n * Project root directory. Can be an absolute path, or a path relative from\n * the location of the config file itself.\n * @default process.cwd()\n */\n root: string\n clear?: boolean\n mode?: 'single'\n input: {\n /**\n * Path or link to the input file\n */\n path: string\n }\n output: {\n /**\n * Path to export folder\n */\n path: string\n }\n /**\n * Array of Kubb plugins to use.\n */\n plugins?: Plugin[]\n /**\n * Log level to report when using the CLI\n */\n\n logLevel?: LogLevel\n}\n\nexport type UserConfigFn = (options: BuildOptions) => WithPromise<UserConfig>\nexport type UserConfigExport = WithPromise<UserConfig> | UserConfigFn\n\nexport const defaultConfig: Partial<UserConfig> = {\n root: process.cwd(),\n}\n\n/**\n * Type helper to make it easier to use kubb.config.ts\n * accepts a direct {@link UserConfig} object, or a function that returns it.\n * The function receives a {@link ConfigEnv} object that exposes two properties:\n */\nexport function defineConfig(config: UserConfigExport): UserConfigExport {\n return config\n}\n","/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { build } from './build'\n\nexport * from './config'\nexport * from './build'\nexport { Plugin, PluginOptions, PluginFactory, createPlugin } from './plugin'\nexport * from './utils'\nexport * from './types'\n\nexport default build\n"]}
1
+ {"version":3,"sources":["../src/build.ts","../src/utils/Emitter.ts","../src/utils/FileEmitter.ts","../src/plugin.ts","../src/utils/isPromise.ts","../src/utils/write.ts","../src/utils/format.ts","../src/utils/cache.ts","../src/utils/read.ts","../src/utils/PluginDriver.ts","../src/config.ts","../src/index.ts"],"names":["path","fse","argument0"],"mappings":";AAAA,OAAOA,WAAU;AAEjB,OAAOC,UAAS;;;ACAT,IAAM,UAAN,MAAmD;AAAA,EACvC,YAG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;AAAA,IACP,GAAG,GAAI;AAAA,EACT,CAAC;AACH;AAEO,SAAS,MAAM,SAA6C;AACjE,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI;AACF,0BAAoB,SAAS,OAAO;AAAA,IACtC,SAAS,GAAP;AACA,aAAO,CAAC;AAAA,IACV;AAAA,EACF,CAAC;AACH;;;AUtGO,IAAM,eAAe,CAC1B,YAMG;;;ACLL,IAAO,cAAQ","sourcesContent":["import path from 'path'\n\nimport fse from 'fs-extra'\n\nimport { PluginDriver } from './utils/PluginDriver'\n\nimport type { PluginContext, TransformResult, ValidationResult, LogLevel, KubbPlugin } from './types'\n\ntype BuildOutput = void\n\n// Same type as ora\ntype Spinner = {\n start: (text?: string) => Spinner\n succeed: (text: string) => Spinner\n stopAndPersist: (options: { text: string }) => Spinner\n render: () => Spinner\n text: string\n info: (text: string) => Spinner\n}\n\nexport type Logger = {\n log: (message: string, logLevel: LogLevel) => void\n spinner?: Spinner\n}\ntype BuildOptions = {\n config: PluginContext['config']\n mode: 'development' | 'production'\n logger?: Logger\n}\n\nasync function transformReducer(this: PluginContext, _previousCode: string, result: TransformResult, _plugin: KubbPlugin) {\n if (result === null) {\n return null\n }\n return result\n}\n\nasync function buildImplementation(options: BuildOptions, done: (output: BuildOutput) => void) {\n const { config, logger } = options\n\n if (config.output.clean) {\n await fse.remove(config.output.path)\n }\n\n const pluginDriver = new PluginDriver(config, { logger })\n const input = fse.readFileSync(path.resolve(config.root, config.input.path), 'utf-8')\n\n const validations = await pluginDriver.hookParallel<'validate', ValidationResult>('validate', [pluginDriver.plugins])\n const validationsWithMessage = validations.filter(Boolean)\n\n if (validationsWithMessage.some((validation) => typeof validation !== 'boolean')) {\n validationsWithMessage.forEach((validation) => {\n if (validation && typeof validation !== 'boolean' && validation?.message) {\n logger?.log(validation.message, 'warn')\n }\n })\n\n return\n }\n\n pluginDriver.fileEmitter.on('new', async (emittedFile) => {\n if (!emittedFile) {\n return\n }\n const { id } = emittedFile\n\n if (!id) {\n throw new Error('No id could be transformed, please add id to emitFile or use resolveId')\n }\n\n let { source: code } = emittedFile\n\n const loadedResult = await pluginDriver.hookFirst('load', [id])\n if (loadedResult) {\n code = loadedResult\n }\n\n if (code) {\n const transformedCode = await pluginDriver.hookReduceArg0('transform', [code, id], transformReducer)\n\n await pluginDriver.hookParallel('writeFile', [transformedCode, id])\n pluginDriver.fileEmitter.delete(emittedFile.id)\n }\n })\n\n await pluginDriver.hookParallel('buildStart', [config])\n\n pluginDriver.emitFile({\n id: config.input.path,\n name: undefined,\n source: input,\n })\n\n pluginDriver.fileEmitter.on('end', async () => {\n await pluginDriver.hookParallel('buildEnd')\n setTimeout(() => {\n done()\n }, 1000)\n })\n}\n\nexport function build(options: BuildOptions): Promise<BuildOutput> {\n return new Promise((resolve, reject) => {\n try {\n buildImplementation(options, resolve)\n } catch (e) {\n reject(e)\n }\n })\n}\n","export type Listener<T> = (value?: T) => void\n\nexport class Emitter<TValue = unknown, TTopics = unknown> {\n private readonly listeners: Set<{\n topic?: TTopics\n cb: Listener<TValue>\n }> = new Set()\n\n private readonly topics?: TTopics[]\n\n constructor(topics?: TTopics[]) {\n this.topics = topics\n }\n\n emit(...params: [topic: TTopics, value?: TValue] | [value?: TValue]) {\n const isTopic = (value: any): value is TTopics => !!this.topics?.includes(value)\n\n if (isTopic(params[0])) {\n this.listeners.forEach((listener) => {\n if (listener.topic === params[0]) {\n listener.cb(params[1])\n }\n })\n return\n }\n this.listeners.forEach((listener) => listener.cb(params[0] as TValue))\n }\n\n subscribe: (cb: Listener<TValue>) => () => void = (cb) => {\n const listener = {\n topic: undefined,\n cb,\n }\n this.listeners.add(listener)\n // Unsubscribe\n return () => this.listeners.delete(listener)\n }\n\n on(topic: TTopics, cb: Listener<TValue>) {\n const listener = {\n topic,\n cb,\n }\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n destroy: () => void = () => this.listeners.clear()\n}\n","import { Emitter } from './Emitter'\n\nexport interface EmittedFile {\n /**\n * equal to importee when getting passed through resolveId\n */\n id: string\n /**\n * The importer is the fully resolved id of the importing module.\n */\n importer?: string\n /**\n * Name to be used to dynamicly create the fileName(based on input.path)\n */\n name?: string\n /**\n * FileName will be the end result so no input.path will not be added\n */\n fileName?: string\n source?: string\n options?: Record<string, any>\n}\n\nexport type EmitFile = (emittedFile: EmittedFile) => void\n\ntype Topics = 'new' | 'delete' | 'end'\nexport class FileEmitter {\n private readonly emitter: Emitter<EmittedFile, Topics>\n\n private readonly filesByReferenceId: Map<string, EmittedFile> = new Map()\n\n constructor(emitter: Emitter<EmittedFile, Topics> = new Emitter<EmittedFile, Topics>(['delete', 'end', 'new'])) {\n this.emitter = emitter\n }\n\n // TODO add default resolveId in core that takes name or fileName to resolve the correct files\n emitFile(emitedFile: EmittedFile) {\n // save locally in this class\n this.assignReferenceId(emitedFile, emitedFile.id)\n this.emitter.emit('new', emitedFile)\n return new Promise<EmittedFile>((resolve) => {\n const subscribe = this.emitter.on('delete', (deletedFile) => {\n if (deletedFile?.id && deletedFile?.id === emitedFile.id) {\n resolve(deletedFile)\n return subscribe()\n }\n return undefined\n })\n })\n }\n\n delete(fileReferenceId: string) {\n const deletedFile = this.filesByReferenceId.get(fileReferenceId)\n this.filesByReferenceId.delete(fileReferenceId)\n if (this.filesByReferenceId.size === 0) {\n this.emitter.emit('end')\n }\n return this.emitter.emit('delete', deletedFile)\n }\n\n subscribe(...params: Parameters<typeof this.emitter['subscribe']>) {\n this.emitter.subscribe(...params)\n }\n\n on(...params: Parameters<typeof this.emitter['on']>) {\n this.emitter.on(...params)\n }\n\n private assignReferenceId(emittedFile: EmittedFile, fileReferenceId: string | undefined) {\n if (fileReferenceId) {\n this.filesByReferenceId.set(fileReferenceId, emittedFile)\n }\n }\n\n getEmittedFile = (fileReferenceId?: string | null): EmittedFile | undefined => {\n if (!fileReferenceId) {\n return undefined\n }\n return this.filesByReferenceId.get(fileReferenceId)\n }\n}\n","import path from 'path'\n\nimport { createPluginCache, getRelativePath, write } from './utils'\n\nimport type { FileEmitter, EmittedFile } from './utils'\nimport type { PluginContext, KubbPlugin, PluginFactoryOptions } from './types'\n\ntype KubbPluginFactory<T extends PluginFactoryOptions = PluginFactoryOptions> = (\n options: T['options']\n) => T['nested'] extends true ? Array<KubbPlugin<T>> : KubbPlugin<T>\n\nexport function createPlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(factory: KubbPluginFactory<T>) {\n return (options: T['options']) => {\n const plugin = factory(options)\n if (Array.isArray(plugin)) {\n throw new Error('Not implemented')\n }\n\n // default transform\n if (!plugin.transform) {\n plugin.transform = function transform(code) {\n return code\n }\n }\n\n return plugin\n }\n}\n\ntype Options = {\n config: PluginContext['config']\n fileEmitter: FileEmitter\n resolveId: PluginContext['resolveId']\n load: PluginContext['load']\n}\n\n// not publicly exported\nexport type CorePluginOptions = PluginFactoryOptions<Options, false, PluginContext>\n\nexport const name = 'core' as const\n\nexport const definePlugin = createPlugin<CorePluginOptions>((options) => {\n const { fileEmitter, resolveId, load } = options\n const indexFiles: EmittedFile[] = []\n\n const api: PluginContext = {\n get config() {\n return options.config\n },\n async emitFile(emittedFile) {\n const resolvedId = await resolveId(emittedFile.id, emittedFile.importer, emittedFile.options)\n const id = resolvedId || emittedFile.importer || emittedFile.id\n\n return fileEmitter.emitFile({\n ...emittedFile,\n id,\n })\n },\n addToRoot: (emittedFile: EmittedFile) => {\n indexFiles.push(emittedFile)\n },\n resolveId,\n load,\n cache: createPluginCache(Object.create(null)),\n }\n\n return {\n name,\n api,\n async buildEnd() {\n if (!indexFiles.length) {\n return\n }\n\n let index = ``\n\n indexFiles.forEach((item) => {\n index += `export * from \"${getRelativePath(path.resolve(this.config.root, this.config.output.path), item.id)}\";\\n`\n })\n\n await write(index, path.resolve(this.config.root, this.config.output.path, 'index.ts'), { format: true })\n },\n resolveId(importee, importer) {\n if (!importer) {\n return null\n }\n return path.resolve(importer, importee)\n },\n }\n})\n","import type { MaybePromise } from '../types'\n\nexport const isPromise = <T>(result: MaybePromise<T>): result is Promise<T> => {\n return typeof (result as any)?.then === 'function'\n}\n","/* eslint-disable consistent-return */\nimport fse from 'fs-extra'\n\nimport { format } from './format'\n\ntype WriteOptions = {\n format: boolean\n}\n\nexport const write = async (data: string, path: string, options: WriteOptions = { format: false }) => {\n const formattedData = options.format ? format(data) : data\n\n try {\n await fse.stat(path)\n const oldContent = await fse.readFile(path, { encoding: 'utf-8' })\n if (oldContent?.toString() === formattedData) {\n return\n }\n } catch (_err) {\n return fse.outputFile(path, formattedData)\n }\n\n return fse.outputFile(path, formattedData)\n}\n","import { format as prettierFormat } from 'prettier'\n\nimport type { Options } from 'prettier'\n\nconst formatOptions: Options = {\n tabWidth: 2,\n printWidth: 160,\n parser: 'typescript',\n singleQuote: true,\n semi: false,\n bracketSameLine: false,\n endOfLine: 'auto',\n}\nexport const format = (text: string) => {\n return prettierFormat(text, formatOptions)\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable consistent-return */\n\nexport interface Cache<TCache = any> {\n delete(id: string): boolean\n get<T = TCache>(id: string): T\n has(id: string): boolean\n set<T = TCache>(id: string, value: T): void\n}\n\nexport function createPluginCache(cache: any): Cache {\n return {\n delete(id: string) {\n return delete cache[id]\n },\n get(id: string) {\n const item = cache[id]\n if (!item) return\n item[0] = 0\n return item[1]\n },\n has(id: string) {\n const item = cache[id]\n if (!item) return false\n item[0] = 0\n return true\n },\n set(id: string, value: any) {\n cache[id] = [0, value]\n },\n }\n}\n","import path from 'path'\n\n// TODO check for a better way or resolving the relative path\nexport const getRelativePath = (from?: string | null, to?: string | null) => {\n if (!from || !to) {\n throw new Error('From and to should be filled in when retrieving the relativePath')\n }\n const newPath = path.relative(from, to).replace('../', '').replace('.ts', '').trimEnd()\n\n return `./${newPath}`\n}\n","/* eslint-disable no-await-in-loop */\n/* eslint-disable no-restricted-syntax */\nimport { FileEmitter } from './FileEmitter'\n\nimport { definePlugin } from '../plugin'\n\nimport type { KubbConfig, KubbPlugin, PluginLifecycleHooks, PluginLifecycle, MaybePromise } from '../types'\nimport type { Logger } from '../build'\nimport type { CorePluginOptions } from '../plugin'\n\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n/**\n * Get the type of the first argument in a function.\n * @example Arg0<(a: string, b: number) => void> -> string\n */\nexport type Argument0<H extends keyof PluginLifecycle> = Parameters<PluginLifecycle[H]>[0]\n\ntype Strategy = 'hookFirst' | 'hookParallel' | 'hookReduceArg0' | 'hookSeq'\n\n// This will make sure no input hook is omitted\nconst hookNames: {\n [P in PluginLifecycleHooks]: 1\n} = {\n validate: 1,\n buildStart: 1,\n resolveId: 1,\n load: 1,\n transform: 1,\n writeFile: 1,\n buildEnd: 1,\n}\nexport const hooks = Object.keys(hookNames) as [PluginLifecycleHooks]\n\nexport class PluginDriver {\n public plugins: KubbPlugin[]\n\n public readonly fileEmitter: FileEmitter = new FileEmitter()\n\n private readonly logger?: Logger\n\n private readonly config: KubbConfig\n\n public readonly core: KubbPlugin<CorePluginOptions> & { api: CorePluginOptions['api'] }\n\n constructor(config: KubbConfig, options: { logger?: Logger }) {\n this.logger = options.logger\n this.config = config\n this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter)\n\n this.core = definePlugin({ config, fileEmitter: this.fileEmitter, load: this.load, resolveId: this.resolveId }) as KubbPlugin<CorePluginOptions> & {\n api: CorePluginOptions['api']\n }\n this.plugins = [this.core, ...(config.plugins || [])]\n }\n\n emitFile(...params: Parameters<FileEmitter['emitFile']>) {\n return this.fileEmitter.emitFile(...params)\n }\n\n resolveId = (source: string, importer: string, meta: Record<string, any> | undefined) => {\n return this.hookFirst('resolveId', [source, importer, meta])\n }\n\n load = async (id: string) => {\n const result = await this.hookFirst('load', [id])\n return result\n }\n\n // chains, first non-null result stops and returns\n hookFirst<H extends PluginLifecycleHooks>(\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<KubbPlugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // parallel\n async hookParallel<H extends PluginLifecycleHooks, TOuput = void>(hookName: H, parameters?: Parameters<PluginLifecycle[H]> | undefined) {\n const parallelPromises: Promise<TOuput>[] = []\n\n for (const plugin of this.getSortedPlugins(hookName)) {\n if ((plugin[hookName] as { sequential?: boolean })?.sequential) {\n await Promise.all(parallelPromises)\n parallelPromises.length = 0\n await this.run('hookParallel', hookName, parameters, plugin)\n } else {\n const promise: Promise<TOuput> = this.run('hookParallel', hookName, parameters, plugin)\n\n parallelPromises.push(promise)\n }\n }\n return Promise.all(parallelPromises)\n }\n\n // chains, reduces returned value, handling the reduced value as the first hook argument\n hookReduceArg0<H extends PluginLifecycleHooks>(\n hookName: H,\n [argument0, ...rest]: Parameters<PluginLifecycle[H]>,\n reduce: (reduction: Argument0<H>, result: ReturnType<PluginLifecycle[H]>, plugin: KubbPlugin) => MaybePromise<Argument0<H> | null>\n ): Promise<Argument0<H>> {\n let promise = Promise.resolve(argument0)\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then((argument0) =>\n this.run('hookReduceArg0', hookName, [argument0, ...rest] as Parameters<PluginLifecycle[H]>, plugin).then((result) =>\n reduce.call(this.core.api, argument0, result, plugin)\n )\n )\n }\n return promise\n }\n\n // chains\n\n hookSeq<H extends PluginLifecycleHooks>(hookName: H, parameters?: Parameters<PluginLifecycle[H]>) {\n let promise: Promise<void> = Promise.resolve()\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then(() => this.run('hookSeq', hookName, parameters, plugin))\n }\n return promise.then(noReturn)\n }\n\n private getSortedPlugins(_hookName: keyof PluginLifecycle): KubbPlugin[] {\n return [...this.plugins]\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n // Implementation signature\n private run<H extends PluginLifecycleHooks, TResult = void>(\n strategy: Strategy,\n hookName: H,\n parameters: unknown[] | undefined,\n plugin: KubbPlugin\n ): Promise<TResult> {\n const hook = plugin[hookName]!\n\n return Promise.resolve().then(() => {\n if (typeof hook !== 'function') {\n return hook\n }\n\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`\n }\n\n const hookResult = (hook as any).apply(this.core.api, parameters)\n\n if (!hookResult?.then) {\n // short circuit for non-thenables and non-Promises\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return hookResult\n }\n\n return Promise.resolve(hookResult).then((result) => {\n // action was fulfilled\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return result\n })\n })\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The acutal plugin\n * @param replaceContext When passed, the plugin context can be overridden.\n */\n private runSync<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, plugin: KubbPlugin): ReturnType<PluginLifecycle[H]> {\n const hook = plugin[hookName]!\n\n // const context = this.pluginContexts.get(plugin)!;\n\n try {\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (hook as Function).apply(this.core.api, parameters)\n } catch (error: any) {\n return error\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noReturn() {}\n","import type { MaybePromise, KubbUserConfig, CLIOptions } from './types'\n\n/**\n * Type helper to make it easier to use kubb.config.ts\n * accepts a direct {@link KubbConfig} object, or a function that returns it.\n * The function receives a {@link ConfigEnv} object that exposes two properties:\n */\nexport const defineConfig = (\n options:\n | MaybePromise<KubbUserConfig>\n | ((\n /** The options derived from CLI flags */\n cliOptions: CLIOptions\n ) => MaybePromise<KubbUserConfig>)\n) => options\n","/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { build } from './build'\n\nexport * from './config'\nexport * from './build'\nexport { CorePluginOptions, createPlugin } from './plugin'\nexport * from './utils'\nexport * from './types'\n\nexport default build\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/core",
3
- "version": "0.14.0",
3
+ "version": "0.19.0",
4
4
  "description": "Generator core",
5
5
  "repository": {
6
6
  "type": "git",
@@ -24,9 +24,15 @@
24
24
  "description": "Mode type",
25
25
  "enum": ["single"]
26
26
  },
27
- "clear": {
28
- "type": "boolean",
29
- "description": "Clear previous generated files"
27
+ "hooks": {
28
+ "type": "object",
29
+ "description": "Hooks that can be called when a specific action is done in Kubb.",
30
+ "properties": {
31
+ "end": {
32
+ "type": "string",
33
+ "description": "Hook that will be called at the end of all executions."
34
+ }
35
+ }
30
36
  },
31
37
  "output": {
32
38
  "type": "object",
@@ -35,6 +41,10 @@
35
41
  "path": {
36
42
  "type": "string",
37
43
  "description": "Output path"
44
+ },
45
+ "clean": {
46
+ "type": "boolean",
47
+ "description": "Clean previous generated files"
38
48
  }
39
49
  }
40
50
  },