9 Audit, Build, and Deploy Visual Applications Using Grunt

VB Studio provides a number of NPM packages that you can use to audit, optimize, build, and deploy the web and mobile apps in your visual applications using Grunt.

About Building Your Application With Grunt

You can use Grunt to build your application from the sources stored in your Git repository or stored locally. Your visual application includes a Grunt file that you modify to define custom tasks that you want to include in the build process, and to configure built-in tasks.

The root folder of your visual application includes two resource files that Grunt uses when building applications: Gruntfile.js and package.json.

File Description
package.json This file declares the dependency and specifies the URL reference to the grunt-vb-build NPM package that provides the Grunt tasks used to build visual applications. VB Studio automatically updates the package version and URL when Oracle publishes a new version of the package.
Gruntfile.js This file contains a basic Grunt script for building the app that can be modified to add custom build tasks, and to configure built-in tasks.

The build folder contains the following artifacts that are generated during the build process:

  • optimized folder — optimized application resources, generated by the vb-optimize task
  • optimized.zip — archive of optimized resources that are uploaded by the vb-deploy task
  • to-be-processed.zip — archive of local sources that are uploaded to VB Studio server for processing

The build process for an application using Grunt includes the following steps:

Step Description
Process the application sources

This step consists of several important processes. The most important is "metadata processing", when the visual application sources are transformed into a deployable form. This includes the injection of Visual Builder runtime links and other configurations into the application's index.html, processing other application templates, and the creation of service definition files.

You run the vb-process-local task to process the sources. This task creates an output directory (build/processed) that can be consumed by the vb-optimized and vb-deploy tasks.

Optimize the processed sources

This step consists of a number of parts: optimize images, optimize styles, create require module bundles, and, if necessary, deploy the app's resources to a content delivery network.

You run the vb-optimize task to optimize the processed sources. The vb-optimize task runs the vb-image-minify, vb-css-minify, vb-require-bundle, and vb-optimize-cdn tasks, and generates the ./build/optimized folder containing the optimized sources.

Deploy the application artifact

This step consists of creating the deployment package archive and deploying it to the VB Studio instance. You run the vb-deploy task to deploy the application artifact.

You can include custom tasks in any of the steps by modifying Gruntfile.js to redefine tasks.

Build Your Application Using VB Studio

You can configure a continuous integration and delivery pipeline to build and deploy your visual application to a Visual Builder environment.

The high-level steps to do this are the same regardless of whether you deploy your visual application to a development, test, or production environment.

For an overview of how you set up a visual application project to build and deploy, see Setting Up for Visual Applications. For specific steps, depending on where you are in the application development lifecycle (development, test, or production), see the following sections:

Build Your Application Locally

After you create your visual application in VB Studio and you are ready to deploy it, you can download the sources to your local machine and use Grunt to build it locally, without setting up a Oracle Visual Builder Studio pipeline for building the application.

To build an application locally you need to install Node.js and its package manager (npm) on your local system. You also need to save the sources for the visual application on your local system. You can get the sources of your visual application in one of the following ways:

  • Cloning the Git repository containing the sources

  • Exporting the visual application from VB Studio and extracting it to your local system

Build and Deploy Your Application

Once you get your application sources, you need to run a number of tasks to build and deploy the application to the Visual Builder environment where you want to use the application.

The tasks that you run depend on what you want to do, and depend on the environments that you want to use. You also need two sets of credentials. One set of credentials is needed to connect to VB Studio itself, and the Designer that you use to create your visual application. We’ll refer to these credentials that you use to access VB Studio as the design-time credentials, or dt. The other set of credentials is the set that you need to deploy your application to the Visual Builder environment. We’ll refer to these latter credentials as the runtime credentials, or rt. You use the vb-credentials task to transfer these credentials.

When deploying an application, you use the --schema option to specify the database schema that will be used. The --schema option must be set to one of the following values: new, dev, stage, or live.

A typical series of tasks that you run if you want to build and deploy your visual application to a Visual Builder instance is the following:

  1. vb-process-local
  2. vb-package
  3. vb-credentials
  4. vb-deploy

