Skip to content

Commit

Permalink
chore: tsconfig.json updates (floydspace#408)
Browse files Browse the repository at this point in the history
* chore(deps): updated dependencies

* chore: updated TS config

- updated `target` to match `package.json` `engines.node`
- enabled `strict`

* chore: added types for `bestzip`

* chore: `strict` updates

* test: updated snapshots

* chore: removed commented code
  • Loading branch information
webdeveric authored Dec 27, 2022
1 parent 698930a commit 6172b65
Show file tree
Hide file tree
Showing 25 changed files with 519 additions and 234 deletions.
2 changes: 1 addition & 1 deletion e2e/__snapshots__/complete.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`complete 1`] = `
"var e=Object.create;var a=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var l=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty;var c=(i,n)=>{for(var s in n)a(i,s,{get:n[s],enumerable:!0})},o=(i,n,s,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of f(n))!u.call(i,t)&&t!==s&&a(i,t,{get:()=>n[t],enumerable:!(r=I(n,t))||r.enumerable});return i};var g=(i,n,s)=>(s=i!=null?e(l(i)):{},o(n||!i||!i.__esModule?a(s,"default",{value:i,enumerable:!0}):s,i)),m=i=>o(a({},"__esModule",{value:!0}),i);var y={};c(y,{handler:()=>p});module.exports=m(y);var d=g(require("isin-validator"));async function p(i){let n=(0,d.default)(i);return{statusCode:200,body:JSON.stringify({message:n?"ISIN is invalid!":"ISIN is fine!",input:i})}}0&&(module.exports={handler});
""use strict";var e=Object.create;var a=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var l=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty;var c=(i,n)=>{for(var s in n)a(i,s,{get:n[s],enumerable:!0})},o=(i,n,s,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of f(n))!u.call(i,t)&&t!==s&&a(i,t,{get:()=>n[t],enumerable:!(r=I(n,t))||r.enumerable});return i};var g=(i,n,s)=>(s=i!=null?e(l(i)):{},o(n||!i||!i.__esModule?a(s,"default",{value:i,enumerable:!0}):s,i)),m=i=>o(a({},"__esModule",{value:!0}),i);var y={};c(y,{handler:()=>p});module.exports=m(y);var d=g(require("isin-validator"));async function p(i){let n=(0,d.default)(i);return{statusCode:200,body:JSON.stringify({message:n?"ISIN is invalid!":"ISIN is fine!",input:i})}}0&&(module.exports={handler});
"
`;

Expand Down
8 changes: 4 additions & 4 deletions e2e/__snapshots__/individually.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`individually 1`] = `
"var l=Object.create;var n=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var m=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty;var u=(e,s)=>n(e,"name",{value:s,configurable:!0});var p=(e,s)=>{for(var o in s)n(e,o,{get:s[o],enumerable:!0})},c=(e,s,o,r)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of f(s))!d.call(e,t)&&t!==o&&n(e,t,{get:()=>s[t],enumerable:!(r=a(s,t))||r.enumerable});return e};var y=(e,s,o)=>(o=e!=null?l(m(e)):{},c(s||!e||!e.__esModule?n(o,"default",{value:e,enumerable:!0}):o,e)),g=e=>c(n({},"__esModule",{value:!0}),e);var S={};p(S,{handler:()=>x});module.exports=g(S);var i=y(require("lodash"));async function x(e,s,o){console.log(i.VERSION),await new Promise(t=>setTimeout(t,500));let r={statusCode:200,body:JSON.stringify({message:"Go Serverless v1.0! Your function executed successfully!",input:e})};o(null,r)}u(x,"handler");0&&(module.exports={handler});
""use strict";var l=Object.create;var n=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var m=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty;var u=(e,s)=>n(e,"name",{value:s,configurable:!0});var p=(e,s)=>{for(var o in s)n(e,o,{get:s[o],enumerable:!0})},c=(e,s,o,r)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of f(s))!d.call(e,t)&&t!==o&&n(e,t,{get:()=>s[t],enumerable:!(r=a(s,t))||r.enumerable});return e};var y=(e,s,o)=>(o=e!=null?l(m(e)):{},c(s||!e||!e.__esModule?n(o,"default",{value:e,enumerable:!0}):o,e)),g=e=>c(n({},"__esModule",{value:!0}),e);var S={};p(S,{handler:()=>x});module.exports=g(S);var i=y(require("lodash"));async function x(e,s,o){console.log(i.VERSION),await new Promise(t=>setTimeout(t,500));let r={statusCode:200,body:JSON.stringify({message:"Go Serverless v1.0! Your function executed successfully!",input:e})};o(null,r)}u(x,"handler");0&&(module.exports={handler});
"
`;

