22const _ = require ( 'lodash' ) ;
33const BbPromise = require ( 'bluebird' ) ;
44
5+ function randomName ( ) {
6+ const chars = 'abcdefghijklmnopqrstufwxyzABCDEFGHIJKLMNOPQRSTUFWXYZ1234567890' ;
7+ const pwd = _ . sampleSize ( chars , 10 ) ;
8+ return pwd . join ( '' ) ;
9+ }
10+
511function isIntrinsic ( obj ) {
6- const isObject = typeof obj === 'object' ;
7- return isObject && Object . keys ( obj ) . some ( ( k ) => k . startsWith ( 'Fn::' ) || k . startsWith ( 'Ref' ) ) ;
12+ return typeof obj === 'object' &&
13+ Object . keys ( obj ) . some ( ( k ) => k . startsWith ( 'Fn::' ) || k . startsWith ( 'Ref' ) ) ;
814}
915
1016function toTags ( obj , serverless ) {
@@ -26,6 +32,39 @@ function toTags(obj, serverless) {
2632 return tags ;
2733}
2834
35+ // return an iterable of
36+ // [ ParamName, IntrinsicFunction ]
37+ // e.g. [ 'mptFnX05Fb', { Ref: 'MyTopic' } ]
38+ // this makes it easy to use _.fromPairs to construct an object afterwards
39+ function * getIntrinsicFunctions ( obj ) {
40+ // eslint-disable-next-line no-restricted-syntax
41+ for ( const key in obj ) {
42+ if ( Object . prototype . hasOwnProperty . call ( obj , key ) ) {
43+ const value = obj [ key ] ;
44+
45+ if ( Array . isArray ( value ) ) {
46+ // eslint-disable-next-line guard-for-in, no-restricted-syntax
47+ for ( const idx in value ) {
48+ const innerFuncs = Array . from ( getIntrinsicFunctions ( value [ idx ] ) ) ;
49+ for ( const x of innerFuncs ) {
50+ yield x ;
51+ }
52+ }
53+ } else if ( isIntrinsic ( value ) ) {
54+ const paramName = randomName ( ) ;
55+ // eslint-disable-next-line no-param-reassign
56+ obj [ key ] = `\${${ paramName } }` ;
57+ yield [ paramName , value ] ;
58+ } else if ( typeof value === 'object' ) {
59+ const innerFuncs = Array . from ( getIntrinsicFunctions ( value ) ) ;
60+ for ( const x of innerFuncs ) {
61+ yield x ;
62+ }
63+ }
64+ }
65+ }
66+ }
67+
2968module . exports = {
3069 isIntrinsic,
3170 compileStateMachines ( ) {
@@ -42,7 +81,17 @@ module.exports = {
4281 DefinitionString = JSON . stringify ( stateMachineObj . definition )
4382 . replace ( / \\ n | \\ r | \\ n \\ r / g, '' ) ;
4483 } else {
45- DefinitionString = JSON . stringify ( stateMachineObj . definition , undefined , 2 ) ;
84+ const functionMappings = Array . from ( getIntrinsicFunctions ( stateMachineObj . definition ) ) ;
85+ if ( _ . isEmpty ( functionMappings ) ) {
86+ DefinitionString = JSON . stringify ( stateMachineObj . definition , undefined , 2 ) ;
87+ } else {
88+ DefinitionString = {
89+ 'Fn::Sub' : [
90+ JSON . stringify ( stateMachineObj . definition , undefined , 2 ) ,
91+ _ . fromPairs ( functionMappings ) ,
92+ ] ,
93+ } ;
94+ }
4695 }
4796 } else {
4897 const errorMessage = [
0 commit comments