@dtwo/kit 3.0.0-rc.13
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/LICENSE +21 -0
- package/README.md +3 -0
- package/dist/index.d.ts +333 -0
- package/dist/index.mjs +796 -0
- package/package.json +41 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 - Dtwo Project
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { ModuleOptions, ModuleDefinition, DtwoModule, Dtwo, DtwoConfig, DtwoOptions, ImportPresetWithDeprecation, DtwoCompatibility, DtwoCompatibilityIssues, ComponentsDir, Component, DtwoTemplate, DtwoHooks, DtwoPlugin, DtwoPluginTemplate, ResolvedDtwoTemplate } from '@dtwo/schema';
|
|
2
|
+
import { LoadConfigOptions } from 'c12';
|
|
3
|
+
import { Import } from 'unimport';
|
|
4
|
+
import { Configuration, WebpackPluginInstance } from 'webpack';
|
|
5
|
+
import { UserConfig, Plugin } from 'wite';
|
|
6
|
+
import * as unctx_index from 'unctx/index';
|
|
7
|
+
import { HoleEventHandler, HoleDevEventHandler, Hole } from 'holepack';
|
|
8
|
+
import * as consola from 'consola';
|
|
9
|
+
import { genSafeVariableName } from 'knitwork';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Define a Dtwo module, automatically merging defaults with user provided options, installing
|
|
13
|
+
* any hooks that are provided, and calling an optional setup function for full control.
|
|
14
|
+
*/
|
|
15
|
+
declare function defineDtwoModule<OptionsT extends ModuleOptions>(definition: ModuleDefinition<OptionsT>): DtwoModule<OptionsT>;
|
|
16
|
+
|
|
17
|
+
/** Installs a module on a Dtwo instance. */
|
|
18
|
+
declare function installModule(moduleToInstall: string | DtwoModule, _inlineOptions?: any, _dtwo?: Dtwo): Promise<void>;
|
|
19
|
+
|
|
20
|
+
interface LoadDtwoConfigOptions extends LoadConfigOptions<DtwoConfig> {
|
|
21
|
+
}
|
|
22
|
+
declare function loadDtwoConfig(opts: LoadDtwoConfigOptions): Promise<DtwoOptions>;
|
|
23
|
+
|
|
24
|
+
interface LoadDtwoOptions extends LoadDtwoConfigOptions {
|
|
25
|
+
/** Load dtwo with development mode */
|
|
26
|
+
dev?: boolean;
|
|
27
|
+
/** Use lazy initialization of dtwo if set to false */
|
|
28
|
+
ready?: boolean;
|
|
29
|
+
/** @deprecated Use cwd option */
|
|
30
|
+
rootDir?: LoadDtwoConfigOptions['cwd'];
|
|
31
|
+
/** @deprecated use overrides option */
|
|
32
|
+
config?: LoadDtwoConfigOptions['overrides'];
|
|
33
|
+
}
|
|
34
|
+
declare function loadDtwo(opts: LoadDtwoOptions): Promise<Dtwo>;
|
|
35
|
+
declare function buildDtwo(dtwo: Dtwo): Promise<any>;
|
|
36
|
+
|
|
37
|
+
declare function addImports(imports: Import | Import[]): void;
|
|
38
|
+
declare function addImportsDir(dirs: string | string[]): void;
|
|
39
|
+
declare function addImportsSources(presets: ImportPresetWithDeprecation | ImportPresetWithDeprecation[]): void;
|
|
40
|
+
|
|
41
|
+
interface ExtendConfigOptions {
|
|
42
|
+
/**
|
|
43
|
+
* Install plugin on dev
|
|
44
|
+
*
|
|
45
|
+
* @default true
|
|
46
|
+
*/
|
|
47
|
+
dev?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Install plugin on build
|
|
50
|
+
*
|
|
51
|
+
* @default true
|
|
52
|
+
*/
|
|
53
|
+
build?: boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Install plugin on server side
|
|
56
|
+
*
|
|
57
|
+
* @default true
|
|
58
|
+
*/
|
|
59
|
+
server?: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Install plugin on client side
|
|
62
|
+
*
|
|
63
|
+
* @default true
|
|
64
|
+
*/
|
|
65
|
+
client?: boolean;
|
|
66
|
+
}
|
|
67
|
+
interface ExtendWebpackConfigOptions extends ExtendConfigOptions {
|
|
68
|
+
}
|
|
69
|
+
interface ExtendWiteConfigOptions extends ExtendConfigOptions {
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Extend Webpack config
|
|
73
|
+
*
|
|
74
|
+
* The fallback function might be called multiple times
|
|
75
|
+
* when applying to both client and server builds.
|
|
76
|
+
*/
|
|
77
|
+
declare function extendWebpackConfig(fn: ((config: Configuration) => void), options?: ExtendWebpackConfigOptions): void;
|
|
78
|
+
/**
|
|
79
|
+
* Extend Wite config
|
|
80
|
+
*/
|
|
81
|
+
declare function extendWiteConfig(fn: ((config: UserConfig) => void), options?: ExtendWiteConfigOptions): (() => void) | undefined;
|
|
82
|
+
/**
|
|
83
|
+
* Append Webpack plugin to the config.
|
|
84
|
+
*/
|
|
85
|
+
declare function addWebpackPlugin(plugin: WebpackPluginInstance | WebpackPluginInstance[], options?: ExtendWebpackConfigOptions): void;
|
|
86
|
+
/**
|
|
87
|
+
* Append Wite plugin to the config.
|
|
88
|
+
*/
|
|
89
|
+
declare function addWitePlugin(plugin: Plugin | Plugin[], options?: ExtendWiteConfigOptions): void;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Check version constraints and return incompatibility issues as an array
|
|
93
|
+
*/
|
|
94
|
+
declare function checkDtwoCompatibility(constraints: DtwoCompatibility, dtwo?: Dtwo): Promise<DtwoCompatibilityIssues>;
|
|
95
|
+
/**
|
|
96
|
+
* Check version constraints and throw a detailed error if has any, otherwise returns true
|
|
97
|
+
*/
|
|
98
|
+
declare function assertDtwoCompatibility(constraints: DtwoCompatibility, dtwo?: Dtwo): Promise<true>;
|
|
99
|
+
/**
|
|
100
|
+
* Check version constraints and return true if passed, otherwise returns false
|
|
101
|
+
*/
|
|
102
|
+
declare function hasDtwoCompatibility(constraints: DtwoCompatibility, dtwo?: Dtwo): Promise<boolean>;
|
|
103
|
+
/**
|
|
104
|
+
* Check if current dtwo instance is version 2 legacy
|
|
105
|
+
*/
|
|
106
|
+
declare function isDtwo2(dtwo?: Dtwo): any;
|
|
107
|
+
/**
|
|
108
|
+
* Check if current dtwo instance is version 3
|
|
109
|
+
*/
|
|
110
|
+
declare function isDtwo3(dtwo?: Dtwo): any;
|
|
111
|
+
/**
|
|
112
|
+
* Get dtwo version
|
|
113
|
+
*/
|
|
114
|
+
declare function getDtwoVersion(dtwo?: Dtwo | any): any;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Register a directory to be scanned for components and imported only when used.
|
|
118
|
+
*
|
|
119
|
+
* Requires Dtwo 2.13+
|
|
120
|
+
*/
|
|
121
|
+
declare function addComponentsDir(dir: ComponentsDir): Promise<void>;
|
|
122
|
+
type AddComponentOptions = {
|
|
123
|
+
name: string;
|
|
124
|
+
filePath: string;
|
|
125
|
+
} & Partial<Exclude<Component, 'shortPath' | 'async' | 'level' | 'import' | 'asyncImport'>>;
|
|
126
|
+
/**
|
|
127
|
+
* Register a directory to be scanned for components and imported only when used.
|
|
128
|
+
*
|
|
129
|
+
* Requires Dtwo 2.13+
|
|
130
|
+
*/
|
|
131
|
+
declare function addComponent(opts: AddComponentOptions): Promise<void>;
|
|
132
|
+
|
|
133
|
+
/** Direct access to the Dtwo context - see https://github.com/unjs/unctx. */
|
|
134
|
+
declare const dtwoCtx: unctx_index.UseContext<Dtwo>;
|
|
135
|
+
/**
|
|
136
|
+
* Get access to Dtwo instance.
|
|
137
|
+
*
|
|
138
|
+
* Throws an error if Dtwo instance is unavailable.
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* ```js
|
|
142
|
+
* const dtwo = useDtwo()
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
declare function useDtwo(): Dtwo;
|
|
146
|
+
/**
|
|
147
|
+
* Get access to Dtwo instance.
|
|
148
|
+
*
|
|
149
|
+
* Returns null if Dtwo instance is unavailable.
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* ```js
|
|
153
|
+
* const dtwo = tryUseDtwo()
|
|
154
|
+
* if (dtwo) {
|
|
155
|
+
* // Do something
|
|
156
|
+
* }
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
declare function tryUseDtwo(): Dtwo | null;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Adds a hole server handler
|
|
163
|
+
*
|
|
164
|
+
*/
|
|
165
|
+
declare function addServerHandler(handler: HoleEventHandler): void;
|
|
166
|
+
/**
|
|
167
|
+
* Adds a hole server handler for development-only
|
|
168
|
+
*
|
|
169
|
+
*/
|
|
170
|
+
declare function addDevServerHandler(handler: HoleDevEventHandler): void;
|
|
171
|
+
/**
|
|
172
|
+
* Adds a Hole plugin
|
|
173
|
+
*/
|
|
174
|
+
declare function addServerPlugin(plugin: string): void;
|
|
175
|
+
/**
|
|
176
|
+
* Adds routes to be prerendered
|
|
177
|
+
*/
|
|
178
|
+
declare function addPrerenderRoutes(routes: string | string[]): void;
|
|
179
|
+
/**
|
|
180
|
+
* Access to the Hole instance
|
|
181
|
+
*
|
|
182
|
+
* **Note:** You can call `useHole()` only after `ready` hook.
|
|
183
|
+
*
|
|
184
|
+
* **Note:** Changes to the Hole instance configuration are not applied.
|
|
185
|
+
*
|
|
186
|
+
* @example
|
|
187
|
+
*
|
|
188
|
+
* ```ts
|
|
189
|
+
* dtwo.hook('ready', () => {
|
|
190
|
+
* console.log(useHole())
|
|
191
|
+
* })
|
|
192
|
+
* ```
|
|
193
|
+
*/
|
|
194
|
+
declare function useHole(): Hole;
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Return a filter function to filter an array of paths
|
|
198
|
+
*/
|
|
199
|
+
declare function isIgnored(pathname: string): boolean;
|
|
200
|
+
|
|
201
|
+
declare function addLayout(this: any, template: DtwoTemplate, name?: string): void;
|
|
202
|
+
|
|
203
|
+
declare function extendPages(cb: DtwoHooks['pages:extend']): void;
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Normalize a dtwo plugin object
|
|
207
|
+
*/
|
|
208
|
+
declare function normalizePlugin(plugin: DtwoPlugin | string): DtwoPlugin;
|
|
209
|
+
/**
|
|
210
|
+
* Registers a dtwo plugin and to the plugins array.
|
|
211
|
+
*
|
|
212
|
+
* Note: You can use mode or .client and .server modifiers with fileName option
|
|
213
|
+
* to use plugin only in client or server side.
|
|
214
|
+
*
|
|
215
|
+
* Note: By default plugin is prepended to the plugins array. You can use second argument to append (push) instead.
|
|
216
|
+
*
|
|
217
|
+
* @example
|
|
218
|
+
* ```js
|
|
219
|
+
* addPlugin({
|
|
220
|
+
* src: path.resolve(__dirname, 'templates/foo.js'),
|
|
221
|
+
* filename: 'foo.server.js' // [optional] only include in server bundle
|
|
222
|
+
* })
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
225
|
+
interface AddPluginOptions {
|
|
226
|
+
append?: boolean;
|
|
227
|
+
}
|
|
228
|
+
declare function addPlugin(_plugin: DtwoPlugin | string, opts?: AddPluginOptions): DtwoPlugin;
|
|
229
|
+
/**
|
|
230
|
+
* Adds a template and registers as a dtwo plugin.
|
|
231
|
+
*/
|
|
232
|
+
declare function addPluginTemplate(plugin: DtwoPluginTemplate | string, opts?: AddPluginOptions): DtwoPlugin;
|
|
233
|
+
|
|
234
|
+
interface ResolvePathOptions {
|
|
235
|
+
/** Base for resolving paths from. Default is Dtwo rootDir. */
|
|
236
|
+
cwd?: string;
|
|
237
|
+
/** An object of aliases. Default is Dtwo configured aliases. */
|
|
238
|
+
alias?: Record<string, string>;
|
|
239
|
+
/** The file extensions to try. Default is Dtwo configured extensions. */
|
|
240
|
+
extensions?: string[];
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Resolve full path to a file or directory respecting Dtwo alias and extensions options
|
|
244
|
+
*
|
|
245
|
+
* If path could not be resolved, normalized input path will be returned
|
|
246
|
+
*/
|
|
247
|
+
declare function resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
|
|
248
|
+
/**
|
|
249
|
+
* Try to resolve first existing file in paths
|
|
250
|
+
*/
|
|
251
|
+
declare function findPath(paths: string | string[], opts?: ResolvePathOptions, pathType?: 'file' | 'dir'): Promise<string | null>;
|
|
252
|
+
/**
|
|
253
|
+
* Resolve path aliases respecting Dtwo alias options
|
|
254
|
+
*/
|
|
255
|
+
declare function resolveAlias(path: string, alias?: Record<string, string>): string;
|
|
256
|
+
interface Resolver {
|
|
257
|
+
resolve(...path: string[]): string;
|
|
258
|
+
resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Create a relative resolver
|
|
262
|
+
*/
|
|
263
|
+
declare function createResolver(base: string | URL): Resolver;
|
|
264
|
+
declare function resolveFiles(path: string, pattern: string | string[], opts?: {
|
|
265
|
+
followSymbolicLinks?: boolean;
|
|
266
|
+
}): Promise<string[]>;
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Renders given template using lodash template during build into the project buildDir
|
|
270
|
+
*/
|
|
271
|
+
declare function addTemplate(_template: DtwoTemplate<any> | string): ResolvedDtwoTemplate<any>;
|
|
272
|
+
/**
|
|
273
|
+
* Normalize a dtwo template object
|
|
274
|
+
*/
|
|
275
|
+
declare function normalizeTemplate(template: DtwoTemplate<any> | string): ResolvedDtwoTemplate<any>;
|
|
276
|
+
/**
|
|
277
|
+
* Trigger rebuilding Dtwo templates
|
|
278
|
+
*
|
|
279
|
+
* You can pass a filter within the options to selectively regenerate a subset of templates.
|
|
280
|
+
*/
|
|
281
|
+
declare function updateTemplates(options?: {
|
|
282
|
+
filter?: (template: ResolvedDtwoTemplate<any>) => boolean;
|
|
283
|
+
}): Promise<any>;
|
|
284
|
+
|
|
285
|
+
declare const logger: consola.Consola;
|
|
286
|
+
declare function useLogger(scope?: string): consola.Consola;
|
|
287
|
+
|
|
288
|
+
/** @deprecated Do not use CJS utils */
|
|
289
|
+
interface ResolveModuleOptions {
|
|
290
|
+
paths?: string | string[];
|
|
291
|
+
}
|
|
292
|
+
/** @deprecated Do not use CJS utils */
|
|
293
|
+
interface RequireModuleOptions extends ResolveModuleOptions {
|
|
294
|
+
/** Clear the require cache (force fresh require) but only if not within `node_modules` */
|
|
295
|
+
clearCache?: boolean;
|
|
296
|
+
/** Automatically de-default the result of requiring the module. */
|
|
297
|
+
interopDefault?: boolean;
|
|
298
|
+
}
|
|
299
|
+
/** @deprecated Do not use CJS utils */
|
|
300
|
+
declare function isNodeModules(id: string): boolean;
|
|
301
|
+
/** @deprecated Do not use CJS utils */
|
|
302
|
+
declare function clearRequireCache(id: string): void;
|
|
303
|
+
/** @deprecated Do not use CJS utils */
|
|
304
|
+
declare function scanRequireTree(id: string, files?: Set<string>): Set<string>;
|
|
305
|
+
/** @deprecated Do not use CJS utils */
|
|
306
|
+
declare function getRequireCacheItem(id: string): NodeModule | undefined;
|
|
307
|
+
/** Resolve the `package.json` file for a given module. */
|
|
308
|
+
declare function requireModulePkg(id: string, opts?: RequireModuleOptions): any;
|
|
309
|
+
/** @deprecated Do not use CJS utils */
|
|
310
|
+
declare function resolveModule(id: string, opts?: ResolveModuleOptions): string;
|
|
311
|
+
/** @deprecated Do not use CJS utils */
|
|
312
|
+
declare function tryResolveModule(path: string, opts?: ResolveModuleOptions): string | null;
|
|
313
|
+
/** @deprecated Do not use CJS utils */
|
|
314
|
+
declare function requireModule(id: string, opts?: RequireModuleOptions): any;
|
|
315
|
+
/** @deprecated Do not use CJS utils */
|
|
316
|
+
declare function importModule(id: string, opts?: RequireModuleOptions): Promise<any>;
|
|
317
|
+
/** @deprecated Do not use CJS utils */
|
|
318
|
+
declare function tryImportModule(id: string, opts?: RequireModuleOptions): Promise<any> | undefined;
|
|
319
|
+
/** @deprecated Do not use CJS utils */
|
|
320
|
+
declare function tryRequireModule(id: string, opts?: RequireModuleOptions): any;
|
|
321
|
+
|
|
322
|
+
/** @deprecated */
|
|
323
|
+
declare function compileTemplate(template: DtwoTemplate, ctx: any): Promise<string>;
|
|
324
|
+
/** @deprecated */
|
|
325
|
+
declare const templateUtils: {
|
|
326
|
+
serialize: (data: any) => string;
|
|
327
|
+
importName: typeof genSafeVariableName;
|
|
328
|
+
importSources: (sources: string | string[], { lazy }?: {
|
|
329
|
+
lazy?: boolean | undefined;
|
|
330
|
+
}) => string;
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
export { AddComponentOptions, AddPluginOptions, ExtendConfigOptions, ExtendWebpackConfigOptions, ExtendWiteConfigOptions, LoadDtwoConfigOptions, LoadDtwoOptions, RequireModuleOptions, ResolveModuleOptions, ResolvePathOptions, Resolver, addComponent, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addServerHandler, addServerPlugin, addTemplate, addWebpackPlugin, addWitePlugin, assertDtwoCompatibility, buildDtwo, checkDtwoCompatibility, clearRequireCache, compileTemplate, createResolver, defineDtwoModule, dtwoCtx, extendPages, extendWebpackConfig, extendWiteConfig, findPath, getDtwoVersion, getRequireCacheItem, hasDtwoCompatibility, importModule, installModule, isDtwo2, isDtwo3, isIgnored, isNodeModules, loadDtwo, loadDtwoConfig, logger, normalizePlugin, normalizeTemplate, requireModule, requireModulePkg, resolveAlias, resolveFiles, resolveModule, resolvePath, scanRequireTree, templateUtils, tryImportModule, tryRequireModule, tryResolveModule, tryUseDtwo, updateTemplates, useDtwo, useHole, useLogger };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,796 @@
|
|
|
1
|
+
import { promises, existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import defu from 'defu';
|
|
3
|
+
import { applyDefaults } from 'untyped';
|
|
4
|
+
import { dirname, join, normalize, relative, isAbsolute, resolve, basename, parse } from 'pathe';
|
|
5
|
+
import consola from 'consola';
|
|
6
|
+
import { getContext } from 'unctx';
|
|
7
|
+
import satisfies from 'semver/functions/satisfies.js';
|
|
8
|
+
import lodashTemplate from 'lodash.template';
|
|
9
|
+
import { genSafeVariableName, genDynamicImport, genImport } from 'knitwork';
|
|
10
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
11
|
+
import { interopDefault } from 'mlly';
|
|
12
|
+
import jiti from 'jiti';
|
|
13
|
+
import { globby } from 'globby';
|
|
14
|
+
import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
|
|
15
|
+
import ignore from 'ignore';
|
|
16
|
+
import { loadConfig } from 'c12';
|
|
17
|
+
import { DtwoConfigSchema } from '@dtwo/schema';
|
|
18
|
+
import { resolvePackageJSON, readPackageJSON } from 'pkg-types';
|
|
19
|
+
import { kebabCase, pascalCase } from 'scule';
|
|
20
|
+
import hash from 'hash-sum';
|
|
21
|
+
|
|
22
|
+
const logger = consola;
|
|
23
|
+
function useLogger(scope) {
|
|
24
|
+
return scope ? logger.withScope(scope) : logger;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const dtwoCtx = getContext("dtwo");
|
|
28
|
+
function useDtwo() {
|
|
29
|
+
const instance = dtwoCtx.tryUse();
|
|
30
|
+
if (!instance) {
|
|
31
|
+
throw new Error("Dtwo instance is unavailable!");
|
|
32
|
+
}
|
|
33
|
+
return instance;
|
|
34
|
+
}
|
|
35
|
+
function tryUseDtwo() {
|
|
36
|
+
return dtwoCtx.tryUse();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function checkDtwoCompatibility(constraints, dtwo = useDtwo()) {
|
|
40
|
+
const issues = [];
|
|
41
|
+
if (constraints.dtwo) {
|
|
42
|
+
const dtwoVersion = getDtwoVersion(dtwo);
|
|
43
|
+
const dtwoSemanticVersion = dtwoVersion.replace(/-[0-9]+\.[0-9a-f]{7,8}/, "");
|
|
44
|
+
if (!satisfies(dtwoSemanticVersion, constraints.dtwo, { includePrerelease: true })) {
|
|
45
|
+
issues.push({
|
|
46
|
+
name: "dtwo",
|
|
47
|
+
message: `Dtwo version \`${constraints.dtwo}\` is required but currently using \`${dtwoVersion}\``
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (isDtwo2(dtwo)) {
|
|
52
|
+
const bridgeRequirement = constraints.bridge;
|
|
53
|
+
const hasBridge = !!dtwo.options.bridge;
|
|
54
|
+
if (bridgeRequirement === true && !hasBridge) {
|
|
55
|
+
issues.push({
|
|
56
|
+
name: "bridge",
|
|
57
|
+
message: "Dtwo bridge is required"
|
|
58
|
+
});
|
|
59
|
+
} else if (bridgeRequirement === false && hasBridge) {
|
|
60
|
+
issues.push({
|
|
61
|
+
name: "bridge",
|
|
62
|
+
message: "Dtwo bridge is not supported"
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
await dtwo.callHook("kit:compatibility", constraints, issues);
|
|
67
|
+
issues.toString = () => issues.map((issue) => ` - [${issue.name}] ${issue.message}`).join("\n");
|
|
68
|
+
return issues;
|
|
69
|
+
}
|
|
70
|
+
async function assertDtwoCompatibility(constraints, dtwo = useDtwo()) {
|
|
71
|
+
const issues = await checkDtwoCompatibility(constraints, dtwo);
|
|
72
|
+
if (issues.length) {
|
|
73
|
+
throw new Error("Dtwo compatibility issues found:\n" + issues.toString());
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
async function hasDtwoCompatibility(constraints, dtwo = useDtwo()) {
|
|
78
|
+
const issues = await checkDtwoCompatibility(constraints, dtwo);
|
|
79
|
+
return !issues.length;
|
|
80
|
+
}
|
|
81
|
+
function isDtwo2(dtwo = useDtwo()) {
|
|
82
|
+
return getDtwoVersion(dtwo).startsWith("2.");
|
|
83
|
+
}
|
|
84
|
+
function isDtwo3(dtwo = useDtwo()) {
|
|
85
|
+
return getDtwoVersion(dtwo).startsWith("3.");
|
|
86
|
+
}
|
|
87
|
+
function getDtwoVersion(dtwo = useDtwo()) {
|
|
88
|
+
const version = (dtwo?._version || dtwo?.version || dtwo?.constructor?.version || "").replace(/^v/g, "");
|
|
89
|
+
if (!version) {
|
|
90
|
+
throw new Error("Cannot determine dtwo version! Is current instance passed?");
|
|
91
|
+
}
|
|
92
|
+
return version;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function compileTemplate(template, ctx) {
|
|
96
|
+
const data = { ...ctx, options: template.options };
|
|
97
|
+
if (template.src) {
|
|
98
|
+
try {
|
|
99
|
+
const srcContents = await promises.readFile(template.src, "utf-8");
|
|
100
|
+
return lodashTemplate(srcContents, {})(data);
|
|
101
|
+
} catch (err) {
|
|
102
|
+
console.error("Error compiling template: ", template);
|
|
103
|
+
throw err;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (template.getContents) {
|
|
107
|
+
return template.getContents(data);
|
|
108
|
+
}
|
|
109
|
+
throw new Error("Invalid template: " + JSON.stringify(template));
|
|
110
|
+
}
|
|
111
|
+
const serialize = (data) => JSON.stringify(data, null, 2).replace(/"{(.+)}"(?=,?$)/gm, (r) => JSON.parse(r).replace(/^{(.*)}$/, "$1"));
|
|
112
|
+
const importSources = (sources, { lazy = false } = {}) => {
|
|
113
|
+
if (!Array.isArray(sources)) {
|
|
114
|
+
sources = [sources];
|
|
115
|
+
}
|
|
116
|
+
return sources.map((src) => {
|
|
117
|
+
if (lazy) {
|
|
118
|
+
return `const ${genSafeVariableName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`;
|
|
119
|
+
}
|
|
120
|
+
return genImport(src, genSafeVariableName(src));
|
|
121
|
+
}).join("\n");
|
|
122
|
+
};
|
|
123
|
+
const importName = genSafeVariableName;
|
|
124
|
+
const templateUtils = { serialize, importName, importSources };
|
|
125
|
+
|
|
126
|
+
function defineDtwoModule(definition) {
|
|
127
|
+
if (!definition.meta) {
|
|
128
|
+
definition.meta = {};
|
|
129
|
+
}
|
|
130
|
+
if (definition.meta.configKey === void 0) {
|
|
131
|
+
definition.meta.configKey = definition.meta.name;
|
|
132
|
+
}
|
|
133
|
+
async function getOptions(inlineOptions, dtwo = useDtwo()) {
|
|
134
|
+
const configKey = definition.meta.configKey || definition.meta.name;
|
|
135
|
+
const _defaults = definition.defaults instanceof Function ? definition.defaults(dtwo) : definition.defaults;
|
|
136
|
+
let _options = defu(inlineOptions, dtwo.options[configKey], _defaults);
|
|
137
|
+
if (definition.schema) {
|
|
138
|
+
_options = await applyDefaults(definition.schema, _options);
|
|
139
|
+
}
|
|
140
|
+
return Promise.resolve(_options);
|
|
141
|
+
}
|
|
142
|
+
async function normalizedModule(inlineOptions, dtwo) {
|
|
143
|
+
if (!dtwo) {
|
|
144
|
+
dtwo = tryUseDtwo() || this.dtwo;
|
|
145
|
+
}
|
|
146
|
+
const uniqueKey = definition.meta.name || definition.meta.configKey;
|
|
147
|
+
if (uniqueKey) {
|
|
148
|
+
dtwo.options._requiredModules = dtwo.options._requiredModules || {};
|
|
149
|
+
if (dtwo.options._requiredModules[uniqueKey]) {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
dtwo.options._requiredModules[uniqueKey] = true;
|
|
153
|
+
}
|
|
154
|
+
if (definition.meta.compatibility) {
|
|
155
|
+
const issues = await checkDtwoCompatibility(definition.meta.compatibility, dtwo);
|
|
156
|
+
if (issues.length) {
|
|
157
|
+
logger.warn(`Module \`${definition.meta.name}\` is disabled due to incompatibility issues:
|
|
158
|
+
${issues.toString()}`);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
dtwo2Shims(dtwo);
|
|
163
|
+
const _options = await getOptions(inlineOptions, dtwo);
|
|
164
|
+
if (definition.hooks) {
|
|
165
|
+
dtwo.hooks.addHooks(definition.hooks);
|
|
166
|
+
}
|
|
167
|
+
await definition.setup?.call(null, _options, dtwo);
|
|
168
|
+
}
|
|
169
|
+
normalizedModule.getMeta = () => Promise.resolve(definition.meta);
|
|
170
|
+
normalizedModule.getOptions = getOptions;
|
|
171
|
+
return normalizedModule;
|
|
172
|
+
}
|
|
173
|
+
const DTWO2_SHIMS_KEY = "__dtwo2_shims_key__";
|
|
174
|
+
function dtwo2Shims(dtwo) {
|
|
175
|
+
if (!isDtwo2(dtwo) || dtwo[DTWO2_SHIMS_KEY]) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
dtwo[DTWO2_SHIMS_KEY] = true;
|
|
179
|
+
dtwo.hooks = dtwo;
|
|
180
|
+
if (!dtwoCtx.tryUse()) {
|
|
181
|
+
dtwoCtx.set(dtwo);
|
|
182
|
+
dtwo.hook("close", () => dtwoCtx.unset());
|
|
183
|
+
}
|
|
184
|
+
let virtualTemplates;
|
|
185
|
+
dtwo.hook("builder:prepared", (_builder, buildOptions) => {
|
|
186
|
+
virtualTemplates = buildOptions.templates.filter((t) => t.getContents);
|
|
187
|
+
for (const template of virtualTemplates) {
|
|
188
|
+
buildOptions.templates.splice(buildOptions.templates.indexOf(template), 1);
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
dtwo.hook("build:templates", async (templates) => {
|
|
192
|
+
const context = {
|
|
193
|
+
dtwo,
|
|
194
|
+
utils: templateUtils,
|
|
195
|
+
app: {
|
|
196
|
+
dir: dtwo.options.srcDir,
|
|
197
|
+
extensions: dtwo.options.extensions,
|
|
198
|
+
plugins: dtwo.options.plugins,
|
|
199
|
+
templates: [
|
|
200
|
+
...templates.templatesFiles,
|
|
201
|
+
...virtualTemplates
|
|
202
|
+
],
|
|
203
|
+
templateVars: templates.templateVars
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
for await (const template of virtualTemplates) {
|
|
207
|
+
const contents = await compileTemplate({ ...template, src: "" }, context);
|
|
208
|
+
await promises.mkdir(dirname(template.dst), { recursive: true });
|
|
209
|
+
await promises.writeFile(template.dst, contents);
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const _require = jiti(process.cwd(), { interopDefault: true, esmResolve: true });
|
|
215
|
+
function isNodeModules(id) {
|
|
216
|
+
return /[/\\]node_modules[/\\]/.test(id);
|
|
217
|
+
}
|
|
218
|
+
function clearRequireCache(id) {
|
|
219
|
+
if (isNodeModules(id)) {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const entry = getRequireCacheItem(id);
|
|
223
|
+
if (!entry) {
|
|
224
|
+
delete _require.cache[id];
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (entry.parent) {
|
|
228
|
+
entry.parent.children = entry.parent.children.filter((e) => e.id !== id);
|
|
229
|
+
}
|
|
230
|
+
for (const child of entry.children) {
|
|
231
|
+
clearRequireCache(child.id);
|
|
232
|
+
}
|
|
233
|
+
delete _require.cache[id];
|
|
234
|
+
}
|
|
235
|
+
function scanRequireTree(id, files = /* @__PURE__ */ new Set()) {
|
|
236
|
+
if (isNodeModules(id) || files.has(id)) {
|
|
237
|
+
return files;
|
|
238
|
+
}
|
|
239
|
+
const entry = getRequireCacheItem(id);
|
|
240
|
+
if (!entry) {
|
|
241
|
+
files.add(id);
|
|
242
|
+
return files;
|
|
243
|
+
}
|
|
244
|
+
files.add(entry.id);
|
|
245
|
+
for (const child of entry.children) {
|
|
246
|
+
scanRequireTree(child.id, files);
|
|
247
|
+
}
|
|
248
|
+
return files;
|
|
249
|
+
}
|
|
250
|
+
function getRequireCacheItem(id) {
|
|
251
|
+
try {
|
|
252
|
+
return _require.cache[id];
|
|
253
|
+
} catch (e) {
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
function requireModulePkg(id, opts = {}) {
|
|
257
|
+
return requireModule(join(id, "package.json"), opts);
|
|
258
|
+
}
|
|
259
|
+
function resolveModule(id, opts = {}) {
|
|
260
|
+
return normalize(_require.resolve(id, {
|
|
261
|
+
paths: [].concat(
|
|
262
|
+
global.__DTWO_PREPATHS__,
|
|
263
|
+
opts.paths || [],
|
|
264
|
+
process.cwd(),
|
|
265
|
+
global.__DTWO_PATHS__
|
|
266
|
+
).filter(Boolean)
|
|
267
|
+
}));
|
|
268
|
+
}
|
|
269
|
+
function tryResolveModule(path, opts = {}) {
|
|
270
|
+
try {
|
|
271
|
+
return resolveModule(path, opts);
|
|
272
|
+
} catch (error) {
|
|
273
|
+
if (error?.code !== "MODULE_NOT_FOUND") {
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return null;
|
|
278
|
+
}
|
|
279
|
+
function requireModule(id, opts = {}) {
|
|
280
|
+
const resolvedPath = resolveModule(id, opts);
|
|
281
|
+
if (opts.clearCache && !isNodeModules(id)) {
|
|
282
|
+
clearRequireCache(resolvedPath);
|
|
283
|
+
}
|
|
284
|
+
const requiredModule = _require(resolvedPath);
|
|
285
|
+
return requiredModule;
|
|
286
|
+
}
|
|
287
|
+
function importModule(id, opts = {}) {
|
|
288
|
+
const resolvedPath = resolveModule(id, opts);
|
|
289
|
+
if (opts.interopDefault !== false) {
|
|
290
|
+
return import(pathToFileURL(resolvedPath).href).then(interopDefault);
|
|
291
|
+
}
|
|
292
|
+
return import(pathToFileURL(resolvedPath).href);
|
|
293
|
+
}
|
|
294
|
+
function tryImportModule(id, opts = {}) {
|
|
295
|
+
try {
|
|
296
|
+
return importModule(id, opts).catch(() => void 0);
|
|
297
|
+
} catch {
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
function tryRequireModule(id, opts = {}) {
|
|
301
|
+
try {
|
|
302
|
+
return requireModule(id, opts);
|
|
303
|
+
} catch (e) {
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function isIgnored(pathname) {
|
|
308
|
+
const dtwo = tryUseDtwo();
|
|
309
|
+
if (!dtwo) {
|
|
310
|
+
return false;
|
|
311
|
+
}
|
|
312
|
+
if (!dtwo._ignore) {
|
|
313
|
+
dtwo._ignore = ignore(dtwo.options.ignoreOptions);
|
|
314
|
+
dtwo._ignore.add(dtwo.options.ignore);
|
|
315
|
+
const dtwoignoreFile = join(dtwo.options.rootDir, ".dtwoignore");
|
|
316
|
+
if (existsSync(dtwoignoreFile)) {
|
|
317
|
+
dtwo._ignore.add(readFileSync(dtwoignoreFile, "utf-8"));
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
const relativePath = relative(dtwo.options.rootDir, pathname);
|
|
321
|
+
if (relativePath.startsWith("..")) {
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
return !!(relativePath && dtwo._ignore.ignores(relativePath));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function resolvePath(path, opts = {}) {
|
|
328
|
+
const _path = path;
|
|
329
|
+
path = normalize(path);
|
|
330
|
+
if (isAbsolute(path) && existsSync(path) && !await isDirectory(path)) {
|
|
331
|
+
return path;
|
|
332
|
+
}
|
|
333
|
+
const dtwo = tryUseDtwo();
|
|
334
|
+
const cwd = opts.cwd || (dtwo ? dtwo.options.rootDir : process.cwd());
|
|
335
|
+
const extensions = opts.extensions || (dtwo ? dtwo.options.extensions : [".ts", ".mjs", ".cjs", ".json"]);
|
|
336
|
+
const modulesDir = dtwo ? dtwo.options.modulesDir : [];
|
|
337
|
+
path = resolveAlias(path);
|
|
338
|
+
if (!isAbsolute(path)) {
|
|
339
|
+
path = resolve(cwd, path);
|
|
340
|
+
}
|
|
341
|
+
let _isDir = false;
|
|
342
|
+
if (existsSync(path)) {
|
|
343
|
+
_isDir = await isDirectory(path);
|
|
344
|
+
if (!_isDir) {
|
|
345
|
+
return path;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
for (const ext of extensions) {
|
|
349
|
+
const pathWithExt = path + ext;
|
|
350
|
+
if (existsSync(pathWithExt)) {
|
|
351
|
+
return pathWithExt;
|
|
352
|
+
}
|
|
353
|
+
const pathWithIndex = join(path, "index" + ext);
|
|
354
|
+
if (_isDir && existsSync(pathWithIndex)) {
|
|
355
|
+
return pathWithIndex;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const resolveModulePath = tryResolveModule(_path, { paths: [cwd, ...modulesDir] });
|
|
359
|
+
if (resolveModulePath) {
|
|
360
|
+
return resolveModulePath;
|
|
361
|
+
}
|
|
362
|
+
return path;
|
|
363
|
+
}
|
|
364
|
+
async function findPath(paths, opts, pathType = "file") {
|
|
365
|
+
if (!Array.isArray(paths)) {
|
|
366
|
+
paths = [paths];
|
|
367
|
+
}
|
|
368
|
+
for (const path of paths) {
|
|
369
|
+
const rPath = await resolvePath(path, opts);
|
|
370
|
+
if (await existsSensitive(rPath)) {
|
|
371
|
+
const _isDir = await isDirectory(rPath);
|
|
372
|
+
if (!pathType || pathType === "file" && !_isDir || pathType === "dir" && _isDir) {
|
|
373
|
+
return rPath;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return null;
|
|
378
|
+
}
|
|
379
|
+
function resolveAlias(path, alias) {
|
|
380
|
+
if (!alias) {
|
|
381
|
+
alias = tryUseDtwo()?.options.alias || {};
|
|
382
|
+
}
|
|
383
|
+
return resolveAlias$1(path, alias);
|
|
384
|
+
}
|
|
385
|
+
function createResolver(base) {
|
|
386
|
+
if (!base) {
|
|
387
|
+
throw new Error("`base` argument is missing for createResolver(base)!");
|
|
388
|
+
}
|
|
389
|
+
base = base.toString();
|
|
390
|
+
if (base.startsWith("file://")) {
|
|
391
|
+
base = dirname(fileURLToPath(base));
|
|
392
|
+
}
|
|
393
|
+
return {
|
|
394
|
+
resolve: (...path) => resolve(base, ...path),
|
|
395
|
+
resolvePath: (path, opts) => resolvePath(path, { cwd: base, ...opts })
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
async function existsSensitive(path) {
|
|
399
|
+
if (!existsSync(path)) {
|
|
400
|
+
return false;
|
|
401
|
+
}
|
|
402
|
+
const dirFiles = await promises.readdir(dirname(path));
|
|
403
|
+
return dirFiles.includes(basename(path));
|
|
404
|
+
}
|
|
405
|
+
async function isDirectory(path) {
|
|
406
|
+
return (await promises.lstat(path)).isDirectory();
|
|
407
|
+
}
|
|
408
|
+
async function resolveFiles(path, pattern, opts = {}) {
|
|
409
|
+
const files = await globby(pattern, { cwd: path, followSymbolicLinks: opts.followSymbolicLinks ?? true });
|
|
410
|
+
return files.map((p) => resolve(path, p)).filter((p) => !isIgnored(p)).sort();
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
async function installModule(moduleToInstall, _inlineOptions, _dtwo) {
|
|
414
|
+
const dtwo = useDtwo();
|
|
415
|
+
const { dtwoModule, inlineOptions } = await normalizeModule(moduleToInstall, _inlineOptions);
|
|
416
|
+
await dtwoModule(inlineOptions, dtwo);
|
|
417
|
+
if (typeof moduleToInstall === "string") {
|
|
418
|
+
dtwo.options.build.transpile.push(moduleToInstall);
|
|
419
|
+
}
|
|
420
|
+
dtwo.options._installedModules = dtwo.options._installedModules || [];
|
|
421
|
+
dtwo.options._installedModules.push({
|
|
422
|
+
meta: await dtwoModule.getMeta?.(),
|
|
423
|
+
entryPath: typeof moduleToInstall === "string" ? resolveAlias(moduleToInstall) : void 0
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
async function normalizeModule(dtwoModule, inlineOptions) {
|
|
427
|
+
const dtwo = useDtwo();
|
|
428
|
+
if (typeof dtwoModule === "string") {
|
|
429
|
+
const _src = resolveModule(resolveAlias(dtwoModule), { paths: dtwo.options.modulesDir });
|
|
430
|
+
const isESM = _src.endsWith(".mjs");
|
|
431
|
+
try {
|
|
432
|
+
dtwoModule = isESM ? await importModule(_src) : requireModule(_src);
|
|
433
|
+
} catch (error) {
|
|
434
|
+
console.error(`Error while requiring module \`${dtwoModule}\`: ${error}`);
|
|
435
|
+
throw error;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (typeof dtwoModule !== "function") {
|
|
439
|
+
throw new TypeError("Dtwo module should be a function: " + dtwoModule);
|
|
440
|
+
}
|
|
441
|
+
return { dtwoModule, inlineOptions };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async function loadDtwoConfig(opts) {
|
|
445
|
+
globalThis.defineDtwoConfig = (c) => c;
|
|
446
|
+
const result = await loadConfig({
|
|
447
|
+
name: "dtwo",
|
|
448
|
+
configFile: "dtwo.config",
|
|
449
|
+
rcFile: ".dtworc",
|
|
450
|
+
extend: { extendKey: ["theme", "extends"] },
|
|
451
|
+
dotenv: true,
|
|
452
|
+
globalRc: true,
|
|
453
|
+
...opts
|
|
454
|
+
});
|
|
455
|
+
delete globalThis.defineDtwoConfig;
|
|
456
|
+
const { configFile, layers = [], cwd } = result;
|
|
457
|
+
const dtwoConfig = result.config;
|
|
458
|
+
dtwoConfig.rootDir = dtwoConfig.rootDir || cwd;
|
|
459
|
+
dtwoConfig._dtwoConfigFile = configFile;
|
|
460
|
+
dtwoConfig._dtwoConfigFiles = [configFile];
|
|
461
|
+
for (const layer of layers) {
|
|
462
|
+
layer.config = layer.config || {};
|
|
463
|
+
layer.config.rootDir = layer.config.rootDir ?? layer.cwd;
|
|
464
|
+
layer.config.srcDir = resolve(layer.config.rootDir, layer.config.srcDir);
|
|
465
|
+
}
|
|
466
|
+
const _layers = layers.filter((layer) => layer.configFile && !layer.configFile.endsWith(".dtworc"));
|
|
467
|
+
dtwoConfig._layers = _layers;
|
|
468
|
+
if (!_layers.length) {
|
|
469
|
+
_layers.push({
|
|
470
|
+
cwd,
|
|
471
|
+
config: {
|
|
472
|
+
rootDir: cwd,
|
|
473
|
+
srcDir: cwd
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
return await applyDefaults(DtwoConfigSchema, dtwoConfig);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
async function loadDtwo(opts) {
|
|
481
|
+
opts.cwd = opts.cwd || opts.rootDir;
|
|
482
|
+
opts.overrides = opts.overrides || opts.config || {};
|
|
483
|
+
const resolveOpts = { paths: opts.cwd };
|
|
484
|
+
opts.overrides.dev = !!opts.dev;
|
|
485
|
+
const nearestDtwoPkg = await Promise.all(["dtwo3", "dtwo", "dtwo-edge"].map((pkg2) => resolvePackageJSON(pkg2, { url: opts.cwd }).catch(() => null))).then((r) => r.filter(Boolean).sort((a, b) => b.length - a.length)[0]);
|
|
486
|
+
if (!nearestDtwoPkg) {
|
|
487
|
+
throw new Error(`Cannot find any dtwo version from ${opts.cwd}`);
|
|
488
|
+
}
|
|
489
|
+
const pkg = await readPackageJSON(nearestDtwoPkg);
|
|
490
|
+
const majorVersion = parseInt((pkg.version || "").split(".")[0]);
|
|
491
|
+
if (majorVersion === 3) {
|
|
492
|
+
const { loadDtwo: loadDtwo3 } = await importModule(pkg._name || pkg.name, resolveOpts);
|
|
493
|
+
const dtwo2 = await loadDtwo3(opts);
|
|
494
|
+
return dtwo2;
|
|
495
|
+
}
|
|
496
|
+
const { loadDtwo: loadDtwo2 } = await tryImportModule("dtwo-edge", resolveOpts) || await importModule("dtwo", resolveOpts);
|
|
497
|
+
const dtwo = await loadDtwo2({
|
|
498
|
+
rootDir: opts.cwd,
|
|
499
|
+
for: opts.dev ? "dev" : "build",
|
|
500
|
+
configOverrides: opts.overrides,
|
|
501
|
+
ready: opts.ready,
|
|
502
|
+
envConfig: opts.dotenv
|
|
503
|
+
});
|
|
504
|
+
return dtwo;
|
|
505
|
+
}
|
|
506
|
+
async function buildDtwo(dtwo) {
|
|
507
|
+
const resolveOpts = { paths: dtwo.options.rootDir };
|
|
508
|
+
if (dtwo.options._majorVersion === 3) {
|
|
509
|
+
const { build: build2 } = await tryImportModule("dtwo3", resolveOpts) || await importModule("dtwo", resolveOpts);
|
|
510
|
+
return build2(dtwo);
|
|
511
|
+
}
|
|
512
|
+
const { build } = await tryImportModule("dtwo-edge", resolveOpts) || await importModule("dtwo", resolveOpts);
|
|
513
|
+
return build(dtwo);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function addImports(imports) {
|
|
517
|
+
assertDtwoCompatibility({ bridge: true });
|
|
518
|
+
useDtwo().hook("imports:extend", (_imports) => {
|
|
519
|
+
_imports.push(...Array.isArray(imports) ? imports : [imports]);
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
function addImportsDir(dirs) {
|
|
523
|
+
assertDtwoCompatibility({ bridge: true });
|
|
524
|
+
useDtwo().hook("imports:dirs", (_dirs) => {
|
|
525
|
+
for (const dir of Array.isArray(dirs) ? dirs : [dirs]) {
|
|
526
|
+
_dirs.push(dir);
|
|
527
|
+
}
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
function addImportsSources(presets) {
|
|
531
|
+
assertDtwoCompatibility({ bridge: true });
|
|
532
|
+
useDtwo().hook("imports:sources", (_presets) => {
|
|
533
|
+
for (const preset of Array.isArray(presets) ? presets : [presets]) {
|
|
534
|
+
_presets.push(preset);
|
|
535
|
+
}
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function extendWebpackConfig(fn, options = {}) {
|
|
540
|
+
const dtwo = useDtwo();
|
|
541
|
+
if (options.dev === false && dtwo.options.dev) {
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
if (options.build === false && dtwo.options.build) {
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
dtwo.hook("webpack:config", (configs) => {
|
|
548
|
+
if (options.server !== false) {
|
|
549
|
+
const config = configs.find((i) => i.name === "server");
|
|
550
|
+
if (config) {
|
|
551
|
+
fn(config);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
if (options.client !== false) {
|
|
555
|
+
const config = configs.find((i) => i.name === "client");
|
|
556
|
+
if (config) {
|
|
557
|
+
fn(config);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
function extendWiteConfig(fn, options = {}) {
|
|
563
|
+
const dtwo = useDtwo();
|
|
564
|
+
if (options.dev === false && dtwo.options.dev) {
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
if (options.build === false && dtwo.options.build) {
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
if (options.server !== false && options.client !== false) {
|
|
571
|
+
return dtwo.hook("wite:extend", ({ config }) => fn(config));
|
|
572
|
+
}
|
|
573
|
+
dtwo.hook("wite:extendConfig", (config, { isClient, isServer }) => {
|
|
574
|
+
if (options.server !== false && isServer) {
|
|
575
|
+
return fn(config);
|
|
576
|
+
}
|
|
577
|
+
if (options.client !== false && isClient) {
|
|
578
|
+
return fn(config);
|
|
579
|
+
}
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
function addWebpackPlugin(plugin, options) {
|
|
583
|
+
extendWebpackConfig((config) => {
|
|
584
|
+
config.plugins = config.plugins || [];
|
|
585
|
+
if (Array.isArray(plugin)) {
|
|
586
|
+
config.plugins.push(...plugin);
|
|
587
|
+
} else {
|
|
588
|
+
config.plugins.push(plugin);
|
|
589
|
+
}
|
|
590
|
+
}, options);
|
|
591
|
+
}
|
|
592
|
+
function addWitePlugin(plugin, options) {
|
|
593
|
+
extendWiteConfig((config) => {
|
|
594
|
+
config.plugins = config.plugins || [];
|
|
595
|
+
if (Array.isArray(plugin)) {
|
|
596
|
+
config.plugins.push(...plugin);
|
|
597
|
+
} else {
|
|
598
|
+
config.plugins.push(plugin);
|
|
599
|
+
}
|
|
600
|
+
}, options);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
async function addComponentsDir(dir) {
|
|
604
|
+
const dtwo = useDtwo();
|
|
605
|
+
await assertDtwoCompatibility({ dtwo: ">=2.13" }, dtwo);
|
|
606
|
+
dtwo.options.components = dtwo.options.components || [];
|
|
607
|
+
dtwo.hook("components:dirs", (dirs) => {
|
|
608
|
+
dirs.push(dir);
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
async function addComponent(opts) {
|
|
612
|
+
const dtwo = useDtwo();
|
|
613
|
+
await assertDtwoCompatibility({ dtwo: ">=2.13" }, dtwo);
|
|
614
|
+
dtwo.options.components = dtwo.options.components || [];
|
|
615
|
+
const component = {
|
|
616
|
+
export: opts.export || "default",
|
|
617
|
+
chunkName: "components/" + kebabCase(opts.name),
|
|
618
|
+
global: opts.global ?? false,
|
|
619
|
+
kebabName: kebabCase(opts.name || ""),
|
|
620
|
+
pascalName: pascalCase(opts.name || ""),
|
|
621
|
+
prefetch: false,
|
|
622
|
+
preload: false,
|
|
623
|
+
mode: "all",
|
|
624
|
+
shortPath: opts.filePath,
|
|
625
|
+
...opts
|
|
626
|
+
};
|
|
627
|
+
dtwo.hook("components:extend", (components) => {
|
|
628
|
+
const existingComponent = components.find((c) => (c.pascalName === component.pascalName || c.kebabName === component.kebabName) && c.mode === component.mode);
|
|
629
|
+
if (existingComponent) {
|
|
630
|
+
const name = existingComponent.pascalName || existingComponent.kebabName;
|
|
631
|
+
console.warn(`Overriding ${name} component.`);
|
|
632
|
+
Object.assign(existingComponent, component);
|
|
633
|
+
} else {
|
|
634
|
+
components.push(component);
|
|
635
|
+
}
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
function normalizeHandlerMethod(handler) {
|
|
640
|
+
const [, method = void 0] = handler.handler.match(/\.(get|head|patch|post|put|delete|connect|options|trace)(\.\w+)*$/) || [];
|
|
641
|
+
return {
|
|
642
|
+
method,
|
|
643
|
+
...handler,
|
|
644
|
+
handler: normalize(handler.handler)
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
function addServerHandler(handler) {
|
|
648
|
+
useDtwo().options.serverHandlers.push(normalizeHandlerMethod(handler));
|
|
649
|
+
}
|
|
650
|
+
function addDevServerHandler(handler) {
|
|
651
|
+
useDtwo().options.devServerHandlers.push(handler);
|
|
652
|
+
}
|
|
653
|
+
function addServerPlugin(plugin) {
|
|
654
|
+
const dtwo = useDtwo();
|
|
655
|
+
dtwo.options.hole.plugins = dtwo.options.hole.plugins || [];
|
|
656
|
+
dtwo.options.hole.plugins.push(normalize(plugin));
|
|
657
|
+
}
|
|
658
|
+
function addPrerenderRoutes(routes) {
|
|
659
|
+
const dtwo = useDtwo();
|
|
660
|
+
if (!Array.isArray(routes)) {
|
|
661
|
+
routes = [routes];
|
|
662
|
+
}
|
|
663
|
+
routes = routes.filter(Boolean);
|
|
664
|
+
if (!routes.length) {
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
dtwo.hook("prerender:routes", (ctx) => {
|
|
668
|
+
for (const route of routes) {
|
|
669
|
+
ctx.routes.add(route);
|
|
670
|
+
}
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
function useHole() {
|
|
674
|
+
const dtwo = useDtwo();
|
|
675
|
+
if (!dtwo._hole) {
|
|
676
|
+
throw new Error("Hole is not initialized yet. You can call `useHole()` only after `ready` hook.");
|
|
677
|
+
}
|
|
678
|
+
return dtwo._hole;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
function addTemplate(_template) {
|
|
682
|
+
const dtwo = useDtwo();
|
|
683
|
+
const template = normalizeTemplate(_template);
|
|
684
|
+
dtwo.options.build.templates = dtwo.options.build.templates.filter((p) => normalizeTemplate(p).filename !== template.filename);
|
|
685
|
+
dtwo.options.build.templates.push(template);
|
|
686
|
+
return template;
|
|
687
|
+
}
|
|
688
|
+
function normalizeTemplate(template) {
|
|
689
|
+
if (!template) {
|
|
690
|
+
throw new Error("Invalid template: " + JSON.stringify(template));
|
|
691
|
+
}
|
|
692
|
+
if (typeof template === "string") {
|
|
693
|
+
template = { src: template };
|
|
694
|
+
} else {
|
|
695
|
+
template = { ...template };
|
|
696
|
+
}
|
|
697
|
+
if (template.src) {
|
|
698
|
+
if (!existsSync(template.src)) {
|
|
699
|
+
throw new Error("Template not found: " + template.src);
|
|
700
|
+
}
|
|
701
|
+
if (!template.filename) {
|
|
702
|
+
const srcPath = parse(template.src);
|
|
703
|
+
template.filename = template.fileName || `${basename(srcPath.dir)}.${srcPath.name}.${hash(template.src)}${srcPath.ext}`;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
if (!template.src && !template.getContents) {
|
|
707
|
+
throw new Error("Invalid template. Either getContents or src options should be provided: " + JSON.stringify(template));
|
|
708
|
+
}
|
|
709
|
+
if (!template.filename) {
|
|
710
|
+
throw new Error("Invalid template. Either filename should be provided: " + JSON.stringify(template));
|
|
711
|
+
}
|
|
712
|
+
if (template.filename.endsWith(".d.ts")) {
|
|
713
|
+
template.write = true;
|
|
714
|
+
}
|
|
715
|
+
if (!template.dst) {
|
|
716
|
+
const dtwo = useDtwo();
|
|
717
|
+
template.dst = resolve(dtwo.options.buildDir, template.filename);
|
|
718
|
+
}
|
|
719
|
+
return template;
|
|
720
|
+
}
|
|
721
|
+
function updateTemplates(options) {
|
|
722
|
+
return useDtwo().hooks.callHook("builder:generateApp", options);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function addLayout(template, name) {
|
|
726
|
+
const dtwo = useDtwo();
|
|
727
|
+
const { filename, src } = addTemplate(template);
|
|
728
|
+
const layoutName = kebabCase(name || parse(filename).name).replace(/["']/g, "");
|
|
729
|
+
if (isDtwo2(dtwo)) {
|
|
730
|
+
const layout = dtwo.options.layouts[layoutName];
|
|
731
|
+
if (layout) {
|
|
732
|
+
return logger.warn(
|
|
733
|
+
`Not overriding \`${layoutName}\` (provided by \`${layout}\`) with \`${src || filename}\`.`
|
|
734
|
+
);
|
|
735
|
+
}
|
|
736
|
+
dtwo.options.layouts[layoutName] = `./${filename}`;
|
|
737
|
+
if (name === "error") {
|
|
738
|
+
this.addErrorLayout(filename);
|
|
739
|
+
}
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
dtwo.hook("app:templates", (app) => {
|
|
743
|
+
if (layoutName in app.layouts) {
|
|
744
|
+
const relativePath = relative(dtwo.options.srcDir, app.layouts[layoutName].file);
|
|
745
|
+
return logger.warn(
|
|
746
|
+
`Not overriding \`${layoutName}\` (provided by \`~/${relativePath}\`) with \`${src || filename}\`.`
|
|
747
|
+
);
|
|
748
|
+
}
|
|
749
|
+
app.layouts[layoutName] = {
|
|
750
|
+
file: join("#build", filename),
|
|
751
|
+
name: layoutName
|
|
752
|
+
};
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
function extendPages(cb) {
|
|
757
|
+
const dtwo = useDtwo();
|
|
758
|
+
if (isDtwo2(dtwo)) {
|
|
759
|
+
dtwo.hook("build:extendRoutes", cb);
|
|
760
|
+
} else {
|
|
761
|
+
dtwo.hook("pages:extend", cb);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
function normalizePlugin(plugin) {
|
|
766
|
+
if (typeof plugin === "string") {
|
|
767
|
+
plugin = { src: plugin };
|
|
768
|
+
} else {
|
|
769
|
+
plugin = { ...plugin };
|
|
770
|
+
}
|
|
771
|
+
if (!plugin.src) {
|
|
772
|
+
throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
|
|
773
|
+
}
|
|
774
|
+
plugin.src = normalize(resolveAlias(plugin.src));
|
|
775
|
+
if (plugin.ssr) {
|
|
776
|
+
plugin.mode = "server";
|
|
777
|
+
}
|
|
778
|
+
if (!plugin.mode) {
|
|
779
|
+
const [, mode = "all"] = plugin.src.match(/\.(server|client)(\.\w+)*$/) || [];
|
|
780
|
+
plugin.mode = mode;
|
|
781
|
+
}
|
|
782
|
+
return plugin;
|
|
783
|
+
}
|
|
784
|
+
function addPlugin(_plugin, opts = {}) {
|
|
785
|
+
const dtwo = useDtwo();
|
|
786
|
+
const plugin = normalizePlugin(_plugin);
|
|
787
|
+
dtwo.options.plugins = dtwo.options.plugins.filter((p) => normalizePlugin(p).src !== plugin.src);
|
|
788
|
+
dtwo.options.plugins[opts.append ? "push" : "unshift"](plugin);
|
|
789
|
+
return plugin;
|
|
790
|
+
}
|
|
791
|
+
function addPluginTemplate(plugin, opts = {}) {
|
|
792
|
+
const normalizedPlugin = typeof plugin === "string" ? { src: plugin } : { ...plugin, src: addTemplate(plugin).dst };
|
|
793
|
+
return addPlugin(normalizedPlugin, opts);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
export { addComponent, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addServerHandler, addServerPlugin, addTemplate, addWebpackPlugin, addWitePlugin, assertDtwoCompatibility, buildDtwo, checkDtwoCompatibility, clearRequireCache, compileTemplate, createResolver, defineDtwoModule, dtwoCtx, extendPages, extendWebpackConfig, extendWiteConfig, findPath, getDtwoVersion, getRequireCacheItem, hasDtwoCompatibility, importModule, installModule, isDtwo2, isDtwo3, isIgnored, isNodeModules, loadDtwo, loadDtwoConfig, logger, normalizePlugin, normalizeTemplate, requireModule, requireModulePkg, resolveAlias, resolveFiles, resolveModule, resolvePath, scanRequireTree, templateUtils, tryImportModule, tryRequireModule, tryResolveModule, tryUseDtwo, updateTemplates, useDtwo, useHole, useLogger };
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dtwo/kit",
|
|
3
|
+
"version": "3.0.0-rc.13",
|
|
4
|
+
"repository": "d2js/framework",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.mjs",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"dependencies": {
|
|
13
|
+
"@dtwo/schema": "3.0.0-rc.13",
|
|
14
|
+
"c12": "^1.0.1",
|
|
15
|
+
"consola": "^2.15.3",
|
|
16
|
+
"defu": "^6.1.1",
|
|
17
|
+
"globby": "^13.1.2",
|
|
18
|
+
"hash-sum": "^2.0.0",
|
|
19
|
+
"ignore": "^5.2.0",
|
|
20
|
+
"jiti": "^1.16.0",
|
|
21
|
+
"knitwork": "^1.0.0",
|
|
22
|
+
"lodash.template": "^4.5.0",
|
|
23
|
+
"mlly": "^1.0.0",
|
|
24
|
+
"pathe": "^1.0.0",
|
|
25
|
+
"pkg-types": "^1.0.1",
|
|
26
|
+
"scule": "^1.0.0",
|
|
27
|
+
"semver": "^7.3.8",
|
|
28
|
+
"unctx": "^2.1.0",
|
|
29
|
+
"unimport": "^1.0.0",
|
|
30
|
+
"untyped": "^1.0.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@types/lodash.template": "^4",
|
|
34
|
+
"@types/semver": "^7",
|
|
35
|
+
"unbuild": "latest"
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": "^14.16.0 || ^16.10.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {}
|
|
41
|
+
}
|