To build and deploy your application locally:

  1. Open a command-line interface and enter node -v to confirm that version 12.1.3.0 or later of Node.js is installed and enter npm -v to confirm that npm is installed.
  2. In the command-line interface, navigate to the folder on your local system containing the package.json and Gruntfile.js files.
  3. Enter npm install to retrieve the node dependencies required to build the application.
    The install command retrieves the grunt-vb-build npm package defined in package.json.
  4. Enter the task names in the command-line interface to process your application sources, package the application, transfer credentials to the Visual Builder instance, and deploy the application to the Visual Builder instance. The following illustrative example shows how you execute these tasks, along with some of the parameters that they support. Consult the entry for each task to view the full list of supported parameters.
    # First build application sources
    ./node_modules/.bin/grunt vb-process-local
    
    # Package the application sources. This task in turn executes 
    # vb-optimize and vb-manifest
    ./node_modules/.bin/grunt vb-package
    
    # Transfer credentials from VB Studio to the target Visual Builder 
    # instance 
    ./node_modules/.bin/grunt vb-credentials:transfer \
        --url:dt=<VB-Studio-instance-url> \
        --username:dt=<VB-Studio-username> \
        --password:dt=<VB-Studio-password> \
        --environment-id=foo
        --url:rt=<Visual-Builder-runtime-instance-url> \
        --username:rt=<Visual-Builder-runtime-username> \
        --password:rt=<Visual-Builder-runtime-password> \
    #   ...other options...
    
    # Deploy and publish the visual application to the target Visual 
    # Builder instance using the data schema from the previously 
    # published live version of the application.
    ./node_modules/.bin/grunt vb-deploy \
        --url:rt=<url of visual builder instance> \
        --username:rt=<username> \
        --password:rt=<password> \
        --id=<your visual app ID> \
        --ver=<your visual app version> \
        --remoteProjectId=<VB Studio project ID> \
        --remoteGitRepo=<URL of the visual app's GIT repository> \
        --schema=live
        --publish
    
When these Grunt tasks finish, you can test your application by opening the URL of the deployed application in your browser. The command-line interface where you run these Grunt tasks displays the URLs that identify the deployment location of the web and/or mobile apps.

Grunt Tasks to Build Your Visual Application

The build tasks exposed by the grunt-vb-build package have options and pre- and post- task hooks that you use when defining the task.

About VB Studio Grunt Build Tasks

You use pre-defined Grunt tasks and options to define the tasks that are performed when building your application.

The public Grunt tasks that are used to build the application are exposed by the grunt-vb-build package. Some tasks have pre- and post- task hooks which you can use to add custom functionality.

Options that you specify for a task might be overridden by other options that have a higher priority. Task options have the following priority:

  1. Command line options
  2. Task:target specific options (for multitasks)
  3. Task specific options
  4. Generic "vb" options

vb-clean

This task cleans the build directory.

The following table describes the subtasks, hooks and inputs and outputs of the vb-clean task.

