Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(applets): integrate into toolkit #1039

Merged
merged 7 commits into from
Nov 2, 2018
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 63 additions & 41 deletions packages/@aws-cdk/applet-js/bin/cdk-applet-js.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
import 'source-map-support/register';

import cdk = require('@aws-cdk/cdk');
import child_process = require('child_process');
import fs = require('fs-extra');
import os = require('os');
import path = require('path');
import { isStackConstructor, parseApplet } from '../lib/applet-helpers';

// tslint:disable-next-line:no-var-requires
const YAML = require('js-yaml');
Expand All @@ -19,65 +22,84 @@ async function main() {

const appletFile = process.argv[2];
if (!appletFile) {
throw new Error(`Usage: ${progname}| <applet.yaml>`);
throw new Error(`Usage: ${progname} <applet.yaml>`);
}

// read applet properties from the provided file
const props = YAML.safeLoad(await fs.readFile(appletFile, { encoding: 'utf-8' }));
// read applet(s) properties from the provided file
const fileContents = YAML.safeLoad(await fs.readFile(appletFile, { encoding: 'utf-8' }));
if (typeof fileContents !== 'object') {
throw new Error(`${appletFile}: should contain a YAML object`);
}
const appletMap = fileContents.applets;
if (!appletMap) {
throw new Error(`${appletFile}: must have an 'applets' key`);
}

const searchDir = path.dirname(appletFile);
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cdkapplet'));
try {
const app = new cdk.App();

for (const [name, definition] of Object.entries(appletMap)) {
await constructStack(app, searchDir, tempDir, name, definition);
}
app.run();
} finally {
await fs.remove(tempDir);
}
}

/**
* Construct a stack from the given props
* @param props Const
*/
async function constructStack(app: cdk.App, searchDir: string, tempDir: string, stackName: string, spec: any) {
// the 'applet' attribute tells us how to load the applet. in the javascript case
// it will be in the format <module>:<class> where <module> is technically passed to "require"
// and <class> is expected to be exported from the module.
const applet: string = props.applet;
if (!applet) {
throw new Error('Applet file missing "applet" attribute');
const appletSpec: string | undefined = spec.type;
if (!appletSpec) {
throw new Error(`Applet ${stackName} missing "type" attribute`);
}

const { moduleName, className } = parseApplet(applet);

// remove the 'applet' attribute as we pass it along to the applet class.
delete props.applet;
const applet = parseApplet(appletSpec);

const props = spec.properties || {};

if (applet.npmPackage) {
// tslint:disable-next-line:no-console
console.error(`Installing NPM package ${applet.npmPackage}`);
// Magic marker to download this package directly off of NPM
// We're going to run NPM as a shell (since programmatic usage is not stable
// by their own admission) and we're installing into a temporary directory.
// (Installing into a permanent directory is useless since NPM doesn't do
// any real caching anyway).
child_process.execFileSync('npm', ['install', '--prefix', tempDir, '--global', applet.npmPackage], {
stdio: 'inherit'
});
searchDir = path.join(tempDir, 'lib');
}

// we need to resolve the module name relatively to where the applet file is
// and not relative to this module or cwd.
const resolve = require.resolve as any; // escapse type-checking since { paths } is not defined
const modulePath = resolve(moduleName, { paths: [ path.dirname(appletFile) ] });
const modulePath = require.resolve(applet.moduleName, { paths: [ searchDir ] });

// load the module
const pkg = require(modulePath);

// find the applet class within the package
// tslint:disable-next-line:variable-name
const AppletStack = pkg[className];
if (!AppletStack) {
throw new Error(`Cannot find applet class "${className}" in module "${moduleName}"`);
}

// create the CDK app
const app = new cdk.App();

const constructName = props.name || className;

// add the applet stack into the app.
new AppletStack(app, constructName, props);

// transfer control to the app
app.run();
}

function parseApplet(applet: string) {
const components = applet.split(':');
// tslint:disable-next-line:prefer-const
let [ moduleName, className ] = components;

if (components.length > 2 || !moduleName) {
throw new Error(`"applet" value is "${applet}" but it must be in the form "<js-module>[:<applet-class>]".
If <applet-class> is not specified, "Applet" is the default`);
const appletConstructor = pkg[applet.className];
if (!appletConstructor) {
throw new Error(`Cannot find applet class "${applet.className}" in module "${applet.moduleName}"`);
}

if (!className) {
className = 'Applet';
if (isStackConstructor(appletConstructor)) {
// add the applet stack into the app.
new appletConstructor(app, stackName, props);
} else {
// Make a stack THEN add it in
const stack = new cdk.Stack(app, stackName, props);
new appletConstructor(stack, 'Default', props);
}

return { moduleName, className };
}
52 changes: 52 additions & 0 deletions packages/@aws-cdk/applet-js/lib/applet-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* Determine whether this constructorFunction is going to create an object that inherits from Stack
*
* We do structural typing.
*/
export function isStackConstructor(constructorFn: any) {
// Test for a public method that Stack has
return constructorFn.prototype.findResource !== undefined;
}

/**
* Extract module name from a NPM package specification
*/
export function extractModuleName(packageSpec: string) {
const m = /^((?:@[a-zA-Z-]+\/)?[a-zA-Z-]+)/i.exec(packageSpec);
if (!m) { throw new Error(`Could not find package name in ${packageSpec}`); }
return m[1];
}

export function parseApplet(applet: string): AppletSpec {
const m = /^(npm:\/\/)?([a-z0-9_@./-]+)(:[a-z_0-9]+)?$/i.exec(applet);
if (!m) {
throw new Error(`"applet" value is "${applet}" but it must be in the form "[npm://]<js-module>[:<applet-class>]".
If <applet-class> is not specified, "Applet" is the default`);
}

if (m[1] === 'npm://') {
return {
npmPackage: m[2],
moduleName: extractModuleName(m[2]),
className: className(m[3]),
};
} else {
return {
moduleName: m[2],
className: className(m[3]),
};
}

function className(s: string | undefined) {
if (s) {
return s.substr(1);
}
return 'Applet';
}
}

export interface AppletSpec {
npmPackage?: string;
moduleName: string;
className: string;
}
Loading