@byaga/cdk-patterns 0.8.5 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/RestApi.ts DELETED
@@ -1,180 +0,0 @@
1
- import {
2
- BasePathMapping,
3
- ContentHandling,
4
- DomainName,
5
- EndpointType,
6
- IDomainName,
7
- IResource,
8
- MockIntegration,
9
- RestApi as RestApiBase
10
- } from "aws-cdk-lib/aws-apigateway";
11
- import {DeployStack} from "./DeployStack"
12
- import {ICorsConfig} from "./ICorsConfig";
13
- import {Duration, Size} from "aws-cdk-lib";
14
- import {Effect, Policy, PolicyStatement, Role} from "aws-cdk-lib/aws-iam";
15
-
16
- interface IRestApiConfig {
17
- cors?: ICorsConfig,
18
- allowCredentials: boolean
19
- }
20
-
21
- interface IBasePathMappingConfig {
22
- domain?: IDomainName,
23
- domainName?: string,
24
- hostedZoneId?: string
25
- }
26
-
27
- interface IResourceNode {
28
- children: { [key: string]: IResourceNode }
29
- node: IResource
30
- }
31
-
32
- const DEFAULT_EXPOSE_HEADERS = ['Date']
33
-
34
- export class RestApi extends RestApiBase {
35
- _id: string
36
- _tree: IResourceNode
37
-
38
-
39
- constructor(stack: DeployStack, id: string, props: IRestApiConfig) {
40
- const {stage} = stack
41
-
42
- console.log('Defining Rest API', stack.genId(id, 'api'))
43
-
44
- const cors: ICorsConfig = props.cors || {}
45
- const allowOrigins: string[] = Array.isArray(cors.allowOrigin) ? cors.allowOrigin : [cors.allowOrigin || '*']
46
- super(stack, stack.genId(id, 'api'), {
47
- restApiName: stack.genName('api'),
48
- deploy: true,
49
- deployOptions: {
50
- stageName: stage,
51
- tracingEnabled: true
52
- },
53
- minCompressionSize: Size.bytes(1000),
54
- endpointConfiguration: {
55
- types: [EndpointType.EDGE]
56
- },
57
- defaultCorsPreflightOptions: {
58
- allowHeaders: ['*'],
59
- allowMethods: ['*'],
60
- allowCredentials: props.allowCredentials,
61
- allowOrigins,
62
- maxAge: Duration.seconds(cors.maxAge || 86400),
63
- exposeHeaders: cors.exposeHeaders || DEFAULT_EXPOSE_HEADERS
64
- }
65
- })
66
- this._id = id
67
-
68
- // APIs MUST have at least one endpoint, so this will give it one
69
- console.log('Adding health endpoint', '/health')
70
- const health = this.root.addResource('health')
71
- health.addMethod("GET", new MockIntegration({
72
- requestTemplates: {
73
- "application/json": "{\"statusCode\": 200}"
74
- },
75
- integrationResponses: [{
76
- statusCode: '200',
77
- contentHandling: ContentHandling.CONVERT_TO_TEXT,
78
- responseTemplates: {
79
- 'application/json': `
80
- ## See http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
81
- ## This template will pass through all parameters including path, querystring, header, stage variables, and context through to the integration endpoint via the body/payload
82
- #set($allParams = $input.params())
83
- {
84
- "body-json" : $input.json('$'),
85
- "params" : {
86
- #foreach($type in $allParams.keySet())
87
- #set($params = $allParams.get($type))
88
- "$type" : {
89
- #foreach($paramName in $params.keySet())
90
- "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
91
- #if($foreach.hasNext),#end
92
- #end
93
- }
94
- #if($foreach.hasNext),#end
95
- #end
96
- },
97
- "stage-variables" : {
98
- #foreach($key in $stageVariables.keySet())
99
- "$key" : "$util.escapeJavaScript($stageVariables.get($key))"
100
- #if($foreach.hasNext),#end
101
- #end
102
- },
103
- "context" : {
104
- "account-id" : "$context.identity.accountId",
105
- "api-id" : "$context.apiId",
106
- "api-key" : "$context.identity.apiKey",
107
- "authorizer-principal-id" : "$context.authorizer.principalId",
108
- "caller" : "$context.identity.caller",
109
- "cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider",
110
- "cognito-authentication-type" : "$context.identity.cognitoAuthenticationType",
111
- "cognito-identity-id" : "$context.identity.cognitoIdentityId",
112
- "cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId",
113
- "http-method" : "$context.httpMethod",
114
- "stage" : "$context.stage",
115
- "source-ip" : "$context.identity.sourceIp",
116
- "user" : "$context.identity.user",
117
- "user-agent" : "$context.identity.userAgent",
118
- "user-arn" : "$context.identity.userArn",
119
- "request-id" : "$context.requestId",
120
- "resource-id" : "$context.resourceId",
121
- "resource-path" : "$context.resourcePath"
122
- }
123
- }`
124
- }
125
- }]
126
- }), {
127
- methodResponses: [{statusCode: "200"}]
128
- })
129
-
130
- this._tree = {node: this.root, children: {}}
131
- }
132
-
133
- addBasePathMapping(stack: DeployStack, config: IBasePathMappingConfig) {
134
- let domain = config.domain
135
- if (!domain && config.domainName && config.hostedZoneId) {
136
- domain = DomainName.fromDomainNameAttributes(stack, stack.genName('domain-name'), {
137
- domainName: config.domainName,
138
- domainNameAliasHostedZoneId: config.hostedZoneId,
139
- domainNameAliasTarget: this.restApiRootResourceId
140
- })
141
- }
142
- if (!domain) throw new Error('Missing Domain Configuration For Base Path Mapping')
143
-
144
- new BasePathMapping(stack, stack.genId(this._id, 'base-path-mapping'), {
145
- domainName: domain,
146
- stage: this.deploymentStage,
147
- restApi: this,
148
- basePath: this._id
149
- })
150
- }
151
-
152
- addAuthorizedRole(stack: DeployStack, roleArn: string): PolicyStatement {
153
- const policyStatement = new PolicyStatement({
154
- effect: Effect.ALLOW,
155
- actions: ['execute-api:Invoke']
156
- })
157
-
158
- const authRole = Role.fromRoleArn(stack, stack.genId('authenticated-role'), roleArn)
159
- authRole.attachInlinePolicy(new Policy(stack, stack.genId('api-access-policy'), {
160
- statements: [policyStatement]
161
- }))
162
- return policyStatement;
163
- }
164
-
165
- path(uri: string): IResource {
166
- const {node} = uri.split('/')
167
- .filter(path => !!path)
168
- .reduce((resource, path) => {
169
- if (!resource.children[path]) {
170
- resource.children[path] = {
171
- children: {},
172
- node: resource.node.addResource(path)
173
- }
174
- }
175
- return resource.children[path];
176
- }, this._tree);
177
-
178
- return node
179
- }
180
- }
package/src/Role.ts DELETED
@@ -1,165 +0,0 @@
1
- import {FederatedPrincipal, IPrincipal, Role as CdkRole} from "aws-cdk-lib/aws-iam";
2
- import {Duration} from "aws-cdk-lib";
3
- import {Output} from './Output'
4
- import {DeployStack} from "./DeployStack";
5
- import {IManagedPolicy} from "aws-cdk-lib/aws-iam/lib/managed-policy";
6
- import {PolicyDocument} from "aws-cdk-lib/aws-iam/lib/policy-document";
7
-
8
- interface IRoleProps {
9
- identityPool: string,
10
- amr: string,
11
- /**
12
- * The IAM principal (i.e. `new ServicePrincipal('sns.amazonaws.com')`) which can assume this role.
13
- *
14
- * You can later modify the assume role policy document by accessing it via
15
- * the `assumeRolePolicy` property.
16
- *
17
- * @stability stable
18
- */
19
- assumedBy?: IPrincipal,
20
-
21
- /**
22
- * (deprecated) ID that the role assumer needs to provide when assuming this role.
23
- *
24
- * If the configured and provided external IDs do not match, the
25
- * AssumeRole operation will fail.
26
- *
27
- * @default No external ID required
28
- * @deprecated see {@link externalIds}
29
- */
30
- readonly externalId?: string;
31
- /**
32
- * List of IDs that the role assumer needs to provide one of when assuming this role.
33
- *
34
- * If the configured and provided external IDs do not match, the
35
- * AssumeRole operation will fail.
36
- *
37
- * @default No external ID required
38
- * @stability stable
39
- */
40
- readonly externalIds?: string[];
41
- /**
42
- * A list of managed policies associated with this role.
43
- *
44
- * You can add managed policies later using
45
- * `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`.
46
- *
47
- * @default - No managed policies.
48
- * @stability stable
49
- */
50
- readonly managedPolicies?: IManagedPolicy[];
51
- /**
52
- * A list of named policies to inline into this role.
53
- *
54
- * These policies will be
55
- * created with the role, whereas those added by ``addToPolicy`` are added
56
- * using a separate CloudFormation resource (allowing a way around circular
57
- * dependencies that could otherwise be introduced).
58
- *
59
- * @default - No policy is inlined in the Role resource.
60
- * @stability stable
61
- */
62
- readonly inlinePolicies?: {
63
- [name: string]: PolicyDocument;
64
- };
65
- /**
66
- * The path associated with this role.
67
- *
68
- * For information about IAM paths, see
69
- * Friendly Names and Paths in IAM User Guide.
70
- *
71
- * @default /
72
- * @stability stable
73
- */
74
- readonly path?: string;
75
- /**
76
- * AWS supports permissions boundaries for IAM entities (users or roles).
77
- *
78
- * A permissions boundary is an advanced feature for using a managed policy
79
- * to set the maximum permissions that an identity-based policy can grant to
80
- * an IAM entity. An entity's permissions boundary allows it to perform only
81
- * the actions that are allowed by both its identity-based policies and its
82
- * permissions boundaries.
83
- *
84
- * @default - No permissions boundary.
85
- * @stability stable
86
- * @link https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html
87
- */
88
- readonly permissionsBoundary?: IManagedPolicy;
89
- /**
90
- * A name for the IAM role.
91
- *
92
- * For valid values, see the RoleName parameter for
93
- * the CreateRole action in the IAM API Reference.
94
- *
95
- * IMPORTANT: If you specify a name, you cannot perform updates that require
96
- * replacement of this resource. You can perform updates that require no or
97
- * some interruption. If you must replace the resource, specify a new name.
98
- *
99
- * If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to
100
- * acknowledge your template's capabilities. For more information, see
101
- * Acknowledging IAM Resources in AWS CloudFormation Templates.
102
- *
103
- * @default - AWS CloudFormation generates a unique physical ID and uses that ID
104
- * for the role name.
105
- * @stability stable
106
- */
107
- readonly roleName?: string;
108
- /**
109
- * The maximum session duration that you want to set for the specified role.
110
- *
111
- * This setting can have a value from 1 hour (3600sec) to 12 (43200sec) hours.
112
- *
113
- * Anyone who assumes the role from the AWS CLI or API can use the
114
- * DurationSeconds API parameter or the duration-seconds CLI parameter to
115
- * request a longer session. The MaxSessionDuration setting determines the
116
- * maximum duration that can be requested using the DurationSeconds
117
- * parameter.
118
- *
119
- * If users don't specify a value for the DurationSeconds parameter, their
120
- * security credentials are valid for one hour by default. This applies when
121
- * you use the AssumeRole* API operations or the assume-role* CLI operations
122
- * but does not apply when you use those operations to create a console URL.
123
- *
124
- * @default Duration.hours(1)
125
- * @stability stable
126
- * @link https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html
127
- */
128
- readonly maxSessionDuration?: Duration;
129
- /**
130
- * A description of the role.
131
- *
132
- * It can be up to 1000 characters long.
133
- *
134
- * @default - No description.
135
- * @stability stable
136
- */
137
- readonly description?: string;
138
- }
139
-
140
- export class Role extends CdkRole {
141
- constructor(stack: DeployStack, id: string, props: IRoleProps) {
142
- console.log('Defining Role', stack.genId(id))
143
- if (!props.assumedBy) {
144
- props.assumedBy = new FederatedPrincipal(
145
- 'cognito-identity.amazonaws.com',
146
- {
147
- StringEquals: {
148
- 'cognito-identity.amazonaws.com:aud': props.identityPool
149
- },
150
- "ForAnyValue:StringLike": {
151
- 'cognito-identity.amazonaws.com:amr': props.amr
152
- }
153
- },
154
- 'sts:AssumeRoleWithWebIdentity'
155
- )
156
- }
157
-
158
- super(stack, stack.genId(id), {
159
- ...props,
160
- roleName: stack.genName(props.roleName || id),
161
- assumedBy: props.assumedBy
162
- })
163
- new Output(stack, `${id}-arn`, this.roleArn)
164
- }
165
- }
@@ -1,47 +0,0 @@
1
- import {DeployStack} from "./DeployStack";
2
- import {IStringParameter, StringParameter} from "aws-cdk-lib/aws-ssm";
3
- import {Effect, IGrantable, PolicyStatement} from "aws-cdk-lib/aws-iam";
4
- import {IKey} from "aws-cdk-lib/aws-kms";
5
-
6
- const paramCache: { [name: string]: IStringParameter } = {}
7
-
8
- interface SsmParameterOptions {
9
- decryptWithKey?: IKey
10
- }
11
-
12
- export class SsmParameter {
13
- parameterName: string
14
- parameterArn: string
15
- decryptWithKey?: IKey
16
- _stack: DeployStack
17
-
18
- constructor(stack: DeployStack, name: string, options?: SsmParameterOptions) {
19
- if (name[0] !== '/') name = '/' + name
20
- this.parameterName = `/${stack.name}${name}`;
21
- this.parameterArn = `arn:aws:ssm:${stack.region}:${stack.account}:parameter${this.parameterName}`
22
- this._stack = stack;
23
- this.decryptWithKey = options?.decryptWithKey
24
- }
25
-
26
- grantRead(grantee: IGrantable) {
27
- grantee.grantPrincipal.addToPrincipalPolicy(new PolicyStatement({
28
- effect: Effect.ALLOW,
29
- actions: ['ssm:GetParameter'],
30
- resources: [this.parameterArn]
31
- }))
32
- if (this.decryptWithKey) {
33
- this.decryptWithKey.grantDecrypt(grantee)
34
- }
35
- }
36
-
37
- get stringValue() {
38
- return this.getParameter().stringValue
39
- }
40
-
41
- getParameter() {
42
- if (!paramCache[this.parameterArn]) {
43
- paramCache[this.parameterArn] = StringParameter.fromStringParameterName(this._stack, this._stack.genId(this.parameterName.substring(1).replace('/', '_')), this.parameterName)
44
- }
45
- return paramCache[this.parameterArn]
46
- }
47
- }
@@ -1,99 +0,0 @@
1
- import {RemovalPolicy} from "aws-cdk-lib/core";
2
- import {Output} from './Output'
3
- import {DeployStack} from "./DeployStack";
4
- import {execSync} from "child_process";
5
- import * as fs from 'fs-extra'
6
- import * as path from 'path'
7
- import {Bucket} from "aws-cdk-lib/aws-s3"
8
- import {BucketDeployment, Source} from "aws-cdk-lib/aws-s3-deployment"
9
- import ApiCertificate from "./ApiCertificate";
10
- import {
11
- CloudFrontAllowedMethods,
12
- CloudFrontWebDistribution,
13
- OriginAccessIdentity,
14
- SSLMethod,
15
- ViewerCertificate,
16
- ViewerProtocolPolicy
17
- } from "aws-cdk-lib/aws-cloudfront"
18
- import IDomainConfig from "./IDomainConfig";
19
- import {PolicyStatement} from "aws-cdk-lib/aws-iam";
20
- import {ARecord, RecordTarget} from "aws-cdk-lib/aws-route53";
21
- import {CloudFrontTarget} from "aws-cdk-lib/aws-route53-targets";
22
-
23
- interface StaticWebSiteConfig {
24
- srcDir?: string,
25
- domain: IDomainConfig,
26
- env: NodeJS.ProcessEnv
27
- }
28
-
29
- export class StaticWebSite {
30
- constructor(stack: DeployStack, id: string, props: StaticWebSiteConfig) {
31
- console.log('Deploying Static Web Site', id)
32
- const srcDir = path.resolve("../src/", props.srcDir || '')
33
- const buildDir = path.resolve("../dist/", props.srcDir || '')
34
-
35
- console.log('Installing Prod Dependencies', id)
36
- execSync('npm i --production --quiet', {
37
- cwd: srcDir
38
- })
39
- console.log('Building UI Source', id)
40
- execSync('npm run export', {
41
- cwd: srcDir,
42
- //env: props.env
43
- })
44
- fs.copySync(path.resolve(srcDir, "./out"), buildDir);
45
-
46
- console.log('Creating HTTPS Certificate', id + '-certificate')
47
- const certificate = new ApiCertificate(stack, id + '-certificate', props.domain);
48
- console.log('Deploying Site Content Bucket', stack.genId(id, "content-bucket"))
49
- const s3BucketSource = new Bucket(stack, stack.genId(id, "content-bucket"), {
50
- bucketName: certificate.domain,
51
- websiteIndexDocument: "index.html",
52
- websiteErrorDocument: "error.html",
53
- publicReadAccess: true,
54
- removalPolicy: RemovalPolicy.DESTROY,
55
- autoDeleteObjects: true
56
- });
57
- new Output(stack, `${id}-content-bucket`, s3BucketSource.bucketName);
58
-
59
- const cloudFrontPolicy = new PolicyStatement({
60
- actions: ['s3:GetBucket*', 's3:GetObject*', 's3:List*'],
61
- resources: [s3BucketSource.bucketArn, s3BucketSource.bucketArn + '/*'],
62
- })
63
-
64
- new BucketDeployment(stack, stack.genId(id, 'bucket-deployment'), {
65
- sources: [Source.asset(buildDir)],
66
- destinationBucket: s3BucketSource
67
- })
68
- const originAccessIdentity = new OriginAccessIdentity(stack, "WebsiteOAI");
69
- cloudFrontPolicy.addArnPrincipal(originAccessIdentity.cloudFrontOriginAccessIdentityS3CanonicalUserId)
70
-
71
- const distro = new CloudFrontWebDistribution(stack, stack.genId(id, 'cloudfront-web-distribution'), {
72
- enabled: true,
73
- //priceClass:
74
- originConfigs: [{
75
- s3OriginSource: {
76
- s3BucketSource,
77
- originAccessIdentity
78
- },
79
- behaviors: [{
80
- allowedMethods: CloudFrontAllowedMethods.GET_HEAD_OPTIONS,
81
- isDefaultBehavior: true
82
- }]
83
- }],
84
- viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
85
- viewerCertificate: ViewerCertificate.fromAcmCertificate(certificate, {
86
- aliases: [certificate.domain],
87
- sslMethod: SSLMethod.SNI
88
- })
89
- })
90
- new Output(stack, `${id}-base-url`, "https://" + certificate.domain);
91
-
92
- console.log('Setting Route53 A-Name Record', props.domain.domainName)
93
- new ARecord(stack, stack.genId('alias'), {
94
- zone: certificate.hostedZone,
95
- recordName: certificate.domain,
96
- target: RecordTarget.fromAlias(new CloudFrontTarget(distro))
97
- })
98
- }
99
- }
package/src/index.ts DELETED
@@ -1,15 +0,0 @@
1
- export {ApiCertificate} from "./ApiCertificate";
2
- export {CognitoApiGatewayAuthorizer} from "./CognitoApiGatewayAuthorizer";
3
- export {DeployStack} from "./DeployStack";
4
- export {DynamoDbTable} from "./DynamoDbTable";
5
- export {FunctionIntegration} from "./FunctionIntegration";
6
- export {IHostedZoneConfig} from "./IHostedZoneConfig";
7
- export {IDomainConfig} from "./IDomainConfig";
8
- export {IStackArguments} from "./IStackArguments";
9
- export {NodeJsLambda} from "./NodeJsLambda";
10
- export {NodeJsLambdaLayer} from "./NodeJsLambdaLayer";
11
- export {Output} from "./Output";
12
- export {RestApi} from "./RestApi";
13
- export {Role} from "./Role";
14
- export {SsmParameter} from "./SsmParameter";
15
- export {StaticWebSite} from "./StaticWebSite";
@@ -1,22 +0,0 @@
1
- import {FunctionProps, ILayerVersion, LayerVersion} from "aws-cdk-lib/aws-lambda"
2
- import {DeployStack} from "../DeployStack";
3
- import {SsmParameter} from "../SsmParameter";
4
-
5
- let honeyCombLayer: ILayerVersion
6
- export function applyHoneycombToLambda(stack: DeployStack, props: FunctionProps): FunctionProps {
7
- if (!honeyCombLayer) honeyCombLayer = LayerVersion.fromLayerVersionArn(stack, stack.genId('hc-layer'), `arn:aws:lambda:${stack.region}:702835727665:layer:honeycomb-lambda-extension-x86_64-v11-1-1:1`)
8
-
9
- const layers = props.layers ? [...props.layers] : []
10
- const environment = props.environment || {}
11
-
12
- layers.push(honeyCombLayer)
13
- environment.LIBHONEY_API_KEY = new SsmParameter(stack, `/honeycomb/api-key`).stringValue
14
- environment.LIBHONEY_DATASET =new SsmParameter(stack, `/honeycomb/dataset`).stringValue
15
- environment.LOGS_API_DISABLE_PLATFORM_MSGS = "true"
16
-
17
- return {
18
- ...props,
19
- layers,
20
- environment
21
- }
22
- }
@@ -1,97 +0,0 @@
1
- import * as path from 'path'
2
- import * as fse from "fs-extra";
3
- import * as fs from "fs";
4
- import {execSync} from "child_process";
5
- import {generateHash, HashResult} from "./generate-hash"
6
- import {getBuildDirectory, getSourceDirectory} from './get-source-directory'
7
- import duration from "./duration";
8
- import emptyDirSync from './empty-directory'
9
- import {IIgnoreOptions} from "./walk-directory";
10
-
11
- const distributionRoot = path.resolve(process.cwd(), "../dist")
12
- const hashRoot = path.join(distributionRoot, "hash")
13
- fse.ensureDirSync(hashRoot)
14
-
15
- export const defaultIgnore: IIgnoreOptions = {
16
- included: (p: fs.Dirent): boolean => {
17
- return !p.name.startsWith(".") &&
18
- !p.name.endsWith(".md") &&
19
- !p.name.includes(".test.") &&
20
- p.name !== 'package-lock.json';
21
- },
22
- childrenIncluded: (p: fs.Dirent): boolean => {
23
- return p.name === "node_modules";
24
- }
25
- } as IIgnoreOptions
26
-
27
- interface IBuildOptions {
28
- dir?: string,
29
- ignore?: IIgnoreOptions
30
- }
31
-
32
- export function buildNodeSource(type: string, id: string, options: IBuildOptions = {}): {
33
- buildDir: string,
34
- moduleChanged: boolean,
35
- packageChanged: boolean,
36
- sourceChanged: boolean
37
- } {
38
- const {dir = ''} = options
39
- const ignore = {
40
- ...defaultIgnore, ...options.ignore
41
- }
42
- const srcDir = getSourceDirectory(type, id)
43
- const buildDir = getBuildDirectory(type, id)
44
- const hashFilePath = path.join(hashRoot, `${type}-${id}-hash.txt`)
45
-
46
- const folderExists = fs.existsSync(buildDir)
47
- const hashFileExists = folderExists && fse.existsSync(hashFilePath)
48
- const prevHash: HashResult = (hashFileExists ? fse.readJsonSync(hashFilePath) : {}) as HashResult
49
- const hash: string = generateHash(srcDir, {ignore});
50
- const nextHash: HashResult = JSON.parse(generateHash(srcDir, {ignore})) as HashResult;
51
- const moduleChanged = JSON.stringify(prevHash, null, '\t') !== hash;
52
- let packageChanged = false, sourceChanged = false;
53
-
54
- if (moduleChanged) {
55
- const prevPackageHash = findPackageHash(prevHash);
56
- const packageHash = findPackageHash(nextHash);
57
- packageChanged = prevPackageHash !== packageHash;
58
-
59
- sourceChanged = sourceWasUpdated(prevHash, nextHash);
60
- if (sourceChanged) {
61
- const rmComplete = duration()
62
- if (folderExists) emptyDirSync(buildDir, {childrenExcluded: folder => folder.name === 'node_modules'})
63
- console.log('Cleanup Duration (ms)', rmComplete())
64
-
65
- const copyComplete = duration()
66
- fse.copySync(srcDir, buildDir, {
67
- filter: src => !~src.indexOf("node_modules") && !src.endsWith('.test.js')
68
- });
69
- console.log('Copy Duration (ms)', copyComplete())
70
- }
71
-
72
- if (packageChanged) {
73
- const installComplete = duration()
74
- execSync("npm i --omit=dev --omit=optional --omit=peer --quite", {
75
- cwd: dir ? path.resolve(buildDir, dir) : buildDir
76
- });
77
- console.log('NPM Install Duration (ms)', installComplete())
78
- }
79
- fs.writeFileSync(hashFilePath, hash);
80
- }
81
-
82
- return {buildDir, packageChanged, sourceChanged, moduleChanged}
83
- }
84
-
85
- function findPackageHash(hash: HashResult): string | undefined {
86
- return hash?.children?.find(file => file.name === 'package.json')?.hash;
87
- }
88
-
89
- function sourceWasUpdated(prevHash: HashResult, nextHash: HashResult): boolean {
90
- const fileCountChanged = prevHash.children?.length != nextHash.children?.length
91
- const updatedItem = prevHash.children?.find(prevFile => {
92
- const nextFile = nextHash.children?.find(f => f.name = prevFile.name);
93
- return prevFile.name !== 'package.json' && (!nextFile || nextFile.hash !== prevFile.hash)
94
- });
95
-
96
- return fileCountChanged || !!updatedItem
97
- }
@@ -1,24 +0,0 @@
1
- const hrDuration = () => {
2
- const startTime: [number, number] = process.hrtime();
3
- const onEnd = function duration(): number {
4
- const hrTime:[number, number] = process.hrtime(startTime);
5
- return hrTime[0] * 1000 + hrTime[1] / 1000000;
6
- };
7
- onEnd.time = startTime;
8
-
9
- return onEnd;
10
- };
11
- const msDuration = () => {
12
- const startTime: number = Date.now();
13
- const onEnd = function duration(): number {
14
- return Date.now() - startTime;
15
- };
16
- onEnd.time = startTime;
17
-
18
- return onEnd;
19
- };
20
-
21
- // @ts-ignore
22
- const duration= process.hrtime ? hrDuration : msDuration
23
-
24
- export default duration
@@ -1,19 +0,0 @@
1
- import * as fse from "fs-extra";
2
- import duration from "./duration";
3
- import walkDirectory, {DirentExtended, IIgnoreOptions} from "./walk-directory";
4
-
5
- export default function emptyDirSync(parentFolder: string, options: IIgnoreOptions) {
6
- const rmComplete = duration()
7
- const files = walkDirectory(parentFolder, options);
8
-
9
- files
10
- .forEach((file:DirentExtended) => {
11
- try {
12
- fse.removeSync(file.fullpath());
13
- console.log('Deleted file:', file.fullpath());
14
- } catch (err) {
15
- console.error('Error deleting file:', err);
16
- }
17
- });
18
- console.log('Empty Directory Complete (ms)', parentFolder, rmComplete())
19
- }