Detail Description
subtasks n/a
multitask n/a
hooks vb-pre-clean, vb-post-clean
input build/*
output n/a

The following table describes the options for the vb-clean task.

Name Mandatory Default Value Description
Build options
build no build Name of build directory.

vb-process-local

This task processes the application sources locally in the Grunt process.

The processing operation resolves various templates and further modifies (adds and updates) several application resources.

To run this task you must provide the VB Studio URL and your credentials for accessing the VB Studio instance. You can provide the credentials directly when you run the task. Alternatively, you can use the accessToken option to specify a valid OAuth access token. If you provide both credentials and an OAuth access token, the task authenticates using the access token.

The following table describes the subtasks, hooks and inputs and outputs of the vb-process-local task.

Detail Description
subtasks n/a
multitask n/a
hooks n/a
input ${gitSources}
output build/processed/*

The following table describes the options for the vb-process-local task. The :ce suffix is only required when your application includes Web Components and, as a result, references the Component Exchange.

Name Mandatory Default Value Description
Authentication options
url[:ce] no n/a URL of Component Exchange service. Not needed if the application does not reference Web Components.
username[:ce] no n/a The username to be used to obtain OAuth access token for further communication with VB Studio services.
password[:ce] no n/a The password to be used to obtain OAuth access token for further communication with VB Studio services.
accessToken[:ce] no n/a The value of an OAuth access token. If provided, username and password options are necessary.
Build options
target no build Name of build directory.
gitSources no ./ The location of the sources of the visual application.

vb-deploy

This task deploys a visual application to a Visual Builder runtime instance.

You must build the visual application using the vb-process-local task before you use the vb-deploy task.

The following table describes the subtasks, hooks and inputs and outputs of the vb-deploy task.

Detail Description
subtasks n/a
multitask n/a
hooks n/a
input

build/processed/*

build/optimized/*

output build/deploy.zip

The following table describes the options for the vb-deploy task.

Name Mandatory Default Value Description
Application selection options
id yes Read from the rootURL attribute in visual-application.json ID of the visual application you're going to build.
ver yes Read from version attribute in visual-application.json Version of the visual application.
url[:rt] yes n/a

A Visual Builder runtime service URL

The rt suffix is optional.

profileId   n/a Application profile ID.
remoteProjectId   n/a ID of the source project
remoteGitRepo   n/a URL of the sources GIT repository
Authentication options
username[:rt] no n/a The username to be used to obtain OAuth access token for further communication with VB Studio runtime.

The rt suffix is optional.

password[:rt] no n/a The password to be used to obtain OAuth access token for further communication with VB Studio runtime.

The rt suffix is optional.

accessToken[:rt] no n/a The value of OAuth access token. If provided, username and password options are not necessary.

The rt suffix is optional.

sslCertificate[:rt] no n/a The path to the SSL certificate for the connection to VB Studio instances provisioned with self-signed certificates.

The rt suffix is optional.

Build options
target   build Name of build directory.
Data processing options
schema no new Specifies data schema processing during application deployment. The value can be new, dev, stage or live.
Other options
publish   false Defines whether the deployed application should be published or not.

vb-credentials

This task transfers credentials of a visual application from VB Studio to the Visual Builder runtime instance where the visual application is deployed.

The transfer includes any basic authentication service credentials or mobile build configurations stored for the visual application in VB Studio.

Run the vb-credentials task when you first use the vb-deploy task to deploy a visual application to the Visual Builder instance or after you change any of the previously used credentials in VB Studio.

# First build application sources
./node_modules/.bin/grunt vb-process-local
# Transfer credentials from VB Studio to the target Visual Builder 
# instance and deploy the visual application to the target Visual 
# Builder instance
./node_modules/.bin/grunt grunt vb-credentials:transfer \
    --url:dt=<VB-Studio-instance-url> \
    --username:dt=<VB-Studio-username> \
    --password:dt=<VB-Studio-password> \
    --environment-id=foo
    --url:rt=<Visual-Builder-runtime-instance-url> \
    --username:rt=<Visual-Builder-runtime-username> \
    --password:rt=<Visual-Builder-runtime-password> \
#   ...other options...

The following table describes the subtasks, hooks and inputs and outputs of the vb-credentials task.

Detail Description
subtasks n/a
multitask n/a
hooks n/a
input n/a
output n/a

The following table describes the task target of the vb-credentials task.

Detail Default Target Description
transfer n/a Transfers credentials.

The following table describes the options for the vb-credentials task.

Name Mandatory Default Value Description
Authentication options
url n/a n/a URL of the VB Studio service.
username no n/a The username to be used to obtain OAuth access token for further communication with VB Studio services.
password no n/a The password to be used to obtain OAuth access token for further communication with VB Studio services.
accessToken no n/a The value of an OAuth access token. If provided, username and password options are necessary.
sslCertificate no n/a The path to the SSL certificate for the connection to VB Studio instances provisioned with self-signed certificates.
Other options
remote-app-name n/a n/a Read from rootURL key in ${gitSources}/visual-application.json
git-repository-name n/a n/a Name of the git repository that stores the visual application. The name is the last path segment in the GIT URL.
environment-id n/a n/a

Name of the associated VB Studio environment.

vb-optimize

This task optimizes the application sources by doing the following: minifies images and CSS, and creates minified requirejs module bundles.

The following table describes the subtasks, hooks and inputs and outputs of the vb-optimize task.

Detail Description
subtasks vb-prepare, vb-image-minify, vb-css-minify, vb-require-bundle
multitask n/a
hooks vb-pre-optimize, vb-post-optimize
input build/processed/*
output build/optimized/*

This task does not define its own options. Any option of the subtasks is relevant.

vb-optimize-cdn

To improve an app's loading performance, you can deploy an app's resources to a Content Delivery Network (CDN). The task inserts a <base> element with a href attribute that contains the base URL of the deployed application resources.

The task inserts the base URL in the href from the following locations in the following order:

  • cdnUrl command-line option
  • cdnUrl setting in vb-optimize-cdn tasks options
  • resolveTemplate.BASE_URL entry from vb-process-raw-index-html task options (for Oracle Cloud Applications)

If you do not specify any of these options, the task will silently do nothing.

This task automatically runs from within the vb-optimize task for visual applications. It does not run for Visual Extension applications.

Detail Description
subtasks -
multitask (config generator task: vb-optimize-cdn-configuration)
hooks -
input build/optimized/*
output build/optimized/*

The following table describes the options for the vb-optimize-cdn task.

Name Mandatory Default Value Description
cdnUrl n/a n/a URL of the deployed application assets

vb-prepare

This task copies either the raw application sources or the processed application sources to the build/optimized directory where the optimization takes place.

If the build/processed directory exists (as a result of the vb-process task) and no rawSourcesMode option is specified, this task will copy the build/processed directory into the build/optimized directory.

If the build/processed directory does NOT exist or rawSourcesMode option is set to "True", this task will copy the raw application sources (specified by the gitSources option, the default values of which is "./") into the build/optimized directory and invoke the vb-process-raw task.

The following table describes the subtasks, hooks and inputs and outputs of the vb-prepare task.

Detail Description
subtasks vb-process-raw
hooks n/a
input build/processed/* or ${gitSources}
output build/optimized/*

The following table describes the options for the vb-prepare task.

Name Mandatory Default Value Description
build no build Name of build directory.
rawSourcesMode no false Specifies if the task should copy raw application sources or metadata processed sources from the build/processed directory.

Note: The implicit value is defined by the existence of build/processed directory (true if the directory exist).

vb-require-bundle

This tasks creates minified requirejs module bundles.

The following table describes the subtasks, hooks and inputs and outputs of the vb-require-bundle task.

Detail Description
subtasks n/a
multitask config generator task: vb-require-bundle-configuration
hooks n/a
input build/optimized/*
output build/optimized/*

The following table describes the options for the vb-require-bundle task.

Name Mandatory Default Value Description
Build options
build no build Name of build directory.
Optimization options
emptyPaths no n/a Comma-separated list of require paths that are set "empty". Requirejs optimizer will not follow and bundle matching dependencies.
requirePaths no n/a

Requirejs optimizer paths mapping. This will override any default values or values read from app-flow.json

The value needs to be in a form of quoted JSON object: (--requirePaths='{ "foo": "boo" }')

bundles    

Defines custom require module bundles.

Configuration schema:

  • <bundle name>
    • modules
      • find
      • ids
    • exclude
      • find
      • ids
bundles.modules    

Specification of the modules that are supposed to be added to the enclosing bundle element.

Configuration schema:

  • find
  • ids
bundles.exclude    

Specify modules that shouldn't be part of the enclosing modules bundle. The exclusions are applied to all bundle modules, including modules added following transitive module dependencies.

Configuration schema:

  • find
  • ids
bundles.[exclude|modules].find    

List of regular expression patterns used for matching optimized application resources.

Regular expressions starting with exclamation mark are considered to be negative - resources matching these patterns won't be included.

bundles.[exclude|modules].ids     Specifies list of module ids.
transpile   false

Determines whether a separate set of require module bundles transpiled to ES5 code using babel preset-env preset should be created and stored into bundles/es5 directory.

When this option is set to true application's index.html is modified so it contains a code snippet that switches between the original bundles for modern browsers and the ES5 versions for IE11.

minify

  true When set to true babel minify preset is used to minify generated requirejs module bundles. The minification is also applied to the ES5 variants of the bundles if created.
include no n/a

Deprecated. You should use the bundles option instead.

Comma-separated list of regular expressions that specify what resources are supposed to be added to the optimization requirejs resources bundle.
exclude no n/a

Deprecated. You should use the bundles option instead.

Comma-separated list of regular expressions that specify what ought NOT to be added to the optimization requirejs resources bundle. A resource will not be added if it is both excluded and included.

vb-test

This task runs the action chain tests that you have defined in your visual application for web and mobile apps.

For more information, see Test Action Chains Using the vb-test Grunt Task.

vb-css-minify

This task minifies the CSS resources.

The following table describes the subtasks, hooks and inputs and outputs of the vb-css-minify task.

Detail Description
subtasks n/a
multitask config generator task: vb-css-minify-configuration
hooks n/a
input build/optimized/*
output build/optimized/*

The following table describes the options for the vb-css-minify task.

Name Mandatory Default Value Description
build no build Name of build directory.

vb-image-minify

This task minifies the image resources.

The following table describes the subtasks, hooks and inputs and outputs of the vb-image-minify task.

Detail Description
subtasks n/a
multitask config generator task: vb-image-minify-configuration
hooks n/a

The following table describes the options for the vb-image-minify task.

Name Mandatory Default Value Description
build no build Name of build directory.

vb-json-minify

This task minifies JSON resources to remove white spaces.

The following table describes the subtasks, hooks and inputs and outputs of the vb-json-minify task.

Detail Description
subtasks n/a
multitask config generator task: vb-json-minify-configuration
hooks n/a
input build/optimized/*
output build/optimized/*

vb-export

This task downloads application sources from the VB Studio instance and expands the archive on the local filesystem for further processing.

The following table describes the subtasks, hooks and inputs and outputs of the vb-export task.

Detail Description
subtasks n/a
multitask n/a
hooks n/a
input build/optimized/*
output build/optimized/*

The following table describes the options for the vb-export task.

Name Mandatory Default Value Description
Application selection options
id yes n/a ID of the visual application you're going to build. The application needs to exist on the referred VB Studio instance.
ver yes n/a Version of the visual application
url yes n/a URL of your VB Studio instance
Authentication options
username no n/a The username to be used to obtain OAuth access token for further communication with VB Studio services.
password no n/a The password to be used to obtain OAuth access token for further communication with VB Studio services.
accessToken no n/a The value of an OAuth access token. If provided, username and password options are necessary.
sslCertificate no n/a The path to the SSL certificate for the connection to VB Studio instances provisioned with self-signed certificates.
Build options
gitSources no ./ The location of the sources of the visual application.

vb-manifest

Creates build manifest(s) for the visual application’s build assets. The assets can be non-optimized (in the build/processed directory) or optimized (in the build/optimized directory).

For base visual applications it creates two kinds of manifests:

  • A manifest in each web or mobile application. This manifest contains a list of application resources, requirejs bundles mapping and the name of the version_<hash> directory. The manifest location is build/[processed|optimized]/[web|mobile]Apps/<applicationName>/build-info.json.
  • A manifest for the visual application itself. This contain the URL of the sources Git repository. The manifest location is build/[processed|optimized]/build-info.json.

For visual applications, it creates one manifest in build/[processed|optimized]/manifest.json for visual extensions.

Note:

This task is a multitask so it requires an existing Grunt configuration to run. You can create your own in your Gruntfile.js or use the vb-manifest-configuration subtask to generate one.

The following table describes the subtasks, hooks and inputs and outputs of the vb-manifest task.

Detail Description
subtasks n/a
multitask config generator task: vb-manifest-configuration
hooks n/a
input build/[processed|optimized]/*
output build/[processed|optimized]/*

The following table describes the options for the vb-manifest task.

Name Mandatory Default Value Description
target no build Name of build directory.
vx-version no n/a Overwrites the version key in a visual extension's manifest with the given value.
git-repository-url no The Git repository URL read from ${gitSources}/.git/config.

See the default value for a description of this option.

The task writes the value into the generated build manifest of the visual application (build/optimized/build-info.json) under git-repository-url.

vb-package

This task packages the visual application sources. It includes application optimization (vb-optimize) and build manifest generation (vb-manifest).

The following table describes the subtasks, hooks and inputs and outputs of the vb-package task.

Detail Description
subtasks vb-optimize, vb-manifest-configuration, vb-manifest
multitask n/a
hooks vb-pre-package, vb-post-package
input build/processed/*
output build/optimized/*

The following table describes the options for the vb-package task.

Name Mandatory Default Value Description
skip-optimize No False If True, the vb-package task will not call the vb-optimize task.

vb-process-raw

This task processes application sources before the optimizations take place in raw sources mode.

This involves following actions:processing of application's index.html template. <!-- visualBuilderScripts -->, <!-- vb:inject id="headContent" --> and <!-- vb:inject id="headContent" theme="resources/css/" --> markers are resolved to appropriate code. This step is done by vb-process-raw-index-html task.copies /services directory from root of visual application to the optimized web applicationupdates service references going outside of the application scope to local references referring the copy of /services directory in the web applicationcopies /dynamicLayouts directory from root of visual application to the optimized web application

The following table describes the subtasks, hooks and inputs and outputs of the vb-process-raw task.

Detail Description
subtasks vb-process-raw-index-html
multitask n/a
hooks n/a
input build/optimized/*
output build/optimized/*

The following table describes the options for the vb-process-raw task.

Name Mandatory Default Value Description
build no build Name of build directory.

vb-process-raw-index-html

This task resolves templating marks in an application's index.html.

This task removes the following templating marks:

  • <!-- visualBuilderScripts -->
  • <!-- vb:inject id="headContent" -->
  • <!-- vb:inject id="headContent" theme="resources/css/" -->

The following template variables are used in the code that replaces these markers:

  • %BASE_URL%
  • %JET_CDN_PATH%
  • %JET_CDN_VERSION%
  • %VB_CDN_PATH%
  • %VB_VERSION%

If the resolveTemplate configuration object is not provided for this task, these variables will be left unresolved in the resulting index.html.

If the resolveTemplate configuration object is set at least to empty object, the template variables will be resolved with values taken from the application's version files (private/custom/versions.json or resources/package/versions.json), or with default values if none of these exist.

grunt.initConfig({
  "vb-process-raw-index-html": {
    options: {
      resolveTemplate: {
          BASE_URL: 'http://oracle.cloud/abc',
      }
    }
  },
});

The configuration object may also contain values for the other template variables. In such case, the configuration value has precedence before the versions files and defaults.

The following table describes the subtasks, hooks and inputs and outputs of the vb-process-raw-index-html task.

Detail Description
subtasks n/a
multitask config generator task: _vb-process-raw-index-configuration
hooks n/a
input build/optimized/*
output build/optimized/*

The following table describes the options for the vb-process-raw-index-html task.

Name Mandatory Default Value Description
build no build Name of build directory.
resolveTemplate no n/a Values for template variables injected into the application's index.html

Customize Your Grunt Build Process

You can edit the Gruntfile.js file included in your application to customize the build tasks that are performed.

Add Custom Functionality to Existing Tasks

The public tasks exposed by the grunt-vb-build package have pre- and post- task hooks that you can redefine to add custom functionality.

For example, you can define hook tasks in Gruntfile.js to add some special application processing before the optimization step (vb-pre-optimize) by performing the following steps:

  1. Open Gruntfile.js.
  2. Edit the file to define the hook tasks.

    To define the hook tasks vb-pre-optimize , your edited Gruntfile.js might be similar to the following:

    module.exports = (grunt) => {
        require('load-grunt-tasks')(grunt);
         grunt.registerTask('vb-pre-optimize', () => {
            // add custom resources or modify existing resources here
        });
    
    };

Override Existing Grunt Tasks

You can override an existing task by registering your own task under the same name.

To override an existing Grunt task:

  1. Open Gruntfile.js.
  2. Edit the file to redefine the task you want to override.

    For example, if you want to do a custom deployment of the application runtime artifact, you can override the vb-deploy task. To redefine the task vb-deploy, your edited Gruntfile.js might be similar to the following:

    module.exports = (grunt) => {
        require('load-grunt-tasks')(grunt);
        grunt.registerTask('vb-deploy', () => {
            // do my own deployment of built "build/processed.zip" runtime application
          archive
        });
    };

Optimize a Specific Web Application

You can optimize a specific application by editing Gruntfile.js or your custom Jenkins shell script to specify a target for the build task.

In Gruntfile.js, you can redefine the vb-build task and specify a target for the vb-optimize task. Alternatively, you can create a new task that performs steps similar to the vb-build task and specify the target.

To specify an app as a task target in Gruntfile.js:

  1. Open Gruntfile.js.
  2. Edit the file to define the tasks performed for the vb-build task and specify a target for the vb-optimize task.

    The target name is the path of the web application relative to the /webApps directory.

    module.exports = (grunt) => {
        require('load-grunt-tasks')(grunt);
        grunt.registerTask('vb-build', [
            'vb-pre-build',
            'vb-clean',
            'vb-prepare-sources',
            'vb-optimize:myWebApp',
            'vb-deploy',
            'vb-post-build',
        ]);
    };

You can also define the target in your Jenkins shell script, for example, by modifying it similar to the following:

grunt vb-prepare-sources --url=... --id=... --ver=... --username=... --password...grunt
 vb-optimize:myWebApp
 grunt vb-deploy --url=... --id=... --ver=... --username=... --password...

You can also edit the script to run only specific optimization tasks:

# vb-image-minify-configuration will create configurations of vb-image-minify multitask for
        all existing web application
grunt vb-image-minify-configuration vb-image-minify

Host an Application on a Content Delivery Network (CDN)

You can host an application on a CDN to improve response times for clients that connect to your visual application.

Before you can publish your app, you need to stage it and export it your local machine. Once you have exported it to your local machine, build it using the following command from the root directory where you extracted the exported application:

./node_modules/.bin/grunt vb-build \
    --url=<url of visual app instance> \
    --username=<username> \
    --password=<password> \
    --id=<your visual app ID> \
    --ver=<your visual app version> \
    --cdnURL=<url of the deployed application's assets> \
    --insertBaseUrl

Note:

The URL for the cdnURL option must end with /. For example, https://hostname:port/CDN/webApp/CDNLocation/. If you omit the final /, the resources will be resolved against the parent segment of the URL.

The insertBaseURL task option inserts a BASE_URL token into index.html's vbInitConfig section.

Copy build/optimized.zip that the grunt vb-build task generates to the CDN host and extract it to the directory location where the CDN will host it.

For information about using the grunt vb-build task, see Build Your Application Locally.

Run and Configure a Multitask

Multitasks require configuration. You can create this either by using the corresponding *-configuration tasks, or by defining the configuration in Gruntfile.js.

To configure a multitask in Gruntfile.js:

  1. Open Gruntfile.js.
  2. Edit the file to configure the multitask.

    For example, to configure the vb-require-bundle multitask, you might edit the file to be similar to the following.

    module.exports = (grunt) => {
      grunt.initConfig({
       'vb-require-bundle': {
           options: {
               "transpile": true,
               "minify": true,
           },
           myWebApp: {
               options: {
                   "transpile": true,
                   "minify": true,
               },
           },
       },
        require('load-grunt-tasks')(grunt);
    };

    The top level task options are applied to all web applications. If you specify a target, the options are applied only to the target application.

Customize Bundle Modules

You can define the content of the requirejs module bundles to create multiple bundles when deploying a visual application.

Pages that you want to load initially can be packaged in the main bundle, and other pages and pages in other flows that are not required initially can be packaged in a separate bundle that can be loaded when needed. Customizing the module bundles can help optimize the time needed to load and run the application.

For example, this configuration example shows how the vb-require-bundle task can be configured to create the following require module bundles for a web application named "webapp1".

  • A bundle for all resources that belong to the application flow dashboard. This bundle will include all files that matches the "flows/dashboard" pattern. This will include all pages, models, resources and nested flows stored in the flows/dashboard directory. This bundle will not contain the module named helpers, that is referred to in one of the included page models.
  • A bundle for resources that belongs to the application flow customers. In this case, the nested flows are excluded (as they are placed into a separate bundle). This bundle also excludes the helpers module.
  • A bundle of resources of flows nested into the customers flow.
  • A "base" bundle of application resources (shell pages and application resources, libraries and styles). This bundle explicitly adds the helpers module.

To customize the bundle modules:

  1. Open Gruntfile.js.
  2. Edit the file to configure the vb-require-bundle task.
    {
      "vb-require-bundle": {
         "webapp1": {
             "options": {
                 "transpile": true,
                 "minify": true,
                 "bundles": {
                     "dashboard": {
                         "modules": {
                             "find": ["flows/dashboard"]
                         },
                         "exclude": {
                           "ids": ["helpers"]
                         }
                       },
                       "customers": {
                           "modules": {
                              "find": ["flows/customers", "!flows/customers/flows"]
                            },
                           "exclude": {
                             "ids": ["helpers"]
                             }
                       },
                       "customers-nested": {
                           "modules": {
                              "find": ["flows/customers/flows"]
                            }
                       },
                       "base": {
                         "modules": {
                           "find": [
                             "app-flow.js",
                             "^pages/",
                             "resources/strings",
                             "resources/css"
                           ],
                           "ids": ["helpers"]
                           }
                       }
                 }
             }
         }
      }
    }

Specify Options of Non-multitasks

You can specify task options in the configurations for specific tasks.

When specifying a task's options, you want to make sure that the options are applied only to the specific task. For example, specifying --url and --username options in the command line will override options specified in the vb-deploy configuration.

To specify task options in Gruntfile.js:

  1. Open Gruntfile.js.
  2. Enter the options for the task.

    For example, to override the URL and credentials parameters for the vb-deploy task in order to deploy to an instance other than where the sources were processed, your edited Gruntfile.js might be similar to the following:

    module.exports = (grunt) => {
      grunt.initConfig({
       'vb-deploy: {
           options: {
               url: 'my production instance URL',
               username: 'production instance username',
           },
       },
        require('load-grunt-tasks')(grunt);
    };

Move a Sitemap Resource to a Visual Application's Root Directory

When you manually add a sitemap to your web application's resources, you can set up the sitemap file to be copied to the visual application's root directory after the app is deployed, so the sitemap path remains unchanged post-deployment.

Each time a web application is deployed, the location of the resources changes to use a new version, and the sitemap file is automatically moved to the new /webApps/webAppName/version_id directory. As a result, you'll need to include the newest version_id in the path to access the application's sitemap.

To automatically copy the sitemap file from the /webApps/webAppName/version_id directory to the application's root directory after each deployment, you can edit your application's Gruntfile.js file and add the vb-post-package task:

  1. Open Gruntfile.js.
  2. Edit the file to define the tasks performed for the vb-post-package task:
    {code:java}
        /**
        Moves sitemap.xml resource back to Visual Application Root.
        */
        grunt.registerTask('vb-post-package', () => {
            const fileName = 'sitemap.txt'; // REPLACE WITH YOUR FILENAME
            const webAppName = 'mywebapp';  // REPLACE WITH YOUR WEB APP NAME
            const webAppDirectory = `build/optimized/webApps/${webAppName}`;
            // find out version dir
            const files = fs.readdirSync(webAppDirectory);
            const versionDir = files.find(file => /^version_\d+/.test(file));
            const source =
    `${webAppDirectory}/${versionDir}/resources/${fileName}`;
            const target = `build/optimized/${fileName}`;
            // move the file back to assets root
            fs.renameSync(source, target);
            console.log(`${source} moved to ${target}`);
            });
    {code}

    Remember to update the task to use your sitemap resource and your web app.