exports[`individually 2`] = `
"var u=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var r=Object.getOwnPropertyNames;var a=Object.prototype.hasOwnProperty;var c=(s,e)=>u(s,"name",{value:e,configurable:!0});var l=(s,e)=>{for(var n in e)u(s,n,{get:e[n],enumerable:!0})},d=(s,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of r(e))!a.call(s,t)&&t!==n&&u(s,t,{get:()=>e[t],enumerable:!(o=i(e,t))||o.enumerable});return s};var f=s=>d(u({},"__esModule",{value:!0}),s);var m={};l(m,{handler:()=>y});module.exports=f(m);async function y(s,e,n){await new Promise(t=>setTimeout(t,500));let o={statusCode:200,body:JSON.stringify({message:"Go Serverless v1.0! Your function executed successfully!",input:s})};n(null,o)}c(y,"handler");0&&(module.exports={handler});
""use strict";var u=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var r=Object.getOwnPropertyNames;var a=Object.prototype.hasOwnProperty;var c=(s,e)=>u(s,"name",{value:e,configurable:!0});var l=(s,e)=>{for(var n in e)u(s,n,{get:e[n],enumerable:!0})},d=(s,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of r(e))!a.call(s,t)&&t!==n&&u(s,t,{get:()=>e[t],enumerable:!(o=i(e,t))||o.enumerable});return s};var f=s=>d(u({},"__esModule",{value:!0}),s);var m={};l(m,{handler:()=>y});module.exports=f(m);async function y(s,e,n){await new Promise(t=>setTimeout(t,500));let o={statusCode:200,body:JSON.stringify({message:"Go Serverless v1.0! Your function executed successfully!",input:s})};n(null,o)}c(y,"handler");0&&(module.exports={handler});
"
`;

