content
stringlengths 28
1.34M
|
---|
import { BrandingOptions, StaticAssetDefinition, StaticAssetExtension } from './types';
/**
* @description
* A helper function to simplify the process of setting custom branding images.
*
* @example
* ```ts
* compileUiExtensions({
* outputPath: path.join(__dirname, '../admin-ui'),
* extensions: [
* setBranding({
* // This is used as the branding in the top-left above the navigation
* smallLogoPath: path.join(__dirname, 'images/my-logo-sm.png'),
* // This is used on the login page
* largeLogoPath: path.join(__dirname, 'images/my-logo-lg.png'),
* faviconPath: path.join(__dirname, 'images/my-favicon.ico'),
* }),
* ],
* });
* ```
*
* @docsCategory UiDevkit
* @docsPage helpers
*/
export function setBranding(options: BrandingOptions): StaticAssetExtension {
const staticAssets: StaticAssetDefinition[] = [];
if (options.smallLogoPath) {
staticAssets.push({
path: options.smallLogoPath,
rename: 'logo-top.webp',
});
}
if (options.largeLogoPath) {
staticAssets.push({
path: options.largeLogoPath,
rename: 'logo-login.webp',
});
}
if (options.faviconPath) {
staticAssets.push({
path: options.faviconPath,
rename: 'favicon.ico',
});
}
return { staticAssets };
}
|
export * from './compile';
export * from './helpers';
export * from './types';
|
/* eslint-disable no-console */
import { notNullOrUndefined } from '@vendure/common/lib/shared-utils';
import * as fs from 'fs-extra';
import { globSync } from 'glob';
import * as path from 'path';
import {
EXTENSION_ROUTES_FILE,
GLOBAL_STYLES_OUTPUT_DIR,
MODULES_OUTPUT_DIR,
SHARED_EXTENSIONS_FILE,
} from './constants';
import { getAllTranslationFiles, mergeExtensionTranslations } from './translations';
import {
AdminUiExtension,
AdminUiExtensionLazyModule,
AdminUiExtensionSharedModule,
AdminUiExtensionWithId,
Extension,
GlobalStylesExtension,
SassVariableOverridesExtension,
StaticAssetExtension,
} from './types';
import {
copyStaticAsset,
copyUiDevkit,
isAdminUiExtension,
isGlobalStylesExtension,
isSassVariableOverridesExtension,
isStaticAssetExtension,
isTranslationExtension,
normalizeExtensions,
} from './utils';
export async function setupScaffold(outputPath: string, extensions: Extension[]) {
deleteExistingExtensionModules(outputPath);
const adminUiExtensions = extensions.filter((e): e is AdminUiExtension => isAdminUiExtension(e));
const normalizedExtensions = normalizeExtensions(adminUiExtensions);
const modulePathMapping = generateModulePathMapping(normalizedExtensions);
copyAdminUiSource(outputPath, modulePathMapping);
await copyExtensionModules(outputPath, normalizedExtensions);
const staticAssetExtensions = extensions.filter(isStaticAssetExtension);
await copyStaticAssets(outputPath, staticAssetExtensions);
const globalStyleExtensions = extensions.filter(isGlobalStylesExtension);
const sassVariableOverridesExtension = extensions.find(isSassVariableOverridesExtension);
await addGlobalStyles(outputPath, globalStyleExtensions, sassVariableOverridesExtension);
const allTranslationFiles = getAllTranslationFiles(extensions.filter(isTranslationExtension));
await mergeExtensionTranslations(outputPath, allTranslationFiles);
copyUiDevkit(outputPath);
}
/**
* Deletes the contents of the /modules directory, which contains the plugin
* extension modules copied over during the last compilation.
*/
function deleteExistingExtensionModules(outputPath: string) {
fs.removeSync(path.join(outputPath, MODULES_OUTPUT_DIR));
}
/**
* Generates a module path mapping object for all extensions with a "pathAlias"
* property declared (if any).
*/
function generateModulePathMapping(extensions: AdminUiExtensionWithId[]) {
const extensionsWithAlias = extensions.filter(e => e.pathAlias);
if (extensionsWithAlias.length === 0) {
return undefined;
}
return extensionsWithAlias.reduce((acc, e) => {
// for imports from the index file if there is one
acc[e.pathAlias as string] = [`src/extensions/${e.id}`];
// direct access to files / deep imports
acc[`${e.pathAlias as string}/*`] = [`src/extensions/${e.id}/*`];
return acc;
}, {} as Record<string, string[]>);
}
/**
* Copies all files from the extensionPaths of the configured extensions into the
* admin-ui source tree.
*/
async function copyExtensionModules(outputPath: string, extensions: AdminUiExtensionWithId[]) {
const adminUiExtensions = extensions.filter(isAdminUiExtension);
const extensionRoutesSource = generateLazyExtensionRoutes(adminUiExtensions);
fs.writeFileSync(path.join(outputPath, EXTENSION_ROUTES_FILE), extensionRoutesSource, 'utf8');
const sharedExtensionModulesSource = generateSharedExtensionModule(extensions);
fs.writeFileSync(path.join(outputPath, SHARED_EXTENSIONS_FILE), sharedExtensionModulesSource, 'utf8');
for (const extension of adminUiExtensions) {
if (!extension.extensionPath) {
continue;
}
const dest = path.join(outputPath, MODULES_OUTPUT_DIR, extension.id);
if (!extension.exclude) {
fs.copySync(extension.extensionPath, dest);
continue;
}
const exclude =
extension.exclude?.map(e => globSync(path.join(extension.extensionPath, e))).flatMap(e => e) ??
[];
fs.copySync(extension.extensionPath, dest, {
filter: name => name === extension.extensionPath || exclude.every(e => e !== name),
});
}
}
async function copyStaticAssets(outputPath: string, extensions: Array<Partial<StaticAssetExtension>>) {
for (const extension of extensions) {
if (Array.isArray(extension.staticAssets)) {
for (const asset of extension.staticAssets) {
await copyStaticAsset(outputPath, asset);
}
}
}
}
async function addGlobalStyles(
outputPath: string,
globalStylesExtensions: GlobalStylesExtension[],
sassVariableOverridesExtension?: SassVariableOverridesExtension,
) {
const globalStylesDir = path.join(outputPath, 'src', GLOBAL_STYLES_OUTPUT_DIR);
await fs.remove(globalStylesDir);
await fs.ensureDir(globalStylesDir);
const imports: string[] = [];
for (const extension of globalStylesExtensions) {
const styleFiles = Array.isArray(extension.globalStyles)
? extension.globalStyles
: [extension.globalStyles];
for (const styleFile of styleFiles) {
await copyGlobalStyleFile(outputPath, styleFile);
imports.push(path.basename(styleFile, path.extname(styleFile)));
}
}
let overridesImport = '';
if (sassVariableOverridesExtension) {
const overridesFile = sassVariableOverridesExtension.sassVariableOverrides;
await copyGlobalStyleFile(outputPath, overridesFile);
overridesImport = `@import "./${GLOBAL_STYLES_OUTPUT_DIR}/${path.basename(
overridesFile,
path.extname(overridesFile),
)}";\n`;
}
const globalStylesSource =
overridesImport +
'@import "./styles/styles";\n' +
imports.map(file => `@import "./${GLOBAL_STYLES_OUTPUT_DIR}/${file}";`).join('\n');
const globalStylesFile = path.join(outputPath, 'src', 'global-styles.scss');
await fs.writeFile(globalStylesFile, globalStylesSource, 'utf-8');
}
export async function copyGlobalStyleFile(outputPath: string, stylePath: string) {
const globalStylesDir = path.join(outputPath, 'src', GLOBAL_STYLES_OUTPUT_DIR);
const fileBasename = path.basename(stylePath);
const styleOutputPath = path.join(globalStylesDir, fileBasename);
await fs.copyFile(stylePath, styleOutputPath);
}
function generateLazyExtensionRoutes(extensions: AdminUiExtensionWithId[]): string {
const routes: string[] = [];
for (const extension of extensions) {
for (const module of extension.ngModules ?? []) {
if (module.type === 'lazy') {
routes.push(` {
path: 'extensions/${module.route}',
loadChildren: () => import('${getModuleFilePath(extension.id, module)}').then(m => m.${
module.ngModuleName
}),
}`);
}
}
for (const route of extension.routes ?? []) {
const prefix = route.prefix === '' ? '' : `${route.prefix ?? 'extensions'}/`;
routes.push(` {
path: '${prefix}${route.route}',
loadChildren: () => import('./extensions/${extension.id}/${path.basename(route.filePath, '.ts')}'),
}`);
}
}
return `export const extensionRoutes = [${routes.join(',\n')}];\n`;
}
function generateSharedExtensionModule(extensions: AdminUiExtensionWithId[]) {
const adminUiExtensions = extensions.filter(isAdminUiExtension);
const moduleImports = adminUiExtensions
.map(e =>
e.ngModules
?.filter(m => m.type === 'shared')
.map(m => `import { ${m.ngModuleName} } from '${getModuleFilePath(e.id, m)}';\n`)
.join(''),
)
.filter(val => !!val)
.join('');
const providerImports = adminUiExtensions
.map((m, i) =>
(m.providers ?? [])
.map(
(f, j) =>
`import SharedProviders_${i}_${j} from './extensions/${m.id}/${path.basename(
f,
'.ts',
)}';\n`,
)
.join(''),
)
.filter(val => !!val)
.join('');
const modules = adminUiExtensions
.map(e =>
e.ngModules
?.filter(m => m.type === 'shared')
.map(m => m.ngModuleName)
.join(', '),
)
.filter(val => !!val)
.join(', ');
const providers = adminUiExtensions
.filter(notNullOrUndefined)
.map((m, i) => (m.providers ?? []).map((f, j) => `...SharedProviders_${i}_${j}`).join(', '))
.filter(val => !!val)
.join(', ');
return `import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
${moduleImports}
${providerImports}
@NgModule({
imports: [CommonModule, ${modules}],
providers: [${providers}],
})
export class SharedExtensionsModule {}
`;
}
function getModuleFilePath(
id: string,
module: AdminUiExtensionLazyModule | AdminUiExtensionSharedModule,
): string {
return `./extensions/${id}/${path.basename(module.ngModuleFileName, '.ts')}`;
}
/**
* Copies the Admin UI sources & static assets to the outputPath if it does not already
* exist there.
*/
function copyAdminUiSource(outputPath: string, modulePathMapping: Record<string, string[]> | undefined) {
const tsconfigFilePath = path.join(outputPath, 'tsconfig.json');
const indexFilePath = path.join(outputPath, '/src/index.html');
if (fs.existsSync(tsconfigFilePath) && fs.existsSync(indexFilePath)) {
configureModulePathMapping(tsconfigFilePath, modulePathMapping);
return;
}
const scaffoldDir = path.join(__dirname, '../scaffold');
const adminUiSrc = path.join(require.resolve('@vendure/admin-ui'), '../../static');
if (!fs.existsSync(scaffoldDir)) {
throw new Error(`Could not find the admin ui scaffold files at ${scaffoldDir}`);
}
if (!fs.existsSync(adminUiSrc)) {
throw new Error(`Could not find the @vendure/admin-ui sources. Looked in ${adminUiSrc}`);
}
// copy scaffold
fs.removeSync(outputPath);
fs.ensureDirSync(outputPath);
fs.copySync(scaffoldDir, outputPath);
configureModulePathMapping(tsconfigFilePath, modulePathMapping);
// copy source files from admin-ui package
const outputSrc = path.join(outputPath, 'src');
fs.ensureDirSync(outputSrc);
fs.copySync(adminUiSrc, outputSrc);
}
export async function setBaseHref(outputPath: string, baseHref: string) {
const angularJsonFilePath = path.join(outputPath, '/angular.json');
const angularJson = await fs.readJSON(angularJsonFilePath, 'utf-8');
angularJson.projects['vendure-admin'].architect.build.options.baseHref = baseHref;
await fs.writeJSON(angularJsonFilePath, angularJson, { spaces: 2 });
}
/**
* Adds module path mapping to the bundled tsconfig.json file if defined as a UI extension.
*/
function configureModulePathMapping(
tsconfigFilePath: string,
modulePathMapping: Record<string, string[]> | undefined,
) {
if (!modulePathMapping) {
return;
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const tsconfig = require(tsconfigFilePath);
tsconfig.compilerOptions.paths = modulePathMapping;
fs.writeFileSync(tsconfigFilePath, JSON.stringify(tsconfig, null, 2));
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import * as fs from 'fs-extra';
import { globSync } from 'glob';
import * as path from 'path';
import { Extension, TranslationExtension, Translations } from './types';
import { logger } from './utils';
/**
* Given an array of extensions, returns a map of languageCode to all files specified by the
* configured globs.
*/
export function getAllTranslationFiles(extensions: TranslationExtension[]): {
[languageCode in LanguageCode]?: string[];
} {
// First collect all globs by language
const allTranslationsWithGlobs: { [languageCode in LanguageCode]?: string[] } = {};
for (const extension of extensions) {
for (const [languageCode, globPattern] of Object.entries(extension.translations || {})) {
const code = languageCode as LanguageCode;
if (globPattern) {
if (!allTranslationsWithGlobs[code]) {
allTranslationsWithGlobs[code] = [globPattern];
} else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
allTranslationsWithGlobs[code]!.push(globPattern);
}
}
}
}
const allTranslationsWithFiles: { [languageCode in LanguageCode]?: string[] } = {};
for (const [languageCode, globs] of Object.entries(allTranslationsWithGlobs)) {
const code = languageCode as LanguageCode;
allTranslationsWithFiles[code] = [];
if (!globs) {
continue;
}
for (const pattern of globs) {
const files = globSync(pattern);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
allTranslationsWithFiles[code]!.push(...files);
}
}
return allTranslationsWithFiles;
}
export async function mergeExtensionTranslations(
outputPath: string,
translationFiles: { [languageCode in LanguageCode]?: string[] },
) {
// Now merge them into the final language-speicific json files
const i18nMessagesDir = path.join(outputPath, 'src/i18n-messages');
for (const [languageCode, files] of Object.entries(translationFiles)) {
if (!files) {
continue;
}
const translationFile = path.join(i18nMessagesDir, `${languageCode}.json`);
const translationBackupFile = path.join(i18nMessagesDir, `${languageCode}.json.bak`);
if (fs.existsSync(translationBackupFile)) {
// restore the original translations from the backup
await fs.copy(translationBackupFile, translationFile);
}
let translations: any = {};
if (fs.existsSync(translationFile)) {
// create a backup of the original (unextended) translations
await fs.copy(translationFile, translationBackupFile);
try {
translations = await fs.readJson(translationFile);
} catch (e: any) {
logger.error(`Could not load translation file: ${translationFile}`);
logger.error(e);
}
}
for (const file of files) {
try {
const contents = await fs.readJson(file);
translations = mergeTranslations(translations, contents);
} catch (e: any) {
logger.error(`Could not load translation file: ${translationFile}`);
logger.error(e);
}
}
// write the final translation files to disk
const sortedTranslations = sortTranslationKeys(translations);
await fs.writeFile(translationFile, JSON.stringify(sortedTranslations, null, 2), 'utf8');
}
}
/**
* Sorts the contents of the translation files so the sections & keys are alphabetical.
*/
function sortTranslationKeys(translations: Translations): Translations {
const result: Translations = {};
const sections = Object.keys(translations).sort();
for (const section of sections) {
const sortedTokens = Object.entries(translations[section])
.sort(([keyA], [keyB]) => (keyA < keyB ? -1 : 1))
.reduce((output, [key, val]) => ({ ...output, [key]: val }), {});
result[section] = sortedTokens;
}
return result;
}
/**
* Merges the second set of translations into the first, returning a new translations
* object.
*/
function mergeTranslations(t1: Translations, t2: Translations): Translations {
const result = { ...t1 };
for (const [section, translations] of Object.entries(t2)) {
result[section] = {
...t1[section],
...translations,
};
}
return result;
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
export type Extension =
| AdminUiExtension
| TranslationExtension
| StaticAssetExtension
| GlobalStylesExtension
| SassVariableOverridesExtension;
/**
* @description
* Defines extensions to the Admin UI translations. Can be used as a stand-alone extension definition which only adds translations
* without adding new UI functionality, or as part of a full {@link AdminUiExtension}.
*
* @docsCategory UiDevkit
* @docsPage AdminUiExtension
*/
export interface TranslationExtension {
/**
* @description
* Optional object defining any translation files for the Admin UI. The value should be an object with
* the key as a 2-character [ISO 639-1 language code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes),
* and the value being a [glob](https://github.com/isaacs/node-glob) for any relevant
* translation files in JSON format.
*
* @example
* ```ts
* translations: {
* en: path.join(__dirname, 'translations/*.en.json'),
* de: path.join(__dirname, 'translations/*.de.json'),
* }
* ```
*/
translations: { [languageCode in LanguageCode]?: string };
}
/**
* @description
* Defines extensions which copy static assets to the custom Admin UI application source asset directory.
*
* @docsCategory UiDevkit
* @docsPage AdminUiExtension
*/
export interface StaticAssetExtension {
/**
* @description
* Optional array of paths to static assets which will be copied over to the Admin UI app's `/static`
* directory.
*/
staticAssets: StaticAssetDefinition[];
}
/**
* @description
* Defines extensions which add global styles to the custom Admin UI application.
*
* @docsCategory UiDevkit
* @docsPage AdminUiExtension
*/
export interface GlobalStylesExtension {
/**
* @description
* Specifies a path (or array of paths) to global style files (css or Sass) which will be
* incorporated into the Admin UI app global stylesheet.
*/
globalStyles: string[] | string;
}
/**
* @description
* Defines an extension which allows overriding Clarity Design System's Sass variables used in styles on the Admin UI.
*
* @docsCategory UiDevkit
* @docsPage AdminUiExtension
*/
export interface SassVariableOverridesExtension {
/**
* @description
* Specifies a path to a Sass style file containing variable declarations, which will take precedence over
* default values defined in Clarity.
*/
sassVariableOverrides: string;
}
/**
* @description
* Defines a route which will be added to the Admin UI application.
*
* @docsCategory UiDevkit
* @docsPage AdminUiExtension
*/
export interface UiExtensionRouteDefinition {
/**
* @description
* The name of the route. This will be used as the path in the URL.
*/
route: string;
/**
* @description
* The path to the file which exports an array of Angular route definitions.
*/
filePath: string;
/**
* @description
* All extensions will be mounted under the `/extensions/` route. This option allows you to specify a
* custom prefix rather than `/extensions/`. For example, setting this to `custom` would cause the extension
* to be mounted at `/custom/<route>` instead.
*
* A common use case for this is to mount the extension at the root of the Admin UI, by setting this to an empty string.
* This is useful when the extension is intended to replace the default Admin UI, rather than extend it.
*
* @since 2.2.0
*/
prefix?: string;
}
/**
* @description
* Defines extensions to the Admin UI application by specifying additional
* Angular [NgModules](https://angular.io/guide/ngmodules) which are compiled
* into the application.
*
* See [Extending the Admin UI](/guides/extending-the-admin-ui/getting-started/) for
* detailed instructions.
*
* @docsCategory UiDevkit
* @docsPage AdminUiExtension
* @docsWeight 0
*/
export interface AdminUiExtension
extends Partial<TranslationExtension>,
Partial<StaticAssetExtension>,
Partial<GlobalStylesExtension> {
/**
* @description
* An optional ID for the extension module. Only used internally for generating
* import paths to your module. If not specified, a unique hash will be used as the id.
*/
id?: string;
/**
* @description
* The path to the directory containing the extension module(s). The entire contents of this directory
* will be copied into the Admin UI app, including all TypeScript source files, html templates,
* scss style sheets etc.
*/
extensionPath: string;
/**
* @description
* One or more Angular modules which extend the default Admin UI.
*
* @deprecated use `routes` instead of lazy modules, and `providers` instead of shared modules in combination
* with Angular standalone components.
*/
ngModules?: Array<AdminUiExtensionSharedModule | AdminUiExtensionLazyModule>;
/**
* @description
* Defines the paths to a file that exports an array of shared providers such as nav menu items, custom form inputs,
* custom detail components, action bar items, custom history entry components.
*/
providers?: string[];
/**
* @description
* Defines routes that will be lazy-loaded at the `/extensions/` route. The filePath should point to a file
* relative to the `extensionPath` which exports an array of Angular route definitions.
*/
routes?: UiExtensionRouteDefinition[];
/**
* @description
* An optional alias for the module so it can be referenced by other UI extension modules.
*
* By default, Angular modules declared in an AdminUiExtension do not have access to code outside the directory
* defined by the `extensionPath`. A scenario in which that can be useful though is in a monorepo codebase where
* a common NgModule is shared across different plugins, each defined in its own package. An example can be found
* below - note that the main `tsconfig.json` also maps the target module but using a path relative to the project's
* root folder. The UI module is not part of the main TypeScript build task as explained in
* [Extending the Admin UI](https://www.vendure.io/docs/plugins/extending-the-admin-ui/) but having `paths`
* properly configured helps with usual IDE code editing features such as code completion and quick navigation, as
* well as linting.
*
* @example
* ```ts title="packages/common-ui-module/src/ui/ui-shared.module.ts"
* import { NgModule } from '\@angular/core';
* import { SharedModule } from '\@vendure/admin-ui/core';
* import { CommonUiComponent } from './components/common-ui/common-ui.component';
*
* export { CommonUiComponent };
*
* \@NgModule({
* imports: [SharedModule],
* exports: [CommonUiComponent],
* declarations: [CommonUiComponent],
* })
* export class CommonSharedUiModule {}
* ```
*
* ```ts title="packages/common-ui-module/src/index.ts"
* import path from 'path';
*
* import { AdminUiExtension } from '\@vendure/ui-devkit/compiler';
*
* export const uiExtensions: AdminUiExtension = {
* // highlight-next-line
* pathAlias: '\@common-ui-module', // this is the important part
* extensionPath: path.join(__dirname, 'ui'),
* ngModules: [
* {
* type: 'shared' as const,
* ngModuleFileName: 'ui-shared.module.ts',
* ngModuleName: 'CommonSharedUiModule',
* },
* ],
* };
* ```
*
* ```json title="tsconfig.json"
* {
* "compilerOptions": {
* "baseUrl": ".",
* "paths": {
* // highlight-next-line
* "\@common-ui-module/*": ["packages/common-ui-module/src/ui/*"]
* }
* }
* }
* ```
*
* ```ts title="packages/sample-plugin/src/ui/ui-extension.module.ts"
* import { NgModule } from '\@angular/core';
* import { SharedModule } from '\@vendure/admin-ui/core';
* // highlight-start
* // the import below works both in the context of the custom Admin UI app as well as the main project
* // '\@common-ui-module' is the value of "pathAlias" and 'ui-shared.module' is the file we want to reference inside "extensionPath"
* import { CommonSharedUiModule, CommonUiComponent } from '\@common-ui-module/ui-shared.module';
* // highlight-end
*
* \@NgModule({
* imports: [
* SharedModule,
* CommonSharedUiModule,
* RouterModule.forChild([
* {
* path: '',
* pathMatch: 'full',
* component: CommonUiComponent,
* },
* ]),
* ],
* })
* export class SampleUiExtensionModule {}
* ```
*/
pathAlias?: string;
/**
* @description
* Optional array specifying filenames or [glob](https://github.com/isaacs/node-glob) patterns that should
* be skipped when copying the directory defined by `extensionPath`.
*
* @example
* ```ts
* exclude: ['**\/*.spec.ts']
* ```
*/
exclude?: string[];
}
/**
* @description
* A static asset can be provided as a path to the asset, or as an object containing a path and a new
* name, which will cause the compiler to copy and then rename the asset.
*
* @docsCategory UiDevkit
* @docsPage AdminUiExtension
*/
export type StaticAssetDefinition = string | { path: string; rename: string };
/**
* @description
* Configuration defining a single NgModule with which to extend the Admin UI.
*
* @docsCategory UiDevkit
* @docsPage AdminUiExtension
*/
export interface AdminUiExtensionSharedModule {
/**
* @description
* Shared modules are directly imported into the main AppModule of the Admin UI
* and should be used to declare custom form components and define custom
* navigation items.
*/
type: 'shared';
/**
* @description
* The name of the file containing the extension module class.
*/
ngModuleFileName: string;
/**
* @description
* The name of the extension module class.
*/
ngModuleName: string;
}
/**
* @description
* Configuration defining a single NgModule with which to extend the Admin UI.
*
* @docsCategory UiDevkit
* @docsPage AdminUiExtension
*/
export interface AdminUiExtensionLazyModule {
/**
* @description
* Lazy modules are lazy-loaded at the `/extensions/` route and should be used for
* modules which define new views for the Admin UI.
*/
type: 'lazy';
/**
* @description
* The route specifies the route at which the module will be lazy-loaded. E.g. a value
* of `'foo'` will cause the module to lazy-load when the `/extensions/foo` route
* is activated.
*/
route: string;
/**
* @description
* The name of the file containing the extension module class.
*/
ngModuleFileName: string;
/**
* @description
* The name of the extension module class.
*/
ngModuleName: string;
}
/**
* @description
* Argument to configure process (watch or compile)
*
* @docsCategory UiDevkit
*/
export type UiExtensionCompilerProcessArgument = string | [string, any];
/**
* @description
* Options to configure how the Admin UI should be compiled.
*
* @docsCategory UiDevkit
*/
export interface UiExtensionCompilerOptions {
/**
* @description
* The directory into which the sources for the extended Admin UI will be copied.
*/
outputPath: string;
/**
* @description
* An array of objects which configure Angular modules and/or
* translations with which to extend the Admin UI.
*/
extensions: Extension[];
/**
* @description
* Allows you to manually specify the path to the Angular CLI compiler script. This can be useful in scenarios
* where for some reason the built-in start/build scripts are unable to locate the `ng` command.
*
* This option should not usually be required.
*
* @example
* ```ts
* compileUiExtensions({
* ngCompilerPath: path.join(__dirname, '../../node_modules/@angular/cli/bin/ng.js'),
* outputPath: path.join(__dirname, '../admin-ui'),
* extensions: [
* // ...
* ],
* })
* ```
*
* @since 2.1.0
*/
ngCompilerPath?: string | undefined;
/**
* @description
* Set to `true` in order to compile the Admin UI in development mode (using the Angular CLI
* [ng serve](https://angular.io/cli/serve) command). When in dev mode, any changes to
* UI extension files will be watched and trigger a rebuild of the Admin UI with live
* reloading.
*
* @default false
*/
devMode?: boolean;
/**
* @description
* Allows the baseHref of the compiled Admin UI app to be set. This determines the prefix
* of the app, for example with the default value of `'/admin/'`, the Admin UI app
* will be configured to be served from `http://<host>/admin/`.
*
* Note: if you are using this in conjunction with the {@link AdminUiPlugin} then you should
* also set the `route` option to match this value.
*
* @example
* ```ts
* AdminUiPlugin.init({
* route: 'my-route',
* port: 5001,
* app: compileUiExtensions({
* baseHref: '/my-route/',
* outputPath: path.join(__dirname, './custom-admin-ui'),
* extensions: [],
* devMode: true,
* }),
* }),
* ```
*
* @default '/admin/'
*/
baseHref?: string;
/**
* @description
* In watch mode, allows the port of the dev server to be specified. Defaults to the Angular CLI default
* of `4200`.
*
* @default 4200 | undefined
*/
watchPort?: number;
/**
* @description
* Internally, the Angular CLI will be invoked as an npm script. By default, the compiler will use Yarn
* to run the script if it is detected, otherwise it will use npm. This setting allows you to explicitly
* set which command to use, rather than relying on the default behavior.
*
* @since 1.5.0
*/
command?: 'yarn' | 'npm';
/**
* @description
* Additional command-line arguments which will get passed to the [ng build](https://angular.io/cli/build)
* command (or [ng serve](https://angular.io/cli/serve) if `devMode = true`).
*
* @example
* ['--disable-host-check'] // to disable host check
*
* @default undefined
*
* @since 1.5.0
*/
additionalProcessArguments?: UiExtensionCompilerProcessArgument[];
}
export type Translations = {
[section: string]: {
[token: string]: string;
};
};
export interface BrandingOptions {
smallLogoPath?: string;
largeLogoPath?: string;
faviconPath?: string;
}
export interface AdminUiExtensionWithId extends AdminUiExtension {
id: string;
}
|
/* eslint-disable no-console */
import chalk from 'chalk';
import { execSync } from 'child_process';
import { createHash } from 'crypto';
import * as fs from 'fs-extra';
import * as path from 'path';
import { STATIC_ASSETS_OUTPUT_DIR } from './constants';
import {
AdminUiExtension,
AdminUiExtensionWithId,
Extension,
GlobalStylesExtension,
SassVariableOverridesExtension,
StaticAssetDefinition,
StaticAssetExtension,
TranslationExtension,
} from './types';
export const logger = {
log: (message: string) => console.log(chalk.green(message)),
error: (message: string) => console.log(chalk.red(message)),
};
/**
* Checks for the global yarn binary and returns true if found.
*/
export function shouldUseYarn(): boolean {
try {
execSync('yarnpkg --version', { stdio: 'ignore' });
return true;
} catch (e: any) {
return false;
}
}
/**
* Returns the string path of a static asset
*/
export function getStaticAssetPath(staticAssetDef: StaticAssetDefinition): string {
return typeof staticAssetDef === 'string' ? staticAssetDef : staticAssetDef.path;
}
/**
* Copy the @vendure/ui-devkit files to the static assets dir.
*/
export function copyUiDevkit(outputPath: string) {
const devkitDir = path.join(outputPath, STATIC_ASSETS_OUTPUT_DIR, 'devkit');
fs.ensureDirSync(devkitDir);
fs.copySync(require.resolve('@vendure/ui-devkit'), path.join(devkitDir, 'ui-devkit.js'));
}
/**
* Copies over any files defined by the extensions' `staticAssets` array to the shared
* static assets directory. When the app is built by the ng cli, this assets directory is
* the copied over to the final static assets location (i.e. http://domain/admin/assets/)
*/
export async function copyStaticAsset(outputPath: string, staticAssetDef: StaticAssetDefinition) {
const staticAssetPath = getStaticAssetPath(staticAssetDef);
const assetBasename = path.basename(staticAssetPath);
const assetOutputPath = path.join(outputPath, STATIC_ASSETS_OUTPUT_DIR, assetBasename);
fs.copySync(staticAssetPath, assetOutputPath);
if (typeof staticAssetDef !== 'string') {
// The asset is being renamed
const newName = path.join(path.dirname(assetOutputPath), staticAssetDef.rename);
try {
// We use copy, remove rather than rename due to problems with the
// EPERM error in Windows.
await fs.copy(assetOutputPath, newName);
await fs.remove(assetOutputPath);
} catch (e: any) {
logger.log(e);
}
}
}
/**
* Ensures each extension has an ID and a value for the optional properties.
* If not defined by the user, a deterministic ID is generated
* from a hash of the extension config.
*/
export function normalizeExtensions(extensions?: AdminUiExtension[]): AdminUiExtensionWithId[] {
return (extensions || []).map(e => {
let id = e.id;
if (!id) {
const hash = createHash('sha256');
hash.update(JSON.stringify(e));
id = hash.digest('hex');
}
return {
staticAssets: [],
translations: {},
globalStyles: [],
...e,
id,
};
});
}
export function isAdminUiExtension(input: Extension): input is AdminUiExtension {
return input.hasOwnProperty('extensionPath');
}
export function isTranslationExtension(input: Extension): input is TranslationExtension {
return input.hasOwnProperty('translations');
}
export function isStaticAssetExtension(input: Extension): input is StaticAssetExtension {
return input.hasOwnProperty('staticAssets');
}
export function isGlobalStylesExtension(input: Extension): input is GlobalStylesExtension {
return input.hasOwnProperty('globalStyles');
}
export function isSassVariableOverridesExtension(input: Extension): input is SassVariableOverridesExtension {
return input.hasOwnProperty('sassVariableOverrides');
}
|
/* eslint-disable no-console */
import path from 'path';
/**
* Checks the versions of the Angular compiler packages between the `admin-ui` and `ui-devkit` packages.
* These must match exactly since using different packages can introduce errors when compiling
* with the ui-devkit.
* See https://github.com/vendure-ecommerce/vendure/issues/758 for more on this issue.
*/
async function checkAngularVersions() {
const adminUiPackageJson = require('../packages/admin-ui/package.json');
const uiDevkitPackageJson = require('../packages/ui-devkit/package.json');
const angularCompilerPackages = ['@angular/cli', '@angular/compiler-cli', '@angular/compiler'];
const illegalSemverPrefixes = /^[~^]/;
const errors: string[] = [];
for (const pkg of angularCompilerPackages) {
const uiVersion =
adminUiPackageJson.devDependencies[pkg as keyof typeof adminUiPackageJson.devDependencies];
const devkitVersion =
uiDevkitPackageJson.dependencies[pkg as keyof typeof uiDevkitPackageJson.dependencies];
// Removing this restriction to allow more flexibility in keeping angular versions
// current for end-users, and also preventing issues in monorepos.
// if (illegalSemverPrefixes.test(uiVersion)) {
// errors.push(`Angular compiler versions must be exact, got "${uiVersion}" in admin-ui package`);
// }
// if (illegalSemverPrefixes.test(devkitVersion)) {
// errors.push(
// `Angular compiler versions must be exact, got "${devkitVersion}" in ui-devkit package`,
// );
// }
if (uiVersion !== devkitVersion) {
errors.push(
`Angular compiler package mismatch [${pkg}] admin-ui: "${uiVersion}", ui-devkit: "${devkitVersion}"`,
);
}
}
if (errors.length) {
for (const error of errors) {
console.log(`ERROR: ${error}`);
}
process.exit(1);
} else {
console.log(`Angular compiler package check passed`);
process.exit(0);
}
}
checkAngularVersions();
|
/* eslint-disable no-console */
import fs from 'fs';
import path from 'path';
/**
* For some unknown reason, a v1.2.2 of @vendure/core included incorrect type definitions for some types.
* Namely, _some_ of the `ConfigurableOperationDef` types had their specific string literal & enum types
* replaced with just `string`, which caused the published package to fail to build.
*
* Example:
* [dummy-payment-method-handler.d.ts](https://unpkg.com/@vendure/core@1.2.2/dist/config/payment/dummy-payment-method-handler.d.ts)
* ```
* export declare const dummyPaymentHandler: PaymentMethodHandler<{
* automaticSettle: {
* type: string;
* label: {
* languageCode: any;
* value: string;
* }[];
* description: {
* languageCode: any;
* value: string;
* }[];
* required: true;
* defaultValue: boolean;
* };
* }>;
* ```
*
* Should be:
* ```ts
* export declare const dummyPaymentHandler: PaymentMethodHandler<{
* automaticSettle: {
* type: "boolean";
* label: {
* languageCode: LanguageCode.en;
* value: string;
* }[];
* description: {
* languageCode: LanguageCode.en;
* value: string;
* }[];
* required: true;
* defaultValue: false;
* };
* }>;
* ```
*
* This script should be run before publishing, in order to verify that this is not the case.
*/
const configPath = path.join(__dirname, '../packages/core/dist/config');
const filesToCheck = [
path.join(configPath, 'payment/dummy-payment-method-handler.d.ts'),
path.join(configPath, 'promotion/actions/product-percentage-discount-action.d.ts'),
path.join(configPath, 'promotion/conditions/contains-products-condition.d.ts'),
path.join(configPath, 'shipping-method/default-shipping-calculator.d.ts'),
path.join(configPath, 'shipping-method/default-shipping-eligibility-checker.d.ts'),
path.join(configPath, 'fulfillment/manual-fulfillment-handler.d.ts'),
];
console.log(`Checking core type definitions...`);
let checkIsOk = true;
for (const filePath of filesToCheck) {
const content = fs.readFileSync(filePath, 'utf-8');
const matches = content.match(/type: string;|languageCode: any;/gm);
if (matches) {
console.warn(`\n\nBad type definitions found in file ${filePath}:`);
console.warn(`==========`);
console.warn(matches.join('\n'));
console.warn(`==========`);
checkIsOk = false;
}
}
if (!checkIsOk) {
process.exit(1);
} else {
console.log(`Type defs ok!`);
process.exit(0);
}
|
/* eslint-disable no-console */
import fs from 'fs';
import path from 'path';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const find = require('find');
/**
* An array of regular expressions defining illegal import patterns to be checked in the
* source files of the monorepo packages. This prevents bad imports (which work locally
* and go undetected) from getting into published releases of Vendure.
*/
const illegalImportPatterns: RegExp[] = [
/@vendure\/common\/src/,
/@vendure\/core\/src/,
/@vendure\/admin-ui\/src/,
];
const exclude: string[] = [
path.join(__dirname, '../packages/dev-server'),
];
findInFiles(illegalImportPatterns, path.join(__dirname, '../packages'), /\.ts$/, exclude);
function findInFiles(patterns: RegExp[], directory: string, fileFilter: RegExp, excludePaths: string[]) {
find.file(fileFilter, directory, async (files: string[]) => {
const nonNodeModulesFiles = files.filter(f => !f.includes('node_modules'));
console.log(`Checking imports in ${nonNodeModulesFiles.length} files...`);
const matches = await getMatchedFiles(patterns, nonNodeModulesFiles, excludePaths);
if (matches.length) {
console.error(`Found illegal imports in the following files:`);
console.error(matches.join('\n'));
process.exitCode = 1;
} else {
console.log('Imports check ok!');
}
});
}
async function getMatchedFiles(patterns: RegExp[], files: string[], excludePaths: string[]) {
const matchedFiles = [];
outer:
for (let i = files.length - 1; i >= 0; i--) {
for (const excludedPath of excludePaths) {
if (files[i].includes(excludedPath)) {
continue outer;
}
}
const content = await readFile(files[i]);
for (const pattern of patterns) {
if (pattern.test(content)) {
matchedFiles.push(files[i]);
continue;
}
}
}
return matchedFiles;
}
function readFile(filePath: string): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
|
import * as Stream from 'stream';
import { PassThrough, Writable } from 'stream';
class Appendee extends PassThrough {
constructor(private factory: any, private opts: any) {
super(opts);
}
_flush(end: any) {
const stream = this.factory();
stream.pipe(new Appender(this, this.opts))
.on('finish', end);
stream.resume();
}
}
class Appender extends Writable {
constructor(private target: any, opts: any) {
super(opts);
}
_write(chunk: any, enc: any, cb: any) {
this.target.push(chunk);
cb();
}
}
/**
* Append the contents of one stream onto another.
* Based on https://github.com/wilsonjackson/add-stream
*/
export function addStream(stream: any, opts?: any) {
opts = opts || {};
let factory;
if (typeof stream === 'function') {
factory = stream;
} else {
stream.pause();
factory = () => stream;
}
return new Appendee(factory, opts);
}
|
import fs from 'fs-extra';
import path from 'path';
import { addStream } from './add-stream';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const conventionalChangelogCore = require('conventional-changelog-core');
let changelogFileName = 'CHANGELOG.md';
if (process.argv.includes('--next') || process.env.npm_config_argv?.includes('publish-prerelease')) {
changelogFileName = 'CHANGELOG_NEXT.md';
}
/**
* The types of commit which will be included in the changelog.
*/
const VALID_TYPES = ['feat', 'fix', 'perf'];
/**
* Define which packages to create changelog entries for.
*/
const VALID_SCOPES: string[] = [
'admin-ui-plugin',
'admin-ui',
'asset-server',
'asset-server-plugin',
'cli',
'common',
'core',
'create',
'elasticsearch-plugin',
'email-plugin',
'email',
'job-queue-plugin',
'payments-plugin',
'testing',
'ui-devkit',
'harden-plugin',
'stellate-plugin',
'sentry-plugin',
];
const mainTemplate = fs.readFileSync(path.join(__dirname, 'template.hbs'), 'utf-8');
const commitTemplate = fs.readFileSync(path.join(__dirname, 'commit.hbs'), 'utf-8');
generateChangelogForPackage();
/**
* Generates changelog entries based on the conventional commits data.
*/
function generateChangelogForPackage() {
const changelogPath = path.join(__dirname, '../../', changelogFileName);
const inStream = fs.createReadStream(changelogPath, { flags: 'a+' });
const tempFile = path.join(__dirname, `__temp_changelog__`);
conventionalChangelogCore(
{
transform: (commit: any, context: any) => {
const includeCommit = VALID_TYPES.includes(commit.type) && scopeIsValid(commit.scope);
if (includeCommit) {
return context(null, commit);
} else {
return context(null, null);
}
},
releaseCount: 1,
outputUnreleased: true,
},
{
version: require('../../lerna.json').version,
},
null,
null,
{
mainTemplate,
commitPartial: commitTemplate,
finalizeContext(context: any, options: any, commits: any) {
context.commitGroups.forEach(addHeaderToCommitGroup);
return context;
},
},
)
.pipe(addStream(inStream))
.pipe(fs.createWriteStream(tempFile))
.on('finish', () => {
fs.createReadStream(tempFile)
.pipe(fs.createWriteStream(changelogPath))
.on('finish', () => {
fs.unlinkSync(tempFile);
});
});
}
function scopeIsValid(scope?: string): boolean {
for (const validScope of VALID_SCOPES) {
if (scope && scope.includes(validScope)) {
return true;
}
}
return false;
}
/**
* The `header` is a more human-readable version of the commit type, as used in the
* template.hbs as a sub-heading.
*/
function addHeaderToCommitGroup(commitGroup: any) {
switch (commitGroup.title) {
case 'fix':
commitGroup.header = 'Fixes';
break;
case 'feat':
commitGroup.header = 'Features';
break;
default:
commitGroup.header = commitGroup.title.charAt(0).toUpperCase() + commitGroup.title.slice(1);
break;
}
}
|
import { makeExecutableSchema } from '@graphql-tools/schema';
import fs from 'fs';
import path from 'path';
const CLIENT_SCHEMA_FILE = '../../packages/admin-ui/src/lib/core/src/data/client-state/client-types.graphql';
const LANGUAGE_CODE_FILE = '../../packages/core/src/api/schema/common/language-code.graphql';
const AUTH_TYPE_FILE = '../../packages/core/src/api/schema/common/auth.type.graphql';
function loadGraphQL(file: string): string {
const filePath = path.join(__dirname, file);
return fs.readFileSync(filePath, 'utf8');
}
/**
* Augments the client schema (used by apollo-link-state) with missing
* definitions, to allow the codegen step to work correctly.
* See: https://github.com/dotansimha/graphql-code-generator/issues/583
*/
function getClientSchema() {
const clientDirective = `
directive @client on FIELD
`;
const clientSchemaString = loadGraphQL(CLIENT_SCHEMA_FILE);
const languageCodeString = loadGraphQL(LANGUAGE_CODE_FILE);
const authTypeString = loadGraphQL(AUTH_TYPE_FILE);
const permissionTypeString = `enum Permission { Placeholder }`;
const schema = makeExecutableSchema({
typeDefs: [
clientSchemaString,
clientDirective,
languageCodeString,
authTypeString,
permissionTypeString,
],
});
return schema;
}
export default getClientSchema();
|
import fs from 'fs';
import { getIntrospectionQuery } from 'graphql';
import http from 'http';
import { ADMIN_API_PATH, API_PORT } from '../../packages/common/src/shared-constants';
/* eslint-disable no-console */
/**
* Makes an introspection query to the Vendure server and writes the result to a
* schema.json file.
*
* If there is an error connecting to the server, the promise resolves to false.
*/
export function downloadIntrospectionSchema(apiPath: string, outputFilePath: string): Promise<boolean> {
const body = JSON.stringify({ query: getIntrospectionQuery({ inputValueDeprecation: true }) });
return new Promise((resolve, reject) => {
const request = http.request(
{
method: 'post',
host: 'localhost',
port: API_PORT,
path: '/' + apiPath,
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
},
},
response => {
const outputFile = fs.createWriteStream(outputFilePath);
response.pipe(outputFile);
response.on('end', () => resolve(true));
response.on('error', reject);
},
);
request.write(body);
request.end();
request.on('error', (err: any) => {
if (err.code === 'ECONNREFUSED') {
console.error(
`ERROR: Could not connect to the Vendure server at http://localhost:${API_PORT}/${apiPath}`,
);
resolve(false);
}
reject(err);
});
});
}
|
import { generate } from '@graphql-codegen/cli';
import { Types } from '@graphql-codegen/plugin-helpers/typings';
import fs from 'fs';
import { buildClientSchema } from 'graphql';
import path from 'path';
import { ADMIN_API_PATH, SHOP_API_PATH } from '../../packages/common/src/shared-constants';
import { downloadIntrospectionSchema } from './download-introspection-schema';
const CLIENT_QUERY_FILES = [
path.join(__dirname, '../../packages/admin-ui/src/lib/core/src/data/definitions/**/*.ts'),
path.join(__dirname, '../../packages/admin-ui/src/lib/**/*.ts'),
];
const specFileToIgnore = [
'import.e2e-spec',
'plugin.e2e-spec',
'shop-definitions',
'custom-fields.e2e-spec',
'custom-field-relations.e2e-spec',
'custom-field-permissions.e2e-spec',
'order-item-price-calculation-strategy.e2e-spec',
'list-query-builder.e2e-spec',
'shop-order.e2e-spec',
'database-transactions.e2e-spec',
'custom-permissions.e2e-spec',
'parallel-transactions.e2e-spec',
'order-merge.e2e-spec',
'entity-hydrator.e2e-spec',
'relations-decorator.e2e-spec',
'active-order-strategy.e2e-spec',
'error-handler-strategy.e2e-spec',
];
const E2E_ADMIN_QUERY_FILES = path.join(
__dirname,
`../../packages/core/e2e/**/!(${specFileToIgnore.join('|')}).ts`,
);
const E2E_SHOP_QUERY_FILES = [path.join(__dirname, '../../packages/core/e2e/graphql/shop-definitions.ts')];
const E2E_ELASTICSEARCH_PLUGIN_QUERY_FILES = path.join(
__dirname,
'../../packages/elasticsearch-plugin/e2e/**/*.ts',
);
const E2E_ASSET_SERVER_PLUGIN_QUERY_FILES = path.join(
__dirname,
'../../packages/asset-server-plugin/e2e/**/*.ts',
);
const ADMIN_SCHEMA_OUTPUT_FILE = path.join(__dirname, '../../schema-admin.json');
const SHOP_SCHEMA_OUTPUT_FILE = path.join(__dirname, '../../schema-shop.json');
/* eslint-disable no-console */
Promise.all([
downloadIntrospectionSchema(ADMIN_API_PATH, ADMIN_SCHEMA_OUTPUT_FILE),
downloadIntrospectionSchema(SHOP_API_PATH, SHOP_SCHEMA_OUTPUT_FILE),
])
.then(([adminSchemaSuccess, shopSchemaSuccess]) => {
if (!adminSchemaSuccess || !shopSchemaSuccess) {
console.log('Attempting to generate types from existing schema json files...');
}
const adminSchemaJson = JSON.parse(fs.readFileSync(ADMIN_SCHEMA_OUTPUT_FILE, 'utf-8'));
const shopSchemaJson = JSON.parse(fs.readFileSync(SHOP_SCHEMA_OUTPUT_FILE, 'utf-8'));
const adminSchema = buildClientSchema(adminSchemaJson.data);
const shopSchema = buildClientSchema(shopSchemaJson.data);
const config = {
namingConvention: {
enumValues: 'keep',
},
strict: true,
scalars: {
Money: 'number',
},
};
const e2eConfig = {
...config,
skipTypename: true,
};
const disableEsLintPlugin = { add: { content: '/* eslint-disable */' } };
const graphQlErrorsPlugin = path.join(__dirname, './plugins/graphql-errors-plugin.js');
const commonPlugins = [disableEsLintPlugin, 'typescript'];
const clientPlugins = [...commonPlugins, 'typescript-operations', 'typed-document-node'];
const codegenConfig: Types.Config = {
overwrite: true,
generates: {
[path.join(
__dirname,
'../../packages/core/src/common/error/generated-graphql-admin-errors.ts',
)]: {
schema: [ADMIN_SCHEMA_OUTPUT_FILE],
plugins: [disableEsLintPlugin, graphQlErrorsPlugin],
},
[path.join(
__dirname,
'../../packages/core/src/common/error/generated-graphql-shop-errors.ts',
)]: {
schema: [SHOP_SCHEMA_OUTPUT_FILE],
plugins: [disableEsLintPlugin, graphQlErrorsPlugin],
},
[path.join(__dirname, '../../packages/core/e2e/graphql/generated-e2e-admin-types.ts')]: {
schema: [ADMIN_SCHEMA_OUTPUT_FILE],
documents: E2E_ADMIN_QUERY_FILES,
plugins: clientPlugins,
config: e2eConfig,
},
[path.join(__dirname, '../../packages/core/e2e/graphql/generated-e2e-shop-types.ts')]: {
schema: [SHOP_SCHEMA_OUTPUT_FILE],
documents: E2E_SHOP_QUERY_FILES,
plugins: clientPlugins,
config: e2eConfig,
},
[path.join(
__dirname,
'../../packages/elasticsearch-plugin/e2e/graphql/generated-e2e-elasticsearch-plugin-types.ts',
)]: {
schema: [ADMIN_SCHEMA_OUTPUT_FILE],
documents: E2E_ELASTICSEARCH_PLUGIN_QUERY_FILES,
plugins: clientPlugins,
config: e2eConfig,
},
[path.join(
__dirname,
'../../packages/asset-server-plugin/e2e/graphql/generated-e2e-asset-server-plugin-types.ts',
)]: {
schema: [ADMIN_SCHEMA_OUTPUT_FILE],
documents: E2E_ASSET_SERVER_PLUGIN_QUERY_FILES,
plugins: clientPlugins,
config: e2eConfig,
},
[path.join(__dirname, '../../packages/admin-ui/src/lib/core/src/common/generated-types.ts')]:
{
schema: [ADMIN_SCHEMA_OUTPUT_FILE, path.join(__dirname, 'client-schema.ts')],
documents: CLIENT_QUERY_FILES,
plugins: clientPlugins,
config: {
...config,
skipTypeNameForRoot: true,
},
},
[path.join(
__dirname,
'../../packages/admin-ui/src/lib/core/src/common/introspection-result.ts',
)]: {
schema: [ADMIN_SCHEMA_OUTPUT_FILE, path.join(__dirname, 'client-schema.ts')],
documents: CLIENT_QUERY_FILES,
plugins: [disableEsLintPlugin, 'fragment-matcher'],
config: { ...config, apolloClientVersion: 3 },
},
[path.join(__dirname, '../../packages/common/src/generated-types.ts')]: {
schema: [ADMIN_SCHEMA_OUTPUT_FILE],
plugins: commonPlugins,
config: {
...config,
scalars: {
...(config.scalars ?? {}),
ID: 'string | number',
},
maybeValue: 'T',
},
},
[path.join(__dirname, '../../packages/common/src/generated-shop-types.ts')]: {
schema: [SHOP_SCHEMA_OUTPUT_FILE],
plugins: commonPlugins,
config: {
...config,
scalars: {
...(config.scalars ?? {}),
ID: 'string | number',
},
maybeValue: 'T',
},
},
[path.join(__dirname, '../../packages/payments-plugin/e2e/graphql/generated-admin-types.ts')]:
{
schema: [ADMIN_SCHEMA_OUTPUT_FILE],
documents: path.join(
__dirname,
'../../packages/payments-plugin/e2e/graphql/admin-queries.ts',
),
plugins: clientPlugins,
config: e2eConfig,
},
[path.join(__dirname, '../../packages/payments-plugin/e2e/graphql/generated-shop-types.ts')]:
{
schema: [SHOP_SCHEMA_OUTPUT_FILE],
documents: path.join(
__dirname,
'../../packages/payments-plugin/e2e/graphql/shop-queries.ts',
),
plugins: clientPlugins,
config: e2eConfig,
},
[path.join(
__dirname,
'../../packages/payments-plugin/src/mollie/graphql/generated-shop-types.ts',
)]: {
schema: [
SHOP_SCHEMA_OUTPUT_FILE,
path.join(
__dirname,
'../../packages/payments-plugin/src/mollie/mollie-shop-schema.ts',
),
],
plugins: clientPlugins,
config,
},
},
};
return generate(codegenConfig);
})
.then(
result => {
process.exit(0);
},
err => {
console.error(err);
process.exit(1);
},
);
|
import { PluginFunction } from '@graphql-codegen/plugin-helpers';
import { buildScalars } from '@graphql-codegen/visitor-plugin-common';
import {
ASTNode,
ASTVisitor,
FieldDefinitionNode,
getNamedType,
GraphQLFieldMap,
GraphQLNamedType,
GraphQLObjectType,
GraphQLSchema,
GraphQLType,
GraphQLUnionType,
InterfaceTypeDefinitionNode,
isNamedType,
isObjectType,
isTypeDefinitionNode,
isUnionType,
Kind,
ListTypeNode,
NonNullTypeNode,
ObjectTypeDefinitionNode,
parse,
printSchema,
UnionTypeDefinitionNode,
visit,
} from 'graphql';
import { ASTVisitFn } from 'graphql/language/visitor';
// This plugin generates classes for all GraphQL types which implement the `ErrorResult` interface.
// This means that when returning an error result from a GraphQL operation, you can use one of
// the generated classes rather than constructing the object by hand.
// It also generates type resolvers to be used by Apollo Server to discriminate between
// members of returned union types.
export const ERROR_INTERFACE_NAME = 'ErrorResult';
const empty = () => '';
type TransformedField = { name: string; type: string };
const errorsVisitor: ASTVisitFn<ASTNode> = (node, key, parent) => {
switch (node.kind) {
case Kind.NON_NULL_TYPE: {
return node.type.kind === 'NamedType'
? node.type.name.value
: node.type.kind === 'ListType'
? node.type
: '';
}
case Kind.FIELD_DEFINITION: {
const type = (node.type.kind === 'ListType' ? node.type.type : node.type) as unknown as string;
const tsType = isScalar(type) ? `Scalars['${type}']` : 'any';
const listPart = node.type.kind === 'ListType' ? `[]` : ``;
return { name: node.name.value, type: `${tsType}${listPart}` };
}
case Kind.SCALAR_TYPE_DEFINITION: {
return '';
}
case Kind.INPUT_OBJECT_TYPE_DEFINITION: {
return '';
}
case Kind.ENUM_TYPE_DEFINITION: {
return '';
}
case Kind.UNION_TYPE_DEFINITION: {
return '';
}
case Kind.INTERFACE_TYPE_DEFINITION: {
if (node.name.value !== ERROR_INTERFACE_NAME) {
return '';
}
return [
`export class ${ERROR_INTERFACE_NAME} {`,
` readonly __typename: string;`,
` readonly errorCode: string;`,
...node.fields
.filter(f => (f as any as TransformedField).name !== 'errorCode')
.map(f => ` readonly ${f.name}: ${f.type};`),
`}`,
].join('\n');
}
case Kind.OBJECT_TYPE_DEFINITION: {
if (!inheritsFromErrorResult(node)) {
return '';
}
const originalNode = parent[key] as ObjectTypeDefinitionNode;
const constructorArgs = (node.fields as any as TransformedField[]).filter(
f => f.name !== 'errorCode' && f.name !== 'message',
);
return [
`export class ${node.name.value} extends ${ERROR_INTERFACE_NAME} {`,
` readonly __typename = '${node.name.value}';`,
// We cast this to "any" otherwise we need to specify it as type "ErrorCode",
// which means shared ErrorResult classes e.g. OrderStateTransitionError
// will not be compatible between the admin and shop variations.
` readonly errorCode = '${camelToUpperSnakeCase(node.name.value)}' as any;`,
` readonly message = '${camelToUpperSnakeCase(node.name.value)}';`,
...constructorArgs.map(f => ` readonly ${f.name}: ${f.type};`),
` constructor(`,
constructorArgs.length
? ` input: { ${constructorArgs.map(f => `${f.name}: ${f.type}`).join(', ')} }`
: '',
` ) {`,
` super();`,
...(constructorArgs.length
? constructorArgs.map(f => ` this.${f.name} = input.${f.name}`)
: []),
` }`,
`}`,
].join('\n');
}
}
};
export const plugin: PluginFunction<any> = (schema, documents, config, info) => {
const printedSchema = printSchema(schema); // Returns a string representation of the schema
const astNode = parse(printedSchema); // Transforms the string into ASTNode
const result = visit(astNode, { leave: errorsVisitor });
const defs = result.definitions
.filter(d => !!d)
// Ensure the ErrorResult base class is first
.sort((a, b) => ((a as any).includes('class ErrorResult') ? -1 : 1));
return {
content: [
`/** This file was generated by the graphql-errors-plugin, which is part of the "codegen" npm script. */`,
generateScalars(schema, config),
...defs,
defs.length ? generateIsErrorFunction(schema) : '',
generateTypeResolvers(schema),
].join('\n\n'),
};
};
function generateScalars(schema: GraphQLSchema, config: any): string {
const scalarMap = buildScalars(schema, config.scalars);
const allScalars = Object.keys(scalarMap)
.map(scalarName => {
const scalarValue = scalarMap[scalarName].output.type;
const scalarType = schema.getType(scalarName);
return ` ${scalarName}: ${scalarValue};`;
})
.join('\n');
return `export type Scalars = {\n${allScalars}\n};`;
}
function generateErrorClassSource(node: ObjectTypeDefinitionNode) {
let source = `export class ${node.name.value} {`;
for (const field of node.fields) {
source += ` ${1}`;
}
}
function generateIsErrorFunction(schema: GraphQLSchema) {
const errorNodes = Object.values(schema.getTypeMap())
.filter(isObjectType)
.filter(node => inheritsFromErrorResult(node));
return `
const errorTypeNames = new Set<string>([${errorNodes.map(n => `'${n.name}'`).join(', ')}]);
function isGraphQLError(input: any): input is import('@vendure/common/lib/generated-types').${ERROR_INTERFACE_NAME} {
return input instanceof ${ERROR_INTERFACE_NAME} || errorTypeNames.has(input.__typename);
}`;
}
function generateTypeResolvers(schema: GraphQLSchema) {
const mutations = getOperationsThatReturnErrorUnions(schema, schema.getMutationType().getFields());
const queries = getOperationsThatReturnErrorUnions(schema, schema.getQueryType().getFields());
const operations = [...mutations, ...queries];
const varName = isAdminApi(schema)
? `adminErrorOperationTypeResolvers`
: `shopErrorOperationTypeResolvers`;
const result = [`export const ${varName} = {`];
const typesHandled = new Set<string>();
for (const operation of operations) {
const returnType = unwrapType(operation.type) as GraphQLUnionType;
if (!typesHandled.has(returnType.name)) {
typesHandled.add(returnType.name);
const nonErrorResult = returnType.getTypes().find(t => !inheritsFromErrorResult(t));
result.push(
` ${returnType.name}: {`,
` __resolveType(value: any) {`,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
` return isGraphQLError(value) ? (value as any).__typename : '${nonErrorResult!.name}';`,
` },`,
` },`,
);
}
}
result.push(`};`);
return result.join('\n');
}
function getOperationsThatReturnErrorUnions(schema: GraphQLSchema, fields: GraphQLFieldMap<any, any>) {
return Object.values(fields).filter(operation => {
const innerType = unwrapType(operation.type);
if (isUnionType(innerType)) {
return isUnionOfResultAndErrors(schema, innerType.getTypes());
}
return false;
});
}
function isUnionOfResultAndErrors(schema: GraphQLSchema, types: ReadonlyArray<GraphQLObjectType>) {
const errorResultTypes = types.filter(type => {
if (isObjectType(type)) {
if (inheritsFromErrorResult(type)) {
return true;
}
}
return false;
});
return (errorResultTypes.length = types.length - 1);
}
function isObjectTypeDefinition(node: any): node is ObjectTypeDefinitionNode {
return node && isTypeDefinitionNode(node) && node.kind === 'ObjectTypeDefinition';
}
function inheritsFromErrorResult(node: ObjectTypeDefinitionNode | GraphQLObjectType): boolean {
const interfaceNames = isObjectType(node)
? node.getInterfaces().map(i => i.name)
: node.interfaces.map(i => i.name.value);
return interfaceNames.includes(ERROR_INTERFACE_NAME);
}
/**
* Unwraps the inner type from a higher-order type, e.g. [Address!]! => Address
*/
function unwrapType(type: GraphQLType): GraphQLNamedType {
return getNamedType(type);
}
function isAdminApi(schema: GraphQLSchema): boolean {
return !!schema.getType('UpdateGlobalSettingsInput');
}
function camelToUpperSnakeCase(input: string): string {
return input.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase();
}
function isScalar(type: string): boolean {
return ['ID', 'String', 'Boolean', 'Int', 'Float', 'JSON', 'DateTime', 'Upload'].includes(type);
}
|
import fs from 'fs';
import klawSync from 'klaw-sync';
import { basename } from 'path';
/* eslint-disable no-console */
/**
* Generates the Hugo front matter with the title of the document
*/
export function generateFrontMatter(title: string, isDefaultIndex = false): string {
return `---
title: "${titleCase(title.replace(/-/g, ' '))}"
isDefaultIndex: ${isDefaultIndex ? 'true' : 'false'}
generated: true
---
<!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script -->
import MemberInfo from '@site/src/components/MemberInfo';
import GenerationInfo from '@site/src/components/GenerationInfo';
import MemberDescription from '@site/src/components/MemberDescription';
`;
}
export function titleCase(input: string): string {
return input
.split(' ')
.map(w => w[0].toLocaleUpperCase() + w.substr(1))
.join(' ');
}
export function normalizeForUrlPart<T extends string | undefined>(input: T): T {
if (input == null) {
return input;
}
return input
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/[^a-zA-Z0-9-_/]/g, ' ')
.replace(/\s+/g, '-')
.toLowerCase() as T;
}
/**
* Delete all generated docs found in the outputPath.
*/
export function deleteGeneratedDocs(outputPath: string) {
if (!fs.existsSync(outputPath)) {
return;
}
try {
let deleteCount = 0;
const files = klawSync(outputPath, { nodir: true });
for (const file of files) {
const content = fs.readFileSync(file.path, 'utf-8');
if (isGenerated(content)) {
fs.unlinkSync(file.path);
deleteCount++;
}
}
if (deleteCount) {
console.log(`Deleted ${deleteCount} generated docs from ${outputPath}`);
}
} catch (e: any) {
console.error('Could not delete generated docs!');
console.log(e);
process.exitCode = 1;
}
}
/**
* Returns true if the content matches that of a generated document.
*/
function isGenerated(content: string) {
return /generated\: true\n---\n/.test(content);
}
|
import fs from 'fs';
import {
buildClientSchema,
GraphQLField,
GraphQLInputObjectType,
GraphQLNamedType,
GraphQLObjectType,
GraphQLType,
GraphQLUnionType,
isEnumType,
isInputObjectType,
isNamedType,
isObjectType,
isScalarType,
isUnionType,
} from 'graphql';
import path from 'path';
import { deleteGeneratedDocs, generateFrontMatter } from './docgen-utils';
/* eslint-disable no-console */
type TargetApi = 'shop' | 'admin';
const targetApi: TargetApi = getTargetApiFromArgs();
// The path to the introspection schema json file
const SCHEMA_FILE = path.join(__dirname, `../../schema-${targetApi}.json`);
// The absolute URL to the generated api docs section
const docsUrl = `/reference/graphql-api/${targetApi}/`;
// The directory in which the markdown files will be saved
const outputPath = path.join(__dirname, `../../docs/docs/reference/graphql-api/${targetApi}`);
const enum FileName {
ENUM = 'enums',
INPUT = 'input-types',
MUTATION = 'mutations',
QUERY = 'queries',
OBJECT = 'object-types',
}
const schemaJson = fs.readFileSync(SCHEMA_FILE, 'utf8');
const parsed = JSON.parse(schemaJson);
const schema = buildClientSchema(parsed.data ? parsed.data : parsed);
deleteGeneratedDocs(outputPath);
generateGraphqlDocs(outputPath);
function generateGraphqlDocs(hugoOutputPath: string) {
const timeStart = +new Date();
let queriesOutput = generateFrontMatter('Queries') + '\n\n';
let mutationsOutput = generateFrontMatter('Mutations') + '\n\n';
let objectTypesOutput = generateFrontMatter('Types') + '\n\n';
let inputTypesOutput = generateFrontMatter('Input Objects') + '\n\n';
let enumsOutput = generateFrontMatter('Enums') + '\n\n';
const sortByName = (a: { name: string }, b: { name: string }) => (a.name < b.name ? -1 : 1);
const sortedTypes = Object.values(schema.getTypeMap()).sort(sortByName);
for (const type of sortedTypes) {
if (type.name.substring(0, 2) === '__') {
// ignore internal types
continue;
}
if (isObjectType(type)) {
if (type.name === 'Query') {
for (const field of Object.values(type.getFields()).sort(sortByName)) {
if (field.name === 'temp__') {
continue;
}
queriesOutput += `\n## ${field.name}\n`;
queriesOutput += `<div class="graphql-code-block">\n`;
queriesOutput += renderDescription(field, 'multi', true);
queriesOutput += codeLine(`type ${identifier('Query')} {`, ['top-level']);
queriesOutput += renderFields([field], false);
queriesOutput += codeLine(`}`, ['top-level']);
queriesOutput += `</div>\n`;
}
} else if (type.name === 'Mutation') {
for (const field of Object.values(type.getFields()).sort(sortByName)) {
mutationsOutput += `\n## ${field.name}\n`;
mutationsOutput += `<div class="graphql-code-block">\n`;
mutationsOutput += renderDescription(field, 'multi', true);
mutationsOutput += codeLine(`type ${identifier('Mutation')} {`, ['top-level']);
mutationsOutput += renderFields([field], false);
mutationsOutput += codeLine(`}`, ['top-level']);
mutationsOutput += `</div>\n`;
}
} else {
objectTypesOutput += `\n## ${type.name}\n\n`;
objectTypesOutput += `<div class="graphql-code-block">\n`;
objectTypesOutput += renderDescription(type, 'multi', true);
objectTypesOutput += codeLine(`type ${identifier(type.name)} {`, ['top-level']);
objectTypesOutput += renderFields(type);
objectTypesOutput += codeLine(`}`, ['top-level']);
objectTypesOutput += `</div>\n`;
}
}
if (isEnumType(type)) {
enumsOutput += `\n## ${type.name}\n\n`;
enumsOutput += `<div class="graphql-code-block">\n`;
enumsOutput += renderDescription(type) + '\n';
enumsOutput += codeLine(`enum ${identifier(type.name)} {`, ['top-level']);
for (const value of type.getValues()) {
enumsOutput += value.description ? renderDescription(value.description, 'single') : '';
enumsOutput += codeLine(value.name);
}
enumsOutput += codeLine(`}`, ['top-level']);
enumsOutput += '\n</div>\n';
}
if (isScalarType(type)) {
objectTypesOutput += `\n## ${type.name}\n\n`;
objectTypesOutput += `<div class="graphql-code-block">\n`;
objectTypesOutput += renderDescription(type, 'multi', true);
objectTypesOutput += codeLine(`scalar ${identifier(type.name)}`, ['top-level']);
objectTypesOutput += '\n</div>\n';
}
if (isInputObjectType(type)) {
inputTypesOutput += `\n## ${type.name}\n\n`;
inputTypesOutput += `<div class="graphql-code-block">\n`;
inputTypesOutput += renderDescription(type, 'multi', true);
inputTypesOutput += codeLine(`input ${identifier(type.name)} {`, ['top-level']);
inputTypesOutput += renderFields(type);
inputTypesOutput += codeLine(`}`, ['top-level']);
inputTypesOutput += '\n</div>\n';
}
if (isUnionType(type)) {
objectTypesOutput += `\n## ${type.name}\n\n`;
objectTypesOutput += `<div class="graphql-code-block">\n`;
objectTypesOutput += renderDescription(type);
objectTypesOutput += codeLine(`union ${identifier(type.name)} =`, ['top-level']);
objectTypesOutput += renderUnion(type);
objectTypesOutput += '\n</div>\n';
}
}
fs.writeFileSync(path.join(hugoOutputPath, FileName.QUERY + '.md'), queriesOutput);
fs.writeFileSync(path.join(hugoOutputPath, FileName.MUTATION + '.md'), mutationsOutput);
fs.writeFileSync(path.join(hugoOutputPath, FileName.OBJECT + '.md'), objectTypesOutput);
fs.writeFileSync(path.join(hugoOutputPath, FileName.INPUT + '.md'), inputTypesOutput);
fs.writeFileSync(path.join(hugoOutputPath, FileName.ENUM + '.md'), enumsOutput);
console.log(`Generated 5 GraphQL API docs in ${+new Date() - timeStart}ms`);
}
function codeLine(content: string, extraClass?: ['top-level' | 'comment'] | undefined): string {
return `<div class="graphql-code-line ${extraClass ? extraClass.join(' ') : ''}">${content}</div>\n`;
}
function identifier(name: string): string {
return `<span class="graphql-code-identifier">${name}</span>\n`;
}
/**
* Renders the type description if it exists.
*/
function renderDescription(
typeOrDescription: { description?: string | null } | string,
mode: 'single' | 'multi' = 'multi',
topLevel = false,
): string {
let description = '';
if (typeof typeOrDescription === 'string') {
description = typeOrDescription;
} else if (!typeOrDescription.description) {
return '';
} else {
description = typeOrDescription.description;
}
if (description.trim() === '') {
return '';
}
description = description
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/{/g, '{')
.replace(/}/g, '}');
// Strip any JSDoc tags which may be used to annotate the generated
// TS types.
const stringsToStrip = [/@docsCategory\s+[^\n]+/g, /@description\s+/g];
for (const pattern of stringsToStrip) {
description = description.replace(pattern, '');
}
let result = '';
const extraClass = topLevel ? ['top-level', 'comment'] : (['comment'] as any);
if (mode === 'single') {
result = codeLine(`"""${description}"""`, extraClass);
} else {
result =
codeLine(`"""`, extraClass) +
description
.split('\n')
.map(line => codeLine(`${line}`, extraClass))
.join('\n') +
codeLine(`"""`, extraClass);
}
result = result.replace(/\s`([^`]+)`\s/g, ' <code>$1</code> ');
return result;
}
function renderFields(
typeOrFields: (GraphQLObjectType | GraphQLInputObjectType) | Array<GraphQLField<any, any>>,
includeDescription = true,
): string {
let output = '';
const fieldsArray: Array<GraphQLField<any, any>> = Array.isArray(typeOrFields)
? typeOrFields
: Object.values(typeOrFields.getFields());
for (const field of fieldsArray) {
if (includeDescription) {
output += field.description ? renderDescription(field.description) : '';
}
output += `${renderFieldSignature(field)}\n`;
}
output += '\n';
return output;
}
function renderUnion(type: GraphQLUnionType): string {
const unionTypes = type
.getTypes()
.map(t => renderTypeAsLink(t))
.join(' | ');
return codeLine(`${unionTypes}`);
}
/**
* Renders a field signature including any argument and output type
*/
function renderFieldSignature(field: GraphQLField<any, any>): string {
let name = field.name;
if (field.args && field.args.length) {
name += `(${field.args.map(arg => arg.name + ': ' + renderTypeAsLink(arg.type)).join(', ')})`;
}
return codeLine(`${name}: ${renderTypeAsLink(field.type)}`);
}
/**
* Renders a type as an anchor link.
*/
function renderTypeAsLink(type: GraphQLType): string {
const innerType = unwrapType(type);
const fileName = isEnumType(innerType)
? FileName.ENUM
: isInputObjectType(innerType)
? FileName.INPUT
: FileName.OBJECT;
const url = `${docsUrl}${fileName}#${innerType.name.toLowerCase()}`;
return type.toString().replace(innerType.name, `<a href="${url}">${innerType.name}</a>`);
}
/**
* Unwraps the inner type from a higher-order type, e.g. [Address!]! => Address
*/
function unwrapType(type: GraphQLType): GraphQLNamedType {
if (isNamedType(type)) {
return type;
}
let innerType = type as GraphQLType;
while (!isNamedType(innerType)) {
innerType = innerType.ofType;
}
return innerType;
}
function getTargetApiFromArgs(): TargetApi {
const apiArg = process.argv.find(arg => /--api=(shop|admin)/.test(arg));
if (!apiArg) {
console.error('\nPlease specify which GraphQL API to generate docs for: --api=<shop|admin>\n');
process.exit(1);
return null as never;
}
return apiArg === '--api=shop' ? 'shop' : 'admin';
}
|
/* eslint-disable no-console */
import fs from 'fs-extra';
import klawSync from 'klaw-sync';
import path, { extname } from 'path';
import { deleteGeneratedDocs, normalizeForUrlPart } from './docgen-utils';
import { TypeMap } from './typescript-docgen-types';
import { TypescriptDocsParser } from './typescript-docs-parser';
import { TypescriptDocsRenderer } from './typescript-docs-renderer';
interface DocsSectionConfig {
sourceDirs: string[];
exclude?: RegExp[];
outputPath: string;
}
const sections: DocsSectionConfig[] = [
{
sourceDirs: ['packages/core/src/', 'packages/common/src/', 'packages/testing/src/'],
exclude: [/generated-shop-types/],
outputPath: 'typescript-api',
},
{
sourceDirs: ['packages/admin-ui-plugin/src/'],
outputPath: '',
},
{
sourceDirs: ['packages/asset-server-plugin/src/'],
outputPath: '',
},
{
sourceDirs: ['packages/email-plugin/src/'],
outputPath: '',
},
{
sourceDirs: ['packages/elasticsearch-plugin/src/'],
outputPath: '',
},
{
sourceDirs: ['packages/job-queue-plugin/src/'],
outputPath: '',
},
{
sourceDirs: ['packages/payments-plugin/src/'],
exclude: [/generated-shop-types/],
outputPath: '',
},
{
sourceDirs: ['packages/harden-plugin/src/'],
outputPath: '',
},
{
sourceDirs: ['packages/stellate-plugin/src/'],
outputPath: '',
},
{
sourceDirs: ['packages/sentry-plugin/src/'],
outputPath: '',
},
{
sourceDirs: ['packages/admin-ui/src/lib/', 'packages/ui-devkit/src/'],
exclude: [/generated-types/],
outputPath: 'admin-ui-api',
},
];
generateTypescriptDocs(sections);
const watchMode = !!process.argv.find(arg => arg === '--watch' || arg === '-w');
if (watchMode) {
console.log(`Watching for changes to source files...`);
sections.forEach(section => {
section.sourceDirs.forEach(dir => {
fs.watch(dir, { recursive: true }, (eventType, file) => {
if (file && extname(file) === '.ts') {
console.log(`Changes detected in ${dir}`);
generateTypescriptDocs([section], true);
}
});
});
});
}
/**
* Uses the TypeScript compiler API to parse the given files and extract out the documentation
* into markdown files
*/
function generateTypescriptDocs(config: DocsSectionConfig[], isWatchMode: boolean = false) {
const timeStart = +new Date();
// This map is used to cache types and their corresponding Hugo path. It is used to enable
// hyperlinking from a member's "type" to the definition of that type.
const globalTypeMap: TypeMap = new Map();
if (!isWatchMode) {
for (const { outputPath, sourceDirs } of config) {
deleteGeneratedDocs(absOutputPath(outputPath));
}
}
for (const { outputPath, sourceDirs, exclude } of config) {
const sourceFilePaths = getSourceFilePaths(sourceDirs, exclude);
const docsPages = new TypescriptDocsParser().parse(sourceFilePaths);
for (const page of docsPages) {
const { category, fileName, declarations } = page;
for (const declaration of declarations) {
const pathToTypeDoc = `reference/${outputPath ? `${outputPath}/` : ''}${
category ? category.map(part => normalizeForUrlPart(part)).join('/') + '/' : ''
}${fileName === 'index' ? '' : fileName}#${toHash(declaration.title)}`;
globalTypeMap.set(declaration.title, pathToTypeDoc);
}
}
const docsUrl = ``;
const generatedCount = new TypescriptDocsRenderer().render(
docsPages,
docsUrl,
absOutputPath(outputPath),
globalTypeMap,
);
if (generatedCount) {
console.log(
`Generated ${generatedCount} typescript api docs for "${outputPath}" in ${
+new Date() - timeStart
}ms`,
);
}
}
}
function toHash(title: string): string {
return title.replace(/\s/g, '').toLowerCase();
}
function absOutputPath(outputPath: string): string {
return path.join(__dirname, '../../docs/docs/reference/', outputPath);
}
function getSourceFilePaths(sourceDirs: string[], excludePatterns: RegExp[] = []): string[] {
return sourceDirs
.map(scanPath =>
klawSync(path.join(__dirname, '../../', scanPath), {
nodir: true,
filter: item => {
const ext = path.extname(item.path);
if (ext === '.ts' || ext === '.tsx') {
for (const pattern of excludePatterns) {
if (pattern.test(item.path)) {
return false;
}
}
return true;
}
return false;
},
traverseAll: true,
}),
)
.reduce((allFiles, files) => [...allFiles, ...files], [])
.map(item => item.path);
}
|
import ts, { HeritageClause } from 'typescript';
export interface MethodParameterInfo {
name: string;
type: string;
optional: boolean;
initializer?: string;
}
export interface MemberInfo {
name: string;
description: string;
type: string;
fullText: string;
modifiers: string[];
since: string | undefined;
experimental: boolean;
}
export interface PropertyInfo extends MemberInfo {
kind: 'property';
defaultValue: string;
}
export interface MethodInfo extends MemberInfo {
kind: 'method';
parameters: MethodParameterInfo[];
}
export interface DocsPage {
title: string;
category: string[];
declarations: ParsedDeclaration[];
fileName: string;
}
export interface DeclarationInfo {
packageName: string;
sourceFile: string;
sourceLine: number;
title: string;
fullText: string;
weight: number;
category: string;
description: string;
page: string | undefined;
since: string | undefined;
experimental: boolean;
}
export interface InterfaceInfo extends DeclarationInfo {
kind: 'interface';
extendsClause: HeritageClause | undefined;
members: Array<PropertyInfo | MethodInfo>;
}
export interface ClassInfo extends DeclarationInfo {
kind: 'class';
extendsClause: HeritageClause | undefined;
implementsClause: HeritageClause | undefined;
members: Array<PropertyInfo | MethodInfo>;
}
export interface TypeAliasInfo extends DeclarationInfo {
kind: 'typeAlias';
members?: Array<PropertyInfo | MethodInfo>;
type: ts.TypeNode;
}
export interface EnumInfo extends DeclarationInfo {
kind: 'enum';
members: PropertyInfo[];
}
export interface FunctionInfo extends DeclarationInfo {
kind: 'function';
parameters: MethodParameterInfo[];
type?: ts.TypeNode;
}
export interface VariableInfo extends DeclarationInfo {
kind: 'variable';
}
export type ParsedDeclaration =
| TypeAliasInfo
| ClassInfo
| InterfaceInfo
| EnumInfo
| FunctionInfo
| VariableInfo;
export type ValidDeclaration =
| ts.InterfaceDeclaration
| ts.TypeAliasDeclaration
| ts.ClassDeclaration
| ts.EnumDeclaration
| ts.FunctionDeclaration
| ts.VariableStatement;
export type TypeMap = Map<string, string>;
|
import fs from 'fs';
import path from 'path';
import ts, { HeritageClause, JSDocTag, Modifier, NodeArray, SyntaxKind } from 'typescript';
import { notNullOrUndefined } from '../../packages/common/src/shared-utils';
import { normalizeForUrlPart } from './docgen-utils';
import {
DocsPage,
MemberInfo,
MethodInfo,
MethodParameterInfo,
ParsedDeclaration,
PropertyInfo,
ValidDeclaration,
} from './typescript-docgen-types';
/**
* Parses TypeScript source files into data structures which can then be rendered into
* markdown for documentation.
*/
export class TypescriptDocsParser {
private readonly atTokenPlaceholder = '__EscapedAtToken__';
private readonly commentBlockEndTokenPlaceholder = '__EscapedCommentBlockEndToken__';
/**
* Parses the TypeScript files given by the filePaths array and returns the
* parsed data structures ready for rendering.
*/
parse(filePaths: string[]): DocsPage[] {
const sourceFiles = filePaths.map(filePath => {
return ts.createSourceFile(
filePath,
this.replaceEscapedTokens(fs.readFileSync(filePath).toString()),
ts.ScriptTarget.ES2015,
true,
);
});
const statements = this.getStatementsWithSourceLocation(sourceFiles);
const pageMap = statements
.map(statement => {
const info = this.parseDeclaration(
statement.statement,
statement.sourceFile,
statement.sourceLine,
);
return info;
})
.filter(notNullOrUndefined)
.reduce((pages, declaration) => {
const pageTitle = declaration.page || declaration.title;
const existingPage = pages.get(pageTitle);
if (existingPage) {
existingPage.declarations.push(declaration);
} else {
const normalizedTitle = normalizeForUrlPart(pageTitle);
const categoryLastPart = declaration.category.split('/').pop();
const fileName = normalizedTitle === categoryLastPart ? 'index' : normalizedTitle;
pages.set(pageTitle, {
title: pageTitle,
category: declaration.category.split('/'),
declarations: [declaration],
fileName,
});
}
return pages;
}, new Map<string, DocsPage>());
return Array.from(pageMap.values());
}
/**
* Maps an array of parsed SourceFiles into statements, including a reference to the original file each statement
* came from.
*/
private getStatementsWithSourceLocation(
sourceFiles: ts.SourceFile[],
): Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }> {
return sourceFiles.reduce(
(st, sf) => {
const statementsWithSources = sf.statements.map(statement => {
const sourceFile = path
.relative(path.join(__dirname, '..'), sf.fileName)
.replace(/\\/g, '/');
const sourceLine = sf.getLineAndCharacterOfPosition(statement.getStart()).line + 1;
return { statement, sourceFile, sourceLine };
});
return [...st, ...statementsWithSources];
},
[] as Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }>,
);
}
/**
* Parses an InterfaceDeclaration into a simple object which can be rendered into markdown.
*/
private parseDeclaration(
statement: ts.Statement,
sourceFile: string,
sourceLine: number,
): ParsedDeclaration | undefined {
if (!this.isValidDeclaration(statement)) {
return;
}
const category = this.getDocsCategory(statement);
if (category === undefined) {
return;
}
let title: string;
if (ts.isVariableStatement(statement)) {
title = statement.declarationList.declarations[0].name.getText();
} else {
title = statement.name ? statement.name.getText() : 'anonymous';
}
const fullText = this.getDeclarationFullText(statement);
const weight = this.getDeclarationWeight(statement);
const description = this.getDeclarationDescription(statement);
const docsPage = this.getDocsPage(statement);
const since = this.getSince(statement);
const experimental = this.getExperimental(statement);
const packageName = this.getPackageName(sourceFile);
const info = {
packageName,
sourceFile,
sourceLine,
fullText,
title,
weight,
category,
description,
page: docsPage,
since,
experimental,
};
if (ts.isInterfaceDeclaration(statement)) {
return {
...info,
kind: 'interface',
extendsClause: this.getHeritageClause(statement, ts.SyntaxKind.ExtendsKeyword),
members: this.parseMembers(statement.members),
};
} else if (ts.isTypeAliasDeclaration(statement)) {
return {
...info,
type: statement.type,
kind: 'typeAlias',
members: ts.isTypeLiteralNode(statement.type)
? this.parseMembers(statement.type.members)
: undefined,
};
} else if (ts.isClassDeclaration(statement)) {
return {
...info,
kind: 'class',
members: this.parseMembers(statement.members),
extendsClause: this.getHeritageClause(statement, ts.SyntaxKind.ExtendsKeyword),
implementsClause: this.getHeritageClause(statement, ts.SyntaxKind.ImplementsKeyword),
};
} else if (ts.isEnumDeclaration(statement)) {
return {
...info,
kind: 'enum' as const,
members: this.parseMembers(statement.members) as PropertyInfo[],
};
} else if (ts.isFunctionDeclaration(statement)) {
const parameters = statement.parameters.map(p => ({
name: p.name.getText(),
type: p.type ? p.type.getText() : '',
optional: !!p.questionToken,
initializer: p.initializer && p.initializer.getText(),
}));
return {
...info,
kind: 'function',
parameters,
type: statement.type,
};
} else if (ts.isVariableStatement(statement)) {
return {
...info,
kind: 'variable',
};
}
}
/**
* Returns the text of any "extends" or "implements" clause of a class or interface.
*/
private getHeritageClause(
statement: ts.ClassDeclaration | ts.InterfaceDeclaration,
kind: ts.SyntaxKind.ExtendsKeyword | ts.SyntaxKind.ImplementsKeyword,
): HeritageClause | undefined {
const { heritageClauses } = statement;
if (!heritageClauses) {
return;
}
const clause = heritageClauses.find(cl => cl.token === kind);
if (!clause) {
return;
}
return clause;
}
/**
* Returns the declaration name plus any type parameters.
*/
private getDeclarationFullText(declaration: ValidDeclaration): string {
let name: string;
if (ts.isVariableStatement(declaration)) {
name = declaration.declarationList.declarations[0].name.getText();
} else {
name = declaration.name ? declaration.name.getText() : 'anonymous';
}
let typeParams = '';
if (
!ts.isEnumDeclaration(declaration) &&
!ts.isVariableStatement(declaration) &&
declaration.typeParameters
) {
typeParams = '<' + declaration.typeParameters.map(tp => tp.getText()).join(', ') + '>';
}
return name + typeParams;
}
private getPackageName(sourceFile: string): string {
const matches = sourceFile.match(/\/packages\/([^/]+)\//);
if (matches) {
return `@vendure/${matches[1]}`;
} else {
return '';
}
}
/**
* Parses an array of interface members into a simple object which can be rendered into markdown.
*/
private parseMembers(
members: ts.NodeArray<ts.TypeElement | ts.ClassElement | ts.EnumMember>,
): Array<PropertyInfo | MethodInfo> {
const result: Array<PropertyInfo | MethodInfo> = [];
const hasModifiers = (member: any): member is { modifiers: NodeArray<Modifier> } =>
Array.isArray(member.modifiers);
for (const member of members) {
const modifiers = hasModifiers(member) ? member.modifiers.map(m => m.getText()) : [];
const isPrivate = modifiers.includes('private');
if (
!isPrivate &&
(ts.isPropertySignature(member) ||
ts.isMethodSignature(member) ||
ts.isPropertyDeclaration(member) ||
ts.isMethodDeclaration(member) ||
ts.isConstructorDeclaration(member) ||
ts.isEnumMember(member) ||
ts.isGetAccessorDeclaration(member) ||
ts.isIndexSignatureDeclaration(member))
) {
const name = member.name
? member.name.getText()
: ts.isIndexSignatureDeclaration(member)
? '[index]'
: 'constructor';
let description = '';
let type = '';
let defaultValue = '';
let parameters: MethodParameterInfo[] = [];
let fullText = '';
let isInternal = false;
let since: string | undefined;
let experimental = false;
if (ts.isConstructorDeclaration(member)) {
fullText = 'constructor';
} else if (ts.isMethodDeclaration(member)) {
fullText = member.name.getText();
} else if (ts.isGetAccessorDeclaration(member)) {
fullText = `${member.name.getText()}: ${member.type ? member.type.getText() : 'void'}`;
} else {
fullText = member.getText();
}
this.parseTags(member, {
description: comment => (description += comment || ''),
example: comment => (description += this.formatExampleCode(comment)),
default: comment => (defaultValue = comment || ''),
internal: comment => (isInternal = true),
since: comment => (since = comment || undefined),
experimental: comment => (experimental = comment != null),
});
if (isInternal) {
continue;
}
if (!ts.isEnumMember(member) && member.type) {
type = member.type.getText();
}
const memberInfo: MemberInfo = {
fullText,
name,
description: this.restoreTokens(description),
type: type.replace(/`/g, '\\`'),
modifiers,
since,
experimental,
};
if (
ts.isMethodSignature(member) ||
ts.isMethodDeclaration(member) ||
ts.isConstructorDeclaration(member)
) {
parameters = member.parameters.map(p => ({
name: p.name.getText(),
type: p.type ? p.type.getText() : '',
optional: !!p.questionToken,
initializer: p.initializer && p.initializer.getText(),
}));
result.push({
...memberInfo,
kind: 'method',
parameters,
});
} else {
result.push({
...memberInfo,
kind: 'property',
defaultValue,
});
}
}
}
return result;
}
private tagCommentText(tag: JSDocTag): string {
if (!tag.comment) {
return '';
}
if (typeof tag.comment === 'string') {
return tag.comment;
}
return tag.comment.map(t => (t.kind === SyntaxKind.JSDocText ? t.text : t.getText())).join('');
}
/**
* Reads the @docsWeight JSDoc tag from the interface.
*/
private getDeclarationWeight(statement: ValidDeclaration): number {
let weight = 10;
this.parseTags(statement, {
docsWeight: comment => (weight = Number.parseInt(comment || '10', 10)),
});
return weight;
}
private getDocsPage(statement: ValidDeclaration): string | undefined {
let docsPage: string | undefined;
this.parseTags(statement, {
docsPage: comment => (docsPage = comment),
});
return docsPage;
}
/**
* Reads the @since JSDoc tag
*/
private getSince(statement: ValidDeclaration): string | undefined {
let since: string | undefined;
this.parseTags(statement, {
since: comment => (since = comment),
});
return since;
}
/**
* Reads the @experimental JSDoc tag
*/
private getExperimental(statement: ValidDeclaration): boolean {
let experimental = false;
this.parseTags(statement, {
experimental: comment => (experimental = comment != null),
});
return experimental;
}
/**
* Reads the @description JSDoc tag from the interface.
*/
private getDeclarationDescription(statement: ValidDeclaration): string {
let description = '';
this.parseTags(statement, {
description: comment => (description += comment),
example: comment => (description += this.formatExampleCode(comment)),
});
return this.restoreTokens(description);
}
/**
* Extracts the "@docsCategory" value from the JSDoc comments if present.
*/
private getDocsCategory(statement: ValidDeclaration): string | undefined {
let category: string | undefined;
this.parseTags(statement, {
docsCategory: comment => (category = comment || ''),
});
return normalizeForUrlPart(category);
}
/**
* Type guard for the types of statement which can ge processed by the doc generator.
*/
private isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
return (
ts.isInterfaceDeclaration(statement) ||
ts.isTypeAliasDeclaration(statement) ||
ts.isClassDeclaration(statement) ||
ts.isEnumDeclaration(statement) ||
ts.isFunctionDeclaration(statement) ||
ts.isVariableStatement(statement)
);
}
/**
* Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
*/
private parseTags<T extends ts.Node>(
node: T,
tagMatcher: { [tagName: string]: (tagComment: string) => void },
): void {
const jsDocTags = ts.getJSDocTags(node);
for (const tag of jsDocTags) {
const tagName = tag.tagName.text;
if (tagMatcher[tagName]) {
tagMatcher[tagName](this.tagCommentText(tag));
}
}
}
/**
* Ensure all the code examples use the unix-style line separators.
*/
private formatExampleCode(example: string = ''): string {
return '\n\n*Example*\n\n' + example.replace(/\r/g, '');
}
/**
* TypeScript from v3.5.1 interprets all '@' tokens in a tag comment as a new tag. This is a problem e.g.
* when a plugin includes in its description some text like "install the @vendure/some-plugin package". Here,
* TypeScript will interpret "@vendure" as a JSDoc tag and remove it and all remaining text from the comment.
*
* The solution is to replace all escaped @ tokens ("\@") with a replacer string so that TypeScript treats them
* as regular comment text, and then once it has parsed the statement, we replace them with the "@" character.
*
* Similarly, '/*' is interpreted as end of a comment block. However, it can be useful to specify a globstar
* pattern in descriptions and therefore it is supported as long as the leading '/' is escaped ("\/").
*/
private replaceEscapedTokens(content: string): string {
return content
.replace(/\\@/g, this.atTokenPlaceholder)
.replace(/\\\/\*/g, this.commentBlockEndTokenPlaceholder);
}
/**
* Restores "@" and "/*" tokens which were replaced by the replaceEscapedTokens() method.
*/
private restoreTokens(content: string): string {
return content
.replace(new RegExp(this.atTokenPlaceholder, 'g'), '@')
.replace(new RegExp(this.commentBlockEndTokenPlaceholder, 'g'), '/*');
}
}
|
/* eslint-disable no-console */
import fs from 'fs-extra';
import path from 'path';
import { HeritageClause } from 'typescript';
import { assertNever } from '../../packages/common/src/shared-utils';
import { generateFrontMatter } from './docgen-utils';
import {
ClassInfo,
DeclarationInfo,
DocsPage,
EnumInfo,
FunctionInfo,
InterfaceInfo,
MethodParameterInfo,
TypeAliasInfo,
TypeMap,
VariableInfo,
} from './typescript-docgen-types';
const INDENT = ' ';
export class TypescriptDocsRenderer {
render(pages: DocsPage[], docsUrl: string, outputPath: string, typeMap: TypeMap): number {
let generatedCount = 0;
if (!fs.existsSync(outputPath)) {
fs.ensureDirSync(outputPath);
}
for (const page of pages) {
let markdown = '';
markdown += generateFrontMatter(page.title);
const declarationsByWeight = page.declarations.sort((a, b) => a.weight - b.weight);
for (const info of declarationsByWeight) {
switch (info.kind) {
case 'interface':
markdown += this.renderInterfaceOrClass(info, typeMap, docsUrl);
break;
case 'typeAlias':
markdown += this.renderTypeAlias(info, typeMap, docsUrl);
break;
case 'class':
markdown += this.renderInterfaceOrClass(info, typeMap, docsUrl);
break;
case 'enum':
markdown += this.renderEnum(info, typeMap, docsUrl);
break;
case 'function':
markdown += this.renderFunction(info, typeMap, docsUrl);
break;
case 'variable':
markdown += this.renderVariable(info, typeMap, docsUrl);
break;
default:
assertNever(info);
}
}
const categoryDir = path.join(outputPath, ...page.category);
if (!fs.existsSync(categoryDir)) {
fs.mkdirsSync(categoryDir);
}
const pathParts = [];
for (const subCategory of page.category) {
pathParts.push(subCategory);
const indexFile = path.join(outputPath, ...pathParts, 'index.md');
const exists = fs.existsSync(indexFile);
const existingContent = exists && fs.readFileSync(indexFile).toString();
const hasActualContent = existingContent && existingContent.includes('isDefaultIndex: false');
if (!exists && !hasActualContent) {
const indexFileContent =
generateFrontMatter(subCategory, true) +
`\n\nimport DocCardList from '@theme/DocCardList';\n\n<DocCardList />`;
fs.writeFileSync(indexFile, indexFileContent);
generatedCount++;
}
}
fs.writeFileSync(path.join(categoryDir, page.fileName + '.md'), markdown);
generatedCount++;
}
return generatedCount;
}
/**
* Render the interface to a markdown string.
*/
private renderInterfaceOrClass(
info: InterfaceInfo | ClassInfo,
knownTypeMap: TypeMap,
docsUrl: string,
): string {
const { title, weight, category, description, members } = info;
let output = '';
output += `\n\n## ${title}\n\n`;
output += this.renderGenerationInfoShortcode(info);
output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
output +=
info.kind === 'interface' ? this.renderInterfaceSignature(info) : this.renderClassSignature(info);
if (info.extendsClause) {
output += '* Extends: ';
output += `${this.renderHeritageClause(info.extendsClause, knownTypeMap, docsUrl)}\n`;
}
if (info.kind === 'class' && info.implementsClause) {
output += '* Implements: ';
output += `${this.renderHeritageClause(info.implementsClause, knownTypeMap, docsUrl)}\n`;
}
if (info.members && info.members.length) {
output += '\n<div className="members-wrapper">\n';
output += `${this.renderMembers(info, knownTypeMap, docsUrl)}\n`;
output += '\n\n</div>\n';
}
return output;
}
/**
* Render the type alias to a markdown string.
*/
private renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: TypeMap, docsUrl: string): string {
const { title, weight, description, type, fullText } = typeAliasInfo;
let output = '';
output += `\n\n## ${title}\n\n`;
output += this.renderGenerationInfoShortcode(typeAliasInfo);
output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
output += this.renderTypeAliasSignature(typeAliasInfo);
if (typeAliasInfo.members && typeAliasInfo.members.length) {
output += '\n<div className="members-wrapper">\n';
output += `${this.renderMembers(typeAliasInfo, knownTypeMap, docsUrl)}\n`;
output += '\n\n</div>\n';
}
return output;
}
private renderEnum(enumInfo: EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
const { title, weight, description, fullText } = enumInfo;
let output = '';
output += `\n\n## ${title}\n\n`;
output += this.renderGenerationInfoShortcode(enumInfo);
output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
output += this.renderEnumSignature(enumInfo);
return output;
}
private renderFunction(functionInfo: FunctionInfo, knownTypeMap: TypeMap, docsUrl: string): string {
const { title, weight, description, fullText, parameters } = functionInfo;
let output = '';
output += `\n\n## ${title}\n\n`;
output += this.renderGenerationInfoShortcode(functionInfo);
output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
output += this.renderFunctionSignature(functionInfo, knownTypeMap);
if (parameters.length) {
output += 'Parameters\n\n';
output += this.renderFunctionParams(parameters, knownTypeMap, docsUrl);
}
return output;
}
private renderVariable(variableInfo: VariableInfo, knownTypeMap: TypeMap, docsUrl: string): string {
const { title, weight, description, fullText } = variableInfo;
let output = '';
output += `\n\n## ${title}\n\n`;
output += this.renderGenerationInfoShortcode(variableInfo);
output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
return output;
}
/**
* Generates a markdown code block string for the interface signature.
*/
private renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
const { fullText, members } = interfaceInfo;
let output = '';
output += '```ts title="Signature"\n';
output += `interface ${fullText} `;
if (interfaceInfo.extendsClause) {
output += interfaceInfo.extendsClause.getText() + ' ';
}
output += '{\n';
output += members.map(member => `${INDENT}${member.fullText}`).join('\n');
output += '\n}\n';
output += '```\n';
return output;
}
private renderClassSignature(classInfo: ClassInfo): string {
const { fullText, members } = classInfo;
let output = '';
output += '```ts title="Signature"\n';
output += `class ${fullText} `;
if (classInfo.extendsClause) {
output += classInfo.extendsClause.getText() + ' ';
}
if (classInfo.implementsClause) {
output += classInfo.implementsClause.getText() + ' ';
}
output += '{\n';
const renderModifiers = (modifiers: string[]) => (modifiers.length ? modifiers.join(' ') + ' ' : '');
output += members
.map(member => {
if (member.kind === 'method') {
const args = member.parameters.map(p => this.renderParameter(p, p.type)).join(', ');
if (member.fullText === 'constructor') {
return `${INDENT}constructor(${args})`;
} else {
return `${INDENT}${member.fullText}(${args}) => ${member.type};`;
}
} else {
return `${INDENT}${member.fullText}`;
}
})
.join('\n');
output += '\n}\n';
output += '```\n';
return output;
}
private renderTypeAliasSignature(typeAliasInfo: TypeAliasInfo): string {
const { fullText, members, type } = typeAliasInfo;
let output = '';
output += '```ts title="Signature"\n';
output += `type ${fullText} = `;
if (members) {
output += '{\n';
output += members.map(member => `${INDENT}${member.fullText}`).join('\n');
output += '\n}\n';
} else {
output += type.getText() + '\n';
}
output += '```\n';
return output;
}
private renderEnumSignature(enumInfo: EnumInfo): string {
const { fullText, members } = enumInfo;
let output = '';
output += '```ts title="Signature"\n';
output += `enum ${fullText} `;
if (members) {
output += '{\n';
output += members
.map(member => {
let line = member.description ? `${INDENT}// ${member.description}\n` : '';
line += `${INDENT}${member.fullText}`;
return line;
})
.join('\n');
output += '\n}\n';
}
output += '```\n';
return output;
}
private renderFunctionSignature(functionInfo: FunctionInfo, knownTypeMap: TypeMap): string {
const { fullText, parameters, type } = functionInfo;
const args = parameters.map(p => this.renderParameter(p, p.type)).join(', ');
let output = '';
output += '```ts title="Signature"\n';
output += `function ${fullText}(${args}): ${type ? type.getText() : 'void'}\n`;
output += '```\n';
return output;
}
private renderFunctionParams(
params: MethodParameterInfo[],
knownTypeMap: TypeMap,
docsUrl: string,
): string {
let output = '';
for (const param of params) {
const type = this.renderType(param.type, knownTypeMap, docsUrl);
output += `### ${param.name}\n\n`;
output += `<MemberInfo kind="parameter" type={\`${type}\`} />\n\n`;
}
return output;
}
private renderMembers(
info: InterfaceInfo | ClassInfo | TypeAliasInfo | EnumInfo,
knownTypeMap: TypeMap,
docsUrl: string,
): string {
const { members, title } = info;
let output = '';
for (const member of members || []) {
let defaultParam = '';
let sinceParam = '';
let experimentalParam = '';
let type = '';
if (member.kind === 'property') {
type = this.renderType(member.type, knownTypeMap, docsUrl);
defaultParam = member.defaultValue
? `default="${this.renderType(member.defaultValue, knownTypeMap, docsUrl)}" `
: '';
} else {
const args = member.parameters
.map(p => this.renderParameter(p, this.renderType(p.type, knownTypeMap, docsUrl)))
.join(', ');
if (member.fullText === 'constructor') {
type = `(${args}) => ${title}`;
} else {
type = `(${args}) => ${this.renderType(member.type, knownTypeMap, docsUrl)}`;
}
}
if (member.since) {
sinceParam = `since="${member.since}" `;
}
if (member.experimental) {
experimentalParam = 'experimental="true"';
}
output += `\n### ${member.name}\n\n`;
output += `<MemberInfo kind="${[member.kind].join(
' ',
)}" type={\`${type}\`} ${defaultParam} ${sinceParam}${experimentalParam} />\n\n`;
output += this.renderDescription(member.description, knownTypeMap, docsUrl);
}
return output;
}
private renderHeritageClause(clause: HeritageClause, knownTypeMap: TypeMap, docsUrl: string) {
return (
clause.types
.map(t => `<code>${this.renderType(t.getText(), knownTypeMap, docsUrl)}</code>`)
.join(', ') + '\n\n'
);
}
private renderParameter(p: MethodParameterInfo, typeString: string): string {
return `${p.name}${p.optional ? '?' : ''}: ${typeString}${
p.initializer ? ` = ${p.initializer}` : ''
}`;
}
private renderGenerationInfoShortcode(info: DeclarationInfo): string {
const sourceFile = info.sourceFile.replace(/^\.\.\//, '');
let sinceData = '';
if (info.since) {
sinceData = ` since="${info.since}"`;
}
let experimental = '';
if (info.experimental) {
experimental = ' experimental="true"';
}
return `<GenerationInfo sourceFile="${sourceFile}" sourceLine="${info.sourceLine}" packageName="${info.packageName}"${sinceData}${experimental} />\n\n`;
}
/**
* This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
* and known types (e.g. "ShippingMethod") into hyperlinks.
*/
private renderType(type: string, knownTypeMap: TypeMap, docsUrl: string): string {
let typeText = type
.trim()
// encode HTML entities
.replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
// remove newlines
.replace(/\n/g, ' ');
for (const [key, val] of knownTypeMap) {
const re = new RegExp(`\\b${key}\\b`, 'g');
const strippedIndex = val.replace(/\/_index$/, '');
typeText = typeText.replace(re, `<a href='${docsUrl}/${strippedIndex}'>${key}</a>`);
}
return typeText;
}
/**
* Replaces any `{@link Foo}` references in the description with hyperlinks.
*/
private renderDescription(description: string, knownTypeMap: TypeMap, docsUrl: string): string {
for (const [key, val] of knownTypeMap) {
const re = new RegExp(`{@link\\s*${key}}`, 'g');
description = description.replace(re, `<a href='${docsUrl}/${val}'>${key}</a>`);
}
return description;
}
}
|
/* eslint-disable no-console */
import { exec } from 'child_process';
import fs from 'fs';
import path from 'path';
getLastCommitHash()
.then(hash => writeBuildInfo(hash))
.then(() => {
console.log('Updated build info');
process.exit(0);
})
.catch(err => {
console.error(err);
process.exit(1);
});
function writeBuildInfo(commitHash: string) {
const corePackageJson = require('../../packages/core/package');
const content = {
version: corePackageJson.version,
commit: commitHash,
};
return new Promise<void>((resolve, reject) => {
fs.writeFile(
path.join(__dirname, '../../docs/data/build.json'),
JSON.stringify(content, null, 2),
err => {
if (err) {
reject(err);
}
resolve();
},
);
});
}
function getLastCommitHash() {
return new Promise<string>((resolve, reject) => {
exec(`git log --pretty=format:'%h' -n 1`, (err, out) => {
if (err) {
reject(err);
}
resolve(out.replace(/'/g, ''));
});
});
}
|