Audit Your Application Using the vb-audit Grunt Task

VB Studio provides an NPM package (grunt-vb-audit) that includes the vb-audit Grunt task that you can use to audit your visual applications.

The root folder of your visual application includes two resource files that Grunt uses when it audits applications: Gruntfile.js and package.json.

File Description
package.json This file declares the dependency and specifies the URL reference to the grunt-vb-audit NPM package that provides the Grunt task to audit visual applications. VB Studio automatically updates the package version and URL when Oracle publishes a new version of the package.
Gruntfile.js This file contains a basic Grunt script that you can modify to add custom audit tasks, and to configure built-in tasks.

As with the Grunt tasks that you use to build and deploy your visual application, you need to install Node.js and its package manager (npm) on your local system. You also need to save the sources for the visual application on your local system.

To audit your application using vb-audit:

  1. Open a command-line interface and enter node -v to confirm that version 12.1.3.0 or later of Node.js is installed and enter npm -v to confirm that npm is installed.
  2. In the command-line interface, navigate to the folder on your local system containing the package.json and Gruntfile.js files.
  3. Enter npm install to retrieve the node dependencies required to audit the application.

    The install command retrieves the grunt-vb-audit NPM package defined in package.json.

  4. Enter grunt vb-audit in the command-line interface to audit your application. The following illustrative example shows how you execute this task.
    # Audit application sources
    ./node_modules/.bin/grunt vb-audit \
    --url=<https://Visual-Builder-runtime-instance-url/ic/builder/> \
    --username=<Visual-Builder-runtime-username> \
    --password=<Visual-Builder-runtime-password> \
    --id=<your visual app ID> \
    --ver=<your visual app version>
    