Expand Down Expand Up @@ -267,7 +267,7 @@ exports[`individually 5`] = `
},
"Type": "AWS::Lambda::Permission",
},
"Hello1LambdaVersionp3wHp8JuRi4SmdELmNVzjQvueXFr127Qn2aIb5O9YHU": {
"Hello1LambdaVersionCSwh1ndXXWK0PuziFcAZEvHblwz5E8ZASq6DpWhA": {
"DeletionPolicy": "Retain",
"Properties": {
"CodeSha256": Any<String>,
Expand Down Expand Up @@ -345,7 +345,7 @@ exports[`individually 5`] = `
},
"Type": "AWS::Lambda::Permission",
},
"Hello2LambdaVersionongx6o4TBoQbh3kyG4cSG0Bj7rT3CNaL1NNKJ5gGiI": {
"Hello2LambdaVersionwMMe1vFJ1KSlA5MihlkJVM5uJp72R4R6u5Vtbnz3NSY": {
"DeletionPolicy": "Retain",
"Properties": {
"CodeSha256": Any<String>,
Expand Down
5 changes: 3 additions & 2 deletions e2e/__snapshots__/minimal.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`minimal 1`] = `
"var __getOwnPropNames = Object.getOwnPropertyNames;
""use strict";
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
Expand Down Expand Up @@ -14265,7 +14266,7 @@ exports[`minimal 4`] = `
},
"Type": "AWS::Lambda::Permission",
},
"ValidateIsinLambdaVersionGmMQZiArm4DPeKSFh1p52LaTpYXcVfaCai5ZLRw": {
"ValidateIsinLambdaVersionEpft2h1OOZyD03CU8JMaqcj3Xcth3KeWrSuKw8G2UQ": {
"DeletionPolicy": "Retain",
"Properties": {
"CodeSha256": Any<String>,
Expand Down
6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,13 @@
},
"main": "dist/index.js",
"files": [
"dist",
"package.json",
"README.md"
"dist"
],
"scripts": {
"prepublishOnly": "npm run build",
"precommit": "npm run test",
"prebuild": "npm run clean",
"build": "tsc",
"build": "tsc -p ./tsconfig.build.json",
"dev": "npm run build -- --watch",
"typecheck": "tsc --noEmit",
"clean": "rm -rf ./dist",
Expand Down
112 changes: 70 additions & 42 deletions src/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,71 +4,92 @@ import pMap from 'p-map';
import path from 'path';
import { uniq } from 'ramda';

import EsbuildServerlessPlugin from '.';
import { isESM } from './helper';
import { FileBuildResult } from './types';
import type EsbuildServerlessPlugin from './index';
import { asArray, assertIsString, isESM, isString } from './helper';
import type { EsbuildOptions, FileBuildResult } from './types';
import { trimExtension } from './utils';
import assert from 'assert';

import type { FunctionBuildResult } from './types';

const getStringArray = (input: unknown): string[] => asArray(input).filter(isString);

export async function bundle(this: EsbuildServerlessPlugin, incremental = false): Promise<void> {
assert(this.buildOptions, 'buildOptions is not defined');

this.prepare();
this.log.verbose(`Compiling to ${this.buildOptions.target} bundle with esbuild...`);
if (this.buildOptions.disableIncremental === true) {

this.log.verbose(`Compiling to ${this.buildOptions?.target} bundle with esbuild...`);

if (this.buildOptions?.disableIncremental === true) {
incremental = false;
}

const exclude = getStringArray(this.buildOptions?.exclude);

// esbuild v0.7.0 introduced config options validation, so I have to delete plugin specific options from esbuild config.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const esbuildOptions: EsbuildOptions = [
'concurrency',
'exclude',
'nativeZip',
'packager',
'packagePath',
'watch',
'keepOutputDirectory',
'packagerOptions',
'installExtraArgs',
'disableIncremental',
'outputFileExtension',
'outputBuildFolder',
'outputWorkFolder',
'nodeExternals',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
].reduce<Record<string, any>>((options, optionName) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { [optionName]: _, ...rest } = options;

return rest;
}, this.buildOptions);

const config: Omit<BuildOptions, 'watch'> = {
...this.buildOptions,
external: [
...this.buildOptions.external,
...(this.buildOptions.exclude === '*' || this.buildOptions.exclude.includes('*')
? []
: this.buildOptions.exclude),
],
...esbuildOptions,
external: [...getStringArray(this.buildOptions?.external), ...(exclude.includes('*') ? [] : exclude)],
incremental,
plugins: this.plugins,
};

if (isESM(this.buildOptions) && this.buildOptions.outputFileExtension === '.cjs') {
const { buildOptions, buildDirPath } = this;

assert(buildOptions, 'buildOptions is not defined');

assertIsString(buildDirPath, 'buildDirPath is not a string');

if (isESM(buildOptions) && buildOptions.outputFileExtension === '.cjs') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore Serverless typings (as of v3.0.2) are incorrect
throw new this.serverless.classes.Error(
'ERROR: format "esm" or platform "neutral" should not output a file with extension ".cjs".'
);
}

if (!isESM(this.buildOptions) && this.buildOptions.outputFileExtension === '.mjs') {
if (!isESM(buildOptions) && buildOptions.outputFileExtension === '.mjs') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore Serverless typings (as of v3.0.2) are incorrect
throw new this.serverless.classes.Error('ERROR: Non esm builds should not output a file with extension ".mjs".');
}

if (this.buildOptions.outputFileExtension !== '.js') {
config.outExtension = { '.js': this.buildOptions.outputFileExtension };
if (buildOptions.outputFileExtension !== '.js') {
config.outExtension = { '.js': buildOptions.outputFileExtension };
}

// esbuild v0.7.0 introduced config options validation, so I have to delete plugin specific options from esbuild config.
delete config['concurrency'];
delete config['exclude'];
delete config['nativeZip'];
delete config['packager'];
delete config['packagePath'];
delete config['watch'];
delete config['keepOutputDirectory'];
delete config['packagerOptions'];
delete config['installExtraArgs'];
delete config['disableIncremental'];
delete config['outputFileExtension'];
delete config['outputBuildFolder'];
delete config['outputWorkFolder'];
delete config['nodeExternals'];

/** Build the files */
const bundleMapper = async (entry: string): Promise<FileBuildResult> => {
const bundlePath = entry.slice(0, entry.lastIndexOf('.')) + this.buildOptions.outputFileExtension;
const bundlePath = entry.slice(0, entry.lastIndexOf('.')) + buildOptions.outputFileExtension;

// check cache
if (this.buildCache) {
const { result } = this.buildCache[entry];
const { result } = this.buildCache[entry] ?? {};
if (result?.rebuild) {
await result.rebuild();
return { bundlePath, entry, result };
Expand All @@ -78,12 +99,12 @@ export async function bundle(this: EsbuildServerlessPlugin, incremental = false)
const result = await build({
...config,
entryPoints: [entry],
outdir: path.join(this.buildDirPath, path.dirname(entry)),
outdir: path.join(buildDirPath, path.dirname(entry)),
});

if (config.metafile) {
fs.writeFileSync(
path.join(this.buildDirPath, `${trimExtension(entry)}-meta.json`),
path.join(buildDirPath, `${trimExtension(entry)}-meta.json`),
JSON.stringify(result.metafile, null, 2)
);
}
Expand All @@ -93,10 +114,10 @@ export async function bundle(this: EsbuildServerlessPlugin, incremental = false)
// Files can contain multiple handlers for multiple functions, we want to get only the unique ones
const uniqueFiles: string[] = uniq(this.functionEntries.map(({ entry }) => entry));

this.log.verbose(`Compiling with concurrency: ${this.buildOptions.concurrency}`);
this.log.verbose(`Compiling with concurrency: ${buildOptions.concurrency}`);

const fileBuildResults = await pMap(uniqueFiles, bundleMapper, {
concurrency: this.buildOptions.concurrency,
concurrency: buildOptions.concurrency,
});

// Create a cache with entry as key
Expand All @@ -106,10 +127,17 @@ export async function bundle(this: EsbuildServerlessPlugin, incremental = false)
}, {});

// Map function entries back to bundles
this.buildResults = this.functionEntries.map(({ entry, func, functionAlias }) => {
const { bundlePath } = this.buildCache[entry];
return { bundlePath, func, functionAlias };
});
this.buildResults = this.functionEntries
.map(({ entry, func, functionAlias }) => {
const { bundlePath } = this.buildCache[entry] ?? {};

if (typeof bundlePath !== 'string' || func === null) {
return;
}

return { bundlePath, func, functionAlias };
})
.filter((result): result is FunctionBuildResult => typeof result === 'object');

this.log.verbose('Compiling completed.');
}
9 changes: 9 additions & 0 deletions src/declarations.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
declare module 'bestzip' {
export type BestZipOptions = {
source: string;
destination: string;
cwd: string;
};

export function bestzip(options: BestZipOptions): Promise<void>;
}
Loading

0 comments on commit 6172b65

Please sign in to comment.