You can omit the task parameters (URL, username, and so on) if the visual application that you audit does not include modules that require a server connection, such as business objects, for the audit to complete. If you do not specify values for the task parameters when a server connection is required, error messages appear in the command-line interface and the corresponding modules fail the audit.

By default, vb-audit audits all files in your application according to the following glob patterns:

[
    '**/*',
    // Ignore npm directories during audit
    '!node/**',
    '!**/node_modules/**',
]

You can override the files to audit with your own glob patterns. The exclusion patterns in the default glob pattern are appended to the glob patterns that you supply.

Configure Audit Options in Gruntfile.js

You can specify server connection properties and vb-audit properties in your visual application's Gruntfile.js file.

The following example shows available options.

grunt.initConfig({
    vb: {
        url: '<VB-instance-url>',
        id: <your visual app ID>,
        ver: <your visual app version>,
        username: <username>,
        password: <password>,  // This is not encrypted
    },
    'vb-audit': {
        options: {
            config: {
                auditors: {
                    // Disable specific auditors
                    'lcm.VirtualRolesAuditor': { // Requires backend
                        disabled: true,
                    },
                    'components.InstalledComponentsAuditor': { // Requires backend
                        disabled: true,
                    },
                    'serviceConnectionAuditor': { // Requires backend
                        disabled: true,
                    },
                    'deploymentProfileAuditor': { // Requires backend
                        disabled: true,
                    },
                },
            },
            files: [ // Globbing patterns to use for this application
                '*',
                'process/**',
                'services/**',
                'settings/**',
                'webApps/**',
                '!**/package-lock.json',
            ],
            processResults: (results) => { // Supply an alternate results processor
                grunt.log.writeln(`Processed ${results.auditedResourceCount} files`);
            },
            outputFile: 'auditoutput.txt', // Output file to receive the audit results (e.g. auditoutput.txt, auditoutput.csv)
        },
    },
});

The entries in 'vb-audit': { options: { config: { are passed to the audit system and override or augment the options that you set in your visual application's settings/audit.json file if you configured options in the latter file using VB Studio’s Audits feature.

For output, you can specify processResults or outputFile. If you specify neither, vb-audit writes the output to the command-line interface. Note that the example Gruntfile.js shown above displays both options, as it is an illustrative example of available options. Omit the option (processResults or outputFile) that you do not want to use, or omit both options if you want to write output to the command-line interface.

The results parameter for processResults has the following format:

{
    auditedResourceCount, <number of resources audited>
    totalResourceCount, <number of resources checked (some resources may not have auditors)>
    issues[{
        ruleId, // String id of the rule
        severity, // ['error' | 'warning' | 'info' | 'todo']
        message, // String message
        filePath, // resource's file path
        location: {
            line,
            col,
            endLine,
            endCol,
            length,
        },
    }]
}

You can specify target-based options in Gruntfile.js that override or augment your standard options. The following example audits the modules in the webApps directory:

grunt.initConfig({
    vb: {
        ...
    },
    'vb-audit': {
        options: {
            ...
        },
 
        webApps: { // target to audit the modules in the webApps directory
            files: [
                'webApps/**'
            ],
        },
    },
});

To audit the webApps target, run the vb-audit task and specify the target:

./node_modules/.bin/grunt vb-audit:webApps

Note:

grunt.config.merge merges the target options, such as webApps in our previous example, into the vb-audit options. It merges array and object properties recursively. If, for example, options defines a files array with 5 elements and you provide a target options with a files array that has 2 elements, the first 2 elements in the options files array will be overwritten and the remaining 3 elements remain unchanged.

A difference between the files option in the Gruntfile.js file and the paths/exclude option in your settings/audit.json file is that the Gruntfile.js files option assembles the set of files that vb-audit sends to the audit system, whereas the audit.json patterns are ignored by the audit system. In particular, if you supply a files option in your Gruntfile.js, you need to have an exclusion pattern for something like node_modules, as processing the thousands of files under node_modules can be time consuming. This exclusion pattern is included in the default configuration.

Override Configuration Options in Gruntfile.js

You can override the Gruntfile.js configuration options for vb-audit by specifying properties on the command-line interface.

The following example shows available options.

./node_modules/.bin/grunt vb-audit \
    --audit.files='webApps/**' \
    --audit.disabledauditors='lcm.VirtualRolesAuditor,components.InstalledComponentsAuditor' \
    --audit.outputfile='auditoutput.txt'