Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 51892c296e | |||
| c5b699db00 | |||
| ee4dd7d4bf | |||
| 4801f649df | |||
| 9888569dcb | |||
| 1ade5a0892 |
@@ -1,11 +0,0 @@
|
||||
root = true
|
||||
|
||||
[*.js]
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.yml]
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
+1
-23
@@ -1,24 +1,2 @@
|
||||
.rvmrc
|
||||
.DS_Store
|
||||
/tmp/
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
npm-debug.log
|
||||
.idea
|
||||
yarn-error.log
|
||||
dist
|
||||
node_modules
|
||||
/handlebars-release.tgz
|
||||
.nyc_output
|
||||
|
||||
# Generated files
|
||||
lib/handlebars/compiler/parser.js
|
||||
/coverage/
|
||||
/dist/
|
||||
/tests/integration/*/dist/
|
||||
|
||||
# Third-party or files that must remain unchanged
|
||||
/spec/expected/
|
||||
/spec/vendor
|
||||
|
||||
# JS-Snippets
|
||||
src/*.js
|
||||
|
||||
+103
-50
@@ -1,66 +1,119 @@
|
||||
module.exports = {
|
||||
extends: ['eslint:recommended', 'plugin:compat/recommended', 'prettier'],
|
||||
globals: {
|
||||
self: false
|
||||
"extends": ["eslint:recommended","plugin:compat/recommended"],
|
||||
"globals": {
|
||||
"self": false,
|
||||
"SOURCE_MAPS": true
|
||||
},
|
||||
env: {
|
||||
node: true,
|
||||
es6: true
|
||||
"env": {
|
||||
"node": true,
|
||||
"es6": true
|
||||
},
|
||||
rules: {
|
||||
'no-console': 'warn',
|
||||
"rules": {
|
||||
// overrides eslint:recommended defaults
|
||||
"no-sparse-arrays": "off",
|
||||
"no-func-assign": "off",
|
||||
"no-console": "warn",
|
||||
"no-debugger": "warn",
|
||||
"no-unreachable": "warn",
|
||||
|
||||
// Possible Errors //
|
||||
//-----------------//
|
||||
"no-unsafe-negation": "error",
|
||||
|
||||
// temporarily disabled until the violating places are fixed.
|
||||
'no-func-assign': 'off',
|
||||
'no-sparse-arrays': 'off',
|
||||
|
||||
// Best Practices //
|
||||
//----------------//
|
||||
'default-case': 'warn',
|
||||
'guard-for-in': 'warn',
|
||||
'no-alert': 'error',
|
||||
'no-caller': 'error',
|
||||
'no-div-regex': 'warn',
|
||||
'no-eval': 'error',
|
||||
'no-extend-native': 'error',
|
||||
'no-extra-bind': 'error',
|
||||
'no-floating-decimal': 'error',
|
||||
'no-implied-eval': 'error',
|
||||
'no-iterator': 'error',
|
||||
'no-labels': 'error',
|
||||
'no-lone-blocks': 'error',
|
||||
'no-loop-func': 'error',
|
||||
'no-multi-str': 'warn',
|
||||
'no-global-assign': 'error',
|
||||
'no-new': 'error',
|
||||
'no-new-func': 'error',
|
||||
'no-new-wrappers': 'error',
|
||||
'no-octal-escape': 'error',
|
||||
'no-process-env': 'error',
|
||||
'no-proto': 'error',
|
||||
'no-return-assign': 'error',
|
||||
'no-script-url': 'error',
|
||||
'no-self-compare': 'error',
|
||||
'no-sequences': 'error',
|
||||
'no-throw-literal': 'error',
|
||||
'no-unused-expressions': 'error',
|
||||
'no-warning-comments': 'warn',
|
||||
'no-with': 'error',
|
||||
radix: 'error',
|
||||
"curly": "error",
|
||||
"default-case": "warn",
|
||||
"dot-notation": ["error", { "allowKeywords": false }],
|
||||
"guard-for-in": "warn",
|
||||
"no-alert": "error",
|
||||
"no-caller": "error",
|
||||
"no-div-regex": "warn",
|
||||
"no-eval": "error",
|
||||
"no-extend-native": "error",
|
||||
"no-extra-bind": "error",
|
||||
"no-floating-decimal": "error",
|
||||
"no-implied-eval": "error",
|
||||
"no-iterator": "error",
|
||||
"no-labels": "error",
|
||||
"no-lone-blocks": "error",
|
||||
"no-loop-func": "error",
|
||||
"no-multi-spaces": "error",
|
||||
"no-multi-str": "warn",
|
||||
"no-global-assign": "error",
|
||||
"no-new": "error",
|
||||
"no-new-func": "error",
|
||||
"no-new-wrappers": "error",
|
||||
"no-octal-escape": "error",
|
||||
"no-process-env": "error",
|
||||
"no-proto": "error",
|
||||
"no-return-assign": "error",
|
||||
"no-script-url": "error",
|
||||
"no-self-compare": "error",
|
||||
"no-sequences": "error",
|
||||
"no-throw-literal": "error",
|
||||
"no-unused-expressions": "error",
|
||||
"no-warning-comments": "warn",
|
||||
"no-with": "error",
|
||||
"radix": "error",
|
||||
"wrap-iife": "error",
|
||||
"no-prototype-builtins": "error",
|
||||
|
||||
|
||||
// Variables //
|
||||
//-----------//
|
||||
'no-label-var': 'error',
|
||||
'no-undef-init': 'error',
|
||||
'no-use-before-define': ['error', 'nofunc'],
|
||||
"no-catch-shadow": "error",
|
||||
"no-label-var": "error",
|
||||
"no-shadow-restricted-names": "error",
|
||||
"no-undef-init": "error",
|
||||
"no-use-before-define": ["error", "nofunc"],
|
||||
|
||||
|
||||
// Stylistic Issues //
|
||||
//------------------//
|
||||
"comma-dangle": ["error", "never"],
|
||||
"quote-props": ["error", "as-needed", { "keywords": true, "unnecessary": false }],
|
||||
"brace-style": ["error", "1tbs", { "allowSingleLine": true }],
|
||||
"camelcase": "error",
|
||||
"comma-spacing": ["error", { "before": false, "after": true }],
|
||||
"comma-style": ["error", "last"],
|
||||
"consistent-this": ["warn", "self"],
|
||||
"eol-last": "error",
|
||||
"func-style": ["error", "declaration"],
|
||||
"key-spacing": ["error", {
|
||||
"beforeColon": false,
|
||||
"afterColon": true
|
||||
}],
|
||||
"new-cap": "error",
|
||||
"new-parens": "error",
|
||||
"no-array-constructor": "error",
|
||||
"no-lonely-if": "error",
|
||||
"no-mixed-spaces-and-tabs": "error",
|
||||
"no-nested-ternary": "warn",
|
||||
"no-new-object": "error",
|
||||
"no-spaced-func": "error",
|
||||
"no-trailing-spaces": "error",
|
||||
"no-extra-parens": ["error", "functions"],
|
||||
"quotes": ["error", "single", "avoid-escape"],
|
||||
"semi": "error",
|
||||
"semi-spacing": ["error", { "before": false, "after": true }],
|
||||
"keyword-spacing": "error",
|
||||
"space-before-blocks": ["error", "always"],
|
||||
"space-before-function-paren": ["error", { "anonymous": "never", "named": "never" }],
|
||||
"space-in-parens": ["error", "never"],
|
||||
"space-infix-ops": "error",
|
||||
"space-unary-ops": "error",
|
||||
"spaced-comment": ["error", "always", { "markers": [","] }],
|
||||
"wrap-regex": "warn",
|
||||
|
||||
// ECMAScript 6 //
|
||||
//--------------//
|
||||
'no-var': 'error'
|
||||
"no-var": "warn"
|
||||
},
|
||||
parserOptions: {
|
||||
sourceType: 'module',
|
||||
ecmaVersion: 6,
|
||||
ecmaFeatures: {}
|
||||
"parserOptions": {
|
||||
"sourceType": "module",
|
||||
"ecmaVersion": 6,
|
||||
"ecmaFeatures": {}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: npm
|
||||
directory: "/"
|
||||
open-pull-requests-limit: 0
|
||||
schedule:
|
||||
interval: weekly
|
||||
allow:
|
||||
- dependency-type: production
|
||||
@@ -1,89 +0,0 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request: {}
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: 'ubuntu-latest'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '16'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
test:
|
||||
name: Test (Node)
|
||||
runs-on: ${{ matrix.operating-system }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
operating-system: ['ubuntu-latest', 'windows-latest']
|
||||
# https://nodejs.org/en/about/releases/
|
||||
node-version: ['16', '18', '20', '22']
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Test
|
||||
run: npm run test
|
||||
|
||||
- name: Test (Integration)
|
||||
# https://github.com/webpack/webpack/issues/14532
|
||||
if: ${{ matrix.node-version == '16' }}
|
||||
run: |
|
||||
cd ./tests/integration/rollup-test && ./test.sh && cd -
|
||||
cd ./tests/integration/webpack-babel-test && ./test.sh && cd -
|
||||
cd ./tests/integration/webpack-test && ./test.sh && cd -
|
||||
|
||||
browser:
|
||||
name: Test (Browser)
|
||||
runs-on: 'ubuntu-22.04'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '16'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Install Playwright
|
||||
run: |
|
||||
npx playwright install-deps
|
||||
npx playwright install
|
||||
|
||||
- name: Build
|
||||
run: npx grunt prepare
|
||||
|
||||
- name: Test
|
||||
run: npm run test:browser
|
||||
@@ -1,38 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
publish-aws-s3:
|
||||
name: Publish to AWS S3
|
||||
runs-on: 'ubuntu-latest'
|
||||
environment: 'builds.handlebarsjs.com.s3.amazonaws.com'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: '16'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Publish
|
||||
run: |
|
||||
git config --global user.email "release@handlebarsjs.com"
|
||||
git config --global user.name "handlebars-lang"
|
||||
npm run publish:aws
|
||||
env:
|
||||
S3_BUCKET_NAME: "builds.handlebarsjs.com"
|
||||
S3_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY_ID }}
|
||||
S3_SECRET_ACCESS_KEY: ${{ secrets.S3_SECRET_ACCESS_KEY }}
|
||||
+7
-12
@@ -1,20 +1,15 @@
|
||||
vendor
|
||||
.rvmrc
|
||||
.DS_Store
|
||||
lib/handlebars/compiler/parser.js
|
||||
/dist/
|
||||
/tmp/
|
||||
/coverage/
|
||||
node_modules
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
npm-debug.log
|
||||
sauce_connect.log*
|
||||
.idea
|
||||
/yarn-error.log
|
||||
/yarn.lock
|
||||
node_modules
|
||||
yarn-error.log
|
||||
/handlebars-release.tgz
|
||||
.nyc_output
|
||||
|
||||
# Generated files
|
||||
lib/handlebars/compiler/parser.js
|
||||
/coverage/
|
||||
/dist/
|
||||
/test-results/
|
||||
/tests/integration/*/dist/
|
||||
/spec/tmp/*
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
[submodule "spec/mustache"]
|
||||
path = spec/mustache
|
||||
url = https://github.com/mustache/spec.git
|
||||
url = git://github.com/mustache/spec.git
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
instrumentation:
|
||||
excludes: ['**/spec/**', '**/handlebars/compiler/parser.js']
|
||||
@@ -1,22 +0,0 @@
|
||||
.rvmrc
|
||||
.DS_Store
|
||||
/tmp/
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
npm-debug.log
|
||||
sauce_connect.log*
|
||||
.idea
|
||||
yarn-error.log
|
||||
node_modules
|
||||
/handlebars-release.tgz
|
||||
.nyc_output
|
||||
|
||||
# Generated files
|
||||
lib/handlebars/compiler/parser.js
|
||||
/coverage/
|
||||
/dist/
|
||||
/tests/integration/*/dist/
|
||||
|
||||
# Third-party or files that must remain unchanged
|
||||
/spec/expected/
|
||||
/spec/vendor
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
language: node_js
|
||||
before_install:
|
||||
- npm install -g grunt-cli
|
||||
script:
|
||||
- grunt --stack travis
|
||||
email:
|
||||
on_failure: change
|
||||
on_success: never
|
||||
env:
|
||||
global:
|
||||
- S3_BUCKET_NAME=builds.handlebarsjs.com
|
||||
- secure: ckyEe5dzjdFDjmZ6wIrhGm0CFBEnKq8c1dYptfgVV/Q5/nJFGzu8T0yTjouS/ERxzdT2H327/63VCxhFnLCRHrsh4rlW/rCy4XI3O/0TeMLgFPa4TXkO8359qZ4CB44TBb3NsJyQXNMYdJpPLTCVTMpuiqqkFFOr+6OeggR7ufA=
|
||||
- secure: Nm4AgSfsgNB21kgKrF9Tl7qVZU8YYREhouQunFracTcZZh2NZ2XH5aHuSiXCj88B13Cr/jGbJKsZ4T3QS3wWYtz6lkyVOx3H3iI+TMtqhD9RM3a7A4O+4vVN8IioB2YjhEu0OKjwgX5gp+0uF+pLEi7Hpj6fupD3AbbL5uYcKg8=
|
||||
matrix:
|
||||
include:
|
||||
- node_js: '10'
|
||||
env:
|
||||
- PUBLISH=true
|
||||
- secure: pLTzghtVll9yGKJI0AaB0uI8GypfWxLTaIB0ZL8//yN3nAEIKMhf/RRilYTsn/rKj2NUa7vt2edYILi3lttOUlCBOwTc9amiRms1W8Lwr/3IdWPeBLvLuH1zNJRm2lBAwU4LBSqaOwhGaxOQr6KHTnWudhNhgOucxpZfvfI/dFw=
|
||||
- secure: yERYCf7AwL11D9uMtacly/THGV8BlzsMmrt+iQVvGA3GaY6QMmfYqf6P6cCH98sH5etd1Y+1e6YrPeMjqI6lyRllT7FptoyOdHulazQe86VQN4sc0EpqMlH088kB7gGjTut9Z+X9ViooT5XEh9WA5jXEI9pXhQJNoIHkWPuwGuY=
|
||||
cache:
|
||||
directories:
|
||||
- node_modules
|
||||
|
||||
git:
|
||||
depth: 100
|
||||
+37
-127
@@ -2,18 +2,18 @@
|
||||
|
||||
## Reporting Issues
|
||||
|
||||
Please see our [FAQ](https://github.com/handlebars-lang/handlebars.js/blob/master/FAQ.md) for common issues that people run into.
|
||||
Please see our [FAQ](https://github.com/wycats/handlebars.js/blob/master/FAQ.md) for common issues that people run into.
|
||||
|
||||
Should you run into other issues with the project, please don't hesitate to let us know by filing an [issue][issue]! In general we are going to ask for an example of the problem failing, which can be as simple as a jsfiddle/jsbin/etc. We've put together a jsfiddle [template][jsfiddle] to ease this. (We will keep this link up to date as new releases occur, so feel free to check back here)
|
||||
|
||||
Pull requests containing only failing tests demonstrating the issue are welcomed and this also helps ensure that your issue won't regress in the future once it's fixed.
|
||||
|
||||
Documentation issues on the [handlebarsjs.com](https://handlebarsjs.com) site should be reported on [handlebars-lang/docs](https://github.com/handlebars-lang/docs).
|
||||
Documentation issues on the handlebarsjs.com site should be reported on [handlebars-site](https://github.com/wycats/handlebars-site).
|
||||
|
||||
## Branches
|
||||
|
||||
- The branch `4.x` contains the currently released version. Bugfixes should be made in this branch.
|
||||
- The branch `master` contains the next version. A release date is not yet specified. Maintainers
|
||||
* The branch `4.x` contains the currently released version. Bugfixes should be made in this branch.
|
||||
* The branch `master` contains the next version. A release date is not yet specified. Maintainers
|
||||
should merge the branch `4.x` into the master branch regularly.
|
||||
|
||||
## Pull Requests
|
||||
@@ -21,7 +21,6 @@ Documentation issues on the [handlebarsjs.com](https://handlebarsjs.com) site sh
|
||||
We also accept [pull requests][pull-request]!
|
||||
|
||||
Generally we like to see pull requests that
|
||||
|
||||
- Maintain the existing code style
|
||||
- Are focused on a single change (i.e. avoid large refactoring or style adjustments in untouched code if not the primary goal of the pull request)
|
||||
- Have [good commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
|
||||
@@ -32,8 +31,8 @@ Generally we like to see pull requests that
|
||||
|
||||
To build Handlebars.js you'll need a few things installed.
|
||||
|
||||
- Node.js
|
||||
- [Grunt](http://gruntjs.com/getting-started)
|
||||
* Node.js
|
||||
* [Grunt](http://gruntjs.com/getting-started)
|
||||
|
||||
Before building, you need to make sure that the Git submodule `spec/mustache` is included (i.e. the directory `spec/mustache` should not be empty). To include it, if using Git version 1.6.5 or newer, use `git clone --recursive` rather than `git clone`. Or, if you already cloned without `--recursive`, use `git submodule update --init`.
|
||||
|
||||
@@ -47,18 +46,16 @@ You can also run our set of benchmarks with `grunt bench`.
|
||||
The `grunt dev` implements watching for tests and allows for in browser testing at `http://localhost:9999/spec/`.
|
||||
|
||||
If you notice any problems, please report them to the GitHub issue tracker at
|
||||
[http://github.com/handlebars-lang/handlebars.js/issues](http://github.com/handlebars-lang/handlebars.js/issues).
|
||||
[http://github.com/wycats/handlebars.js/issues](http://github.com/wycats/handlebars.js/issues).
|
||||
|
||||
## Running Tests
|
||||
##Running Tests
|
||||
|
||||
To run tests locally, first install all dependencies.
|
||||
|
||||
```sh
|
||||
npm install
|
||||
```
|
||||
|
||||
Clone the mustache specs into the spec/mustache folder.
|
||||
|
||||
```sh
|
||||
cd spec
|
||||
rm -r mustache
|
||||
@@ -66,141 +63,54 @@ git clone https://github.com/mustache/spec.git mustache
|
||||
```
|
||||
|
||||
From the root directory, run the tests.
|
||||
|
||||
```sh
|
||||
npm test
|
||||
```
|
||||
|
||||
## Linting and Formatting
|
||||
## Ember testing
|
||||
|
||||
Handlebars uses `eslint` to enforce best-practices and `prettier` to auto-format files.
|
||||
We do linting and formatting in two phases:
|
||||
The current ember distribution should be tested as part of the handlebars release process. This requires building the `handlebars-source` gem locally and then executing the ember test script.
|
||||
|
||||
- Committed files are linted and formatted in a pre-commit hook. In this stage eslint-errors are forbidden,
|
||||
while warnings are allowed.
|
||||
- The GitHub CI job also lints all files and checks if they are formatted correctly. In this stage, warnings
|
||||
are forbidden.
|
||||
```sh
|
||||
npm link
|
||||
grunt build release
|
||||
cp dist/*.js $emberRepoDir/bower_components/handlebars/
|
||||
|
||||
You can use the following scripts to make sure that the CI job does not fail:
|
||||
|
||||
- **npm run lint** will run `eslint` and fail on warnings
|
||||
- **npm run format** will run `prettier` on all files
|
||||
- **npm run check-before-pull-request** will perform all most checks that our CI job does in its build-job, excluding the "integration-test".
|
||||
- **npm run test:integration** will run integration tests (using old NodeJS versions and integrations with webpack, babel and so on)
|
||||
These tests only work on a Linux-machine with `nvm` installed (for running tests in multiple versions of NodeJS).
|
||||
cd $emberRepoDir
|
||||
npm link handlebars
|
||||
npm test
|
||||
```
|
||||
|
||||
## Releasing the latest version
|
||||
|
||||
Before attempting the release Handlebars, please make sure that you have the following authorizations:
|
||||
*When releasing a previous version of Handlebars, please look into the CONTRIBUNG.md in the corresponding branch.*
|
||||
|
||||
- Push-access to [handlebars-lang/handlebars.js](https://github.com/handlebars-lang/handlebars.js/)
|
||||
- Publishing rights on npmjs.com for the [handlebars](https://www.npmjs.com/package/handlebars) package
|
||||
- Publishing rights on rubygems for the [handlebars-source](https://rubygems.org/gems/handlebars-source) package
|
||||
- Push-access to the repo for legacy package managers: [components/handlebars.js](https://github.com/components/handlebars.js)
|
||||
- Push-access to the production-repo of the handlebars site: [handlebars-lang/docs](https://github.com/handlebars-lang/docs)
|
||||
Handlebars utilizes the [release yeoman generator][generator-release] to perform most release tasks.
|
||||
|
||||
_When releasing a previous version of Handlebars, please look into the CONTRIBUNG.md in the corresponding branch._
|
||||
A full release may be completed with the following:
|
||||
|
||||
A full release via Docker may be completed with the following:
|
||||
```
|
||||
npm ci
|
||||
yo release
|
||||
npm publish
|
||||
yo release:publish components handlebars.js dist/components/
|
||||
|
||||
1. Create a `Dockerfile` in this folder for releasing
|
||||
```Dockerfile
|
||||
FROM node:10-slim
|
||||
|
||||
ENV EDITOR=vim
|
||||
|
||||
# Update stretch repositories
|
||||
RUN sed -i -e 's/deb.debian.org/archive.debian.org/g' \
|
||||
-e 's|security.debian.org|archive.debian.org/|g' \
|
||||
-e '/stretch-updates/d' /etc/apt/sources.list
|
||||
|
||||
# Install release dependencies
|
||||
RUN apt-get update
|
||||
RUN apt-get install -y git vim
|
||||
|
||||
# Work around deprecated npm dependency install via unauthenticated git-protocol:
|
||||
# https://github.com/kpdecker/generator-release/blob/87aab9b84c9f083635c3fcc822f18acce1f48736/package.json#L31
|
||||
RUN git config --system url."https://github.com/".insteadOf git://github.com/
|
||||
|
||||
# Configure git
|
||||
RUN git config --system user.email "release@handlebarsjs.com"
|
||||
RUN git config --system user.name "handlebars-lang"
|
||||
|
||||
RUN mkdir /home/node/.config
|
||||
RUN mkdir /home/node/.ssh
|
||||
RUN mkdir /home/node/tmp
|
||||
|
||||
# Generate config for yo generator-release:
|
||||
# https://github.com/kpdecker/generator-release#example
|
||||
# You have to add a valid GitHub access token! (Used for reading issues and pull requests.)
|
||||
RUN echo "module.exports = {\n auth: 'oauth',\n token: 'GitHub personal access token'\n};" > /home/node/.config/generator-release
|
||||
RUN chown -R node:node /home/node/.config
|
||||
RUN chown -R node:node /home/node/.ssh
|
||||
RUN chown -R node:node /home/node/tmp
|
||||
|
||||
# Add the generated key to GitHub: https://github.com/settings/keys
|
||||
RUN ssh-keygen -q -t ed25519 -N '' -f /home/node/.ssh/id_ed25519 -C "release@handlebarsjs.com"
|
||||
RUN chmod 0600 /home/node/.ssh/id_ed25519*
|
||||
RUN chown node:node /home/node/.ssh/id_ed25519*
|
||||
```
|
||||
2. Build and run the Docker image
|
||||
```bash
|
||||
docker build --tag handlebars:release .
|
||||
docker run --rm --interactive --tty \
|
||||
--volume $PWD:/app \
|
||||
--workdir /app \
|
||||
--user $(id -u):$(id -g) \
|
||||
--env NPM_CONFIG_PREFIX=/home/node/.npm-global \
|
||||
handlebars:release bash -c 'export PATH=$PATH:/home/node/.npm-global/bin; bash'
|
||||
```
|
||||
* Add SSH key to GitHub: `cat /home/node/.ssh/id_ed25519.pub` (https://github.com/settings/keys)
|
||||
* Add GitHub API token: `vi /home/node/.config/generator-release`
|
||||
* Execute the following steps:
|
||||
```bash
|
||||
npm install
|
||||
npm install -g yo@1 grunt@1 generator-release
|
||||
npm run release
|
||||
# Warning! This step will collect data from GitHub, bump the version,
|
||||
# create a new commit, create a new tag and push it to GitHub.
|
||||
# https://github.com/kpdecker/generator-release?tab=readme-ov-file#usage
|
||||
yo release
|
||||
npm login
|
||||
npm publish
|
||||
yo release:publish components handlebars.js dist/components/
|
||||
```
|
||||
6. Publish Ruby `handlebars-source` gem:
|
||||
```bash
|
||||
docker run --rm --interactive --tty \
|
||||
--volume $PWD:/app \
|
||||
--workdir /app \
|
||||
ruby:3.2-slim bash
|
||||
```
|
||||
* Execute the following steps:
|
||||
```bash
|
||||
cd dist/components/
|
||||
gem build handlebars-source.gemspec
|
||||
gem push handlebars-source-*.gem
|
||||
```
|
||||
|
||||
### After the release
|
||||
cd dist/components/
|
||||
gem build handlebars-source.gemspec
|
||||
gem push handlebars-source-*.gem
|
||||
```
|
||||
|
||||
After the release, you should check that all places have really been updated. Especially verify that the `latest`-tags
|
||||
in those places still point to the latest version
|
||||
|
||||
- [The npm-package](https://www.npmjs.com/package/handlebars) (check latest-tag)
|
||||
- [The bower package](https://github.com/components/handlebars.js) (check the package.json)
|
||||
- [The AWS S3 Bucket](https://s3.amazonaws.com/builds.handlebarsjs.com) (check latest-tag)
|
||||
- [RubyGems](https://rubygems.org/gems/handlebars-source)
|
||||
* [The npm-package](https://www.npmjs.com/package/handlebars) (check latest-tag)
|
||||
* [The bower package](https://github.com/components/handlebars.js) (check the package.json)
|
||||
* [The AWS S3 Bucket](https://s3.amazonaws.com/builds.handlebarsjs.com) (check latest-tag)
|
||||
* [RubyGems](https://rubygems.org/gems/handlebars-source)
|
||||
|
||||
When everything is OK, the **handlebars site** needs to be updated.
|
||||
|
||||
Go to the master branch of the repo [handlebars-lang/docs](https://github.com/handlebars-lang/docs/tree/master)
|
||||
and make a minimal change to the README. This will invoke a github-action that redeploys
|
||||
the site, fetching the latest version-number from the npm-registry.
|
||||
(note that the default-branch of this repo is not the master and regular changes are done
|
||||
in the `handlebars-lang/docs`-repo).
|
||||
When everything is OK, the handlebars site needs to be updated to point to the new version numbers. The jsfiddle link should be updated to point to the most recent distribution for all instances in our documentation.
|
||||
|
||||
[generator-release]: https://github.com/walmartlabs/generator-release
|
||||
[pull-request]: https://github.com/handlebars-lang/handlebars.js/pull/new/master
|
||||
[issue]: https://github.com/handlebars-lang/handlebars.js/issues/new
|
||||
[pull-request]: https://github.com/wycats/handlebars.js/pull/new/master
|
||||
[issue]: https://github.com/wycats/handlebars.js/issues/new
|
||||
[jsfiddle]: https://jsfiddle.net/9D88g/180/
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
1. How can I file a bug report:
|
||||
|
||||
See our guidelines on [reporting issues](https://github.com/handlebars-lang/handlebars.js/blob/master/CONTRIBUTING.md#reporting-issues).
|
||||
See our guidelines on [reporting issues](https://github.com/wycats/handlebars.js/blob/master/CONTRIBUTING.md#reporting-issues).
|
||||
|
||||
1. Why isn't my Mustache template working?
|
||||
|
||||
Handlebars deviates from Mustache slightly on a few behaviors. These variations are documented in our [readme](https://github.com/handlebars-lang/handlebars.js#differences-between-handlebarsjs-and-mustache).
|
||||
Handlebars deviates from Mustache slightly on a few behaviors. These variations are documented in our [readme](https://github.com/wycats/handlebars.js#differences-between-handlebarsjs-and-mustache).
|
||||
|
||||
1. Why is it slower when compiling?
|
||||
|
||||
@@ -36,18 +36,16 @@
|
||||
```sh
|
||||
handlebars --version
|
||||
```
|
||||
|
||||
If using the integrated precompiler and
|
||||
|
||||
```javascript
|
||||
console.log(Handlebars.VERSION);
|
||||
```
|
||||
|
||||
On the client side.
|
||||
|
||||
We include the built client libraries in the npm package for those who want to be certain that they are using the same client libraries as the compiler.
|
||||
|
||||
Should these match, please file an issue with us, per our [issue filing guidelines](https://github.com/handlebars-lang/handlebars.js/blob/master/CONTRIBUTING.md#reporting-issues).
|
||||
Should these match, please file an issue with us, per our [issue filing guidelines](https://github.com/wycats/handlebars.js/blob/master/CONTRIBUTING.md#reporting-issues).
|
||||
|
||||
1. Why doesn't IE like the `default` name in the AMD module?
|
||||
|
||||
@@ -55,8 +53,8 @@
|
||||
|
||||
1. How do I load the runtime library when using AMD?
|
||||
|
||||
There are two options for loading under AMD environments. The first is to use the `handlebars.runtime.amd.js` file. This may require a [path mapping](https://github.com/handlebars-lang/handlebars.js/blob/master/spec/amd-runtime.html#L31) as well as access via the `default` field.
|
||||
There are two options for loading under AMD environments. The first is to use the `handlebars.runtime.amd.js` file. This may require a [path mapping](https://github.com/wycats/handlebars.js/blob/master/spec/amd-runtime.html#L31) as well as access via the `default` field.
|
||||
|
||||
The other option is to load the `handlebars.runtime.js` UMD build, which might not require path configuration and exposes the library as both the module root and the `default` field for compatibility.
|
||||
The other option is to load the `handlebars.runtime.js` UMD build, which might not require path configuration and exposes the library as both the module root and the `default` field for compatibility.
|
||||
|
||||
If not using ES6 transpilers or accessing submodules in the build the former option should be sufficient for most use cases.
|
||||
|
||||
+117
-162
@@ -1,151 +1,82 @@
|
||||
/* eslint-disable no-process-env */
|
||||
module.exports = function(grunt) {
|
||||
|
||||
grunt.initConfig({
|
||||
pkg: grunt.file.readJSON('package.json'),
|
||||
|
||||
clean: [
|
||||
'tmp',
|
||||
'dist',
|
||||
'lib/handlebars/compiler/parser.js',
|
||||
'/tests/integration/**/node_modules'
|
||||
],
|
||||
eslint: {
|
||||
files: [
|
||||
'*.js',
|
||||
'bench/**/*.js',
|
||||
'tasks/**/*.js',
|
||||
'lib/**/!(*.min|parser).js',
|
||||
'spec/**/!(*.amd|json2|require).js',
|
||||
'integration-testing/multi-nodejs-test/*.js',
|
||||
'integration-testing/webpack-test/*.js',
|
||||
'integration-testing/webpack-test/src/*.js'
|
||||
]
|
||||
},
|
||||
|
||||
clean: ['tmp', 'dist', 'lib/handlebars/compiler/parser.js', 'integration-testing/**/node_modules'],
|
||||
|
||||
copy: {
|
||||
dist: {
|
||||
options: {
|
||||
processContent: function(content) {
|
||||
return (
|
||||
grunt.template.process(
|
||||
'/**!\n\n @license\n <%= pkg.name %> v<%= pkg.version %>\n\n<%= grunt.file.read("LICENSE") %>\n*/\n'
|
||||
) + content
|
||||
);
|
||||
return grunt.template.process('/**!\n\n @license\n <%= pkg.name %> v<%= pkg.version %>\n\n<%= grunt.file.read("LICENSE") %>\n*/\n')
|
||||
+ content;
|
||||
}
|
||||
},
|
||||
files: [{ expand: true, cwd: 'dist/', src: ['*.js'], dest: 'dist/' }]
|
||||
files: [
|
||||
{expand: true, cwd: 'dist/', src: ['*.js'], dest: 'dist/'}
|
||||
]
|
||||
},
|
||||
cdnjs: {
|
||||
files: [
|
||||
{ expand: true, cwd: 'dist/', src: ['*.js'], dest: 'dist/cdnjs' }
|
||||
{expand: true, cwd: 'dist/', src: ['*.js'], dest: 'dist/cdnjs'}
|
||||
]
|
||||
},
|
||||
components: {
|
||||
files: [
|
||||
{
|
||||
expand: true,
|
||||
cwd: 'components/',
|
||||
src: ['**'],
|
||||
dest: 'dist/components'
|
||||
},
|
||||
{ expand: true, cwd: 'dist/', src: ['*.js'], dest: 'dist/components' }
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
babel: {
|
||||
options: {
|
||||
sourceMaps: 'inline',
|
||||
loose: ['es6.modules'],
|
||||
auxiliaryCommentBefore: 'istanbul ignore next'
|
||||
},
|
||||
amd: {
|
||||
options: {
|
||||
modules: 'amd'
|
||||
},
|
||||
files: [
|
||||
{
|
||||
expand: true,
|
||||
cwd: 'lib/',
|
||||
src: '**/!(index).js',
|
||||
dest: 'dist/amd/'
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
cjs: {
|
||||
options: {
|
||||
modules: 'common'
|
||||
},
|
||||
files: [
|
||||
{
|
||||
cwd: 'lib/',
|
||||
expand: true,
|
||||
src: '**/!(index).js',
|
||||
dest: 'dist/cjs/'
|
||||
}
|
||||
{expand: true, cwd: 'components/', src: ['**'], dest: 'dist/components'},
|
||||
{expand: true, cwd: 'dist/', src: ['*.js'], dest: 'dist/components'}
|
||||
]
|
||||
}
|
||||
},
|
||||
webpack: {
|
||||
build: require('./webpack.config')
|
||||
},
|
||||
babel: {
|
||||
options: {
|
||||
context: __dirname,
|
||||
module: {
|
||||
loaders: [
|
||||
// the optional 'runtime' transformer tells babel to require the runtime instead of inlining it.
|
||||
{
|
||||
test: /\.jsx?$/,
|
||||
exclude: /node_modules/,
|
||||
loader:
|
||||
'babel-loader?optional=runtime&loose=es6.modules&auxiliaryCommentBefore=istanbul%20ignore%20next'
|
||||
}
|
||||
sourceMaps: 'inline',
|
||||
auxiliaryCommentBefore: 'istanbul ignore next'
|
||||
},
|
||||
amd: {
|
||||
options: {
|
||||
plugins: ['@babel/plugin-transform-modules-amd']
|
||||
},
|
||||
files: [{
|
||||
expand: true,
|
||||
cwd: 'lib/',
|
||||
src: '**/!(index).js',
|
||||
dest: 'dist/amd/'
|
||||
}]
|
||||
},
|
||||
|
||||
cjs: {
|
||||
options: {
|
||||
plugins: [
|
||||
'@babel/plugin-transform-modules-commonjs',
|
||||
// support "import * as Handlebars" for backward-compatibility
|
||||
'babel-plugin-add-module-exports'
|
||||
]
|
||||
},
|
||||
output: {
|
||||
path: 'dist/',
|
||||
library: 'Handlebars',
|
||||
libraryTarget: 'umd'
|
||||
}
|
||||
},
|
||||
handlebars: {
|
||||
entry: './lib/handlebars.js',
|
||||
output: {
|
||||
filename: 'handlebars.js'
|
||||
}
|
||||
},
|
||||
runtime: {
|
||||
entry: './lib/handlebars.runtime.js',
|
||||
output: {
|
||||
filename: 'handlebars.runtime.js'
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
requirejs: {
|
||||
options: {
|
||||
optimize: 'none',
|
||||
baseUrl: 'dist/amd/'
|
||||
},
|
||||
dist: {
|
||||
options: {
|
||||
name: 'handlebars',
|
||||
out: 'dist/handlebars.amd.js'
|
||||
}
|
||||
},
|
||||
runtime: {
|
||||
options: {
|
||||
name: 'handlebars.runtime',
|
||||
out: 'dist/handlebars.runtime.amd.js'
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
uglify: {
|
||||
options: {
|
||||
mangle: true,
|
||||
compress: true,
|
||||
preserveComments: /(?:^!|@(?:license|preserve|cc_on))/
|
||||
},
|
||||
dist: {
|
||||
files: [
|
||||
{
|
||||
cwd: 'dist/',
|
||||
expand: true,
|
||||
src: ['handlebars*.js', '!*.min.js'],
|
||||
dest: 'dist/',
|
||||
rename: function(dest, src) {
|
||||
return dest + src.replace(/\.js$/, '.min.js');
|
||||
}
|
||||
}
|
||||
]
|
||||
files: [{
|
||||
cwd: 'lib/',
|
||||
expand: true,
|
||||
src: '**/!(index).js',
|
||||
dest: 'dist/cjs/'
|
||||
}]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -165,13 +96,50 @@ module.exports = function(grunt) {
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
shell: {
|
||||
integrationTests: {
|
||||
command: './tests/integration/run-integration-tests.sh'
|
||||
'saucelabs-mocha': {
|
||||
all: {
|
||||
options: {
|
||||
build: process.env.TRAVIS_JOB_ID,
|
||||
urls: ['http://localhost:9999/spec/?headless=true', 'http://localhost:9999/spec/amd.html?headless=true'],
|
||||
detailedError: true,
|
||||
concurrency: 4,
|
||||
browsers: [
|
||||
{browserName: 'chrome'},
|
||||
{browserName: 'firefox', platform: 'Linux'},
|
||||
// {browserName: 'safari', version: 9, platform: 'OS X 10.11'},
|
||||
// {browserName: 'safari', version: 8, platform: 'OS X 10.10'},
|
||||
{browserName: 'internet explorer', version: 11, platform: 'Windows 8.1'},
|
||||
{browserName: 'internet explorer', version: 10, platform: 'Windows 8'}
|
||||
]
|
||||
}
|
||||
},
|
||||
sanity: {
|
||||
options: {
|
||||
build: process.env.TRAVIS_JOB_ID,
|
||||
urls: ['http://localhost:9999/spec/umd.html?headless=true', 'http://localhost:9999/spec/amd-runtime.html?headless=true', 'http://localhost:9999/spec/umd-runtime.html?headless=true'],
|
||||
detailedError: true,
|
||||
concurrency: 2,
|
||||
browsers: [
|
||||
{browserName: 'chrome'}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
bgShell: {
|
||||
checkTypes: {
|
||||
cmd: 'npm run checkTypes',
|
||||
bg: false,
|
||||
fail: true
|
||||
},
|
||||
integrationTests: {
|
||||
cmd: './integration-testing/run-integration-tests.sh',
|
||||
bg: false,
|
||||
fail: true
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
watch: {
|
||||
scripts: {
|
||||
options: {
|
||||
@@ -179,59 +147,46 @@ module.exports = function(grunt) {
|
||||
},
|
||||
|
||||
files: ['src/*', 'lib/**/*.js', 'spec/**/*.js'],
|
||||
tasks: ['on-file-change']
|
||||
tasks: ['build', 'amd', 'tests', 'test']
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Build a new version of the library
|
||||
this.registerTask('build', 'Builds a distributable version of the current project', [
|
||||
'eslint',
|
||||
'bgShell:checkTypes',
|
||||
'parser',
|
||||
'node',
|
||||
'globals']);
|
||||
|
||||
this.registerTask('amd', ['babel:amd']);
|
||||
this.registerTask('node', ['babel:cjs']);
|
||||
this.registerTask('globals', ['webpack']);
|
||||
this.registerTask('tests', ['concat:tests']);
|
||||
|
||||
this.registerTask('release', 'Build final packages', ['eslint', 'amd', 'test:min', 'copy:dist', 'copy:components', 'copy:cdnjs']);
|
||||
|
||||
// Load tasks from npm
|
||||
grunt.loadNpmTasks('grunt-contrib-clean');
|
||||
grunt.loadNpmTasks('grunt-contrib-concat');
|
||||
grunt.loadNpmTasks('grunt-contrib-connect');
|
||||
grunt.loadNpmTasks('grunt-contrib-copy');
|
||||
grunt.loadNpmTasks('grunt-contrib-requirejs');
|
||||
grunt.loadNpmTasks('grunt-contrib-uglify');
|
||||
grunt.loadNpmTasks('grunt-contrib-watch');
|
||||
grunt.loadNpmTasks('grunt-babel');
|
||||
grunt.loadNpmTasks('grunt-shell');
|
||||
grunt.loadNpmTasks('grunt-bg-shell');
|
||||
grunt.loadNpmTasks('grunt-eslint');
|
||||
grunt.loadNpmTasks('@knappi/grunt-saucelabs');
|
||||
grunt.loadNpmTasks('grunt-webpack');
|
||||
|
||||
grunt.task.loadTasks('tasks');
|
||||
|
||||
grunt.registerTask('node', ['babel:cjs']);
|
||||
grunt.registerTask('amd', ['babel:amd', 'requirejs']);
|
||||
grunt.registerTask('globals', ['webpack']);
|
||||
grunt.registerTask('release', 'Build final packages', [
|
||||
'uglify',
|
||||
'test:min',
|
||||
'copy:dist',
|
||||
'copy:components',
|
||||
'copy:cdnjs'
|
||||
]);
|
||||
grunt.registerTask('bench', ['metrics']);
|
||||
grunt.registerTask('sauce', process.env.SAUCE_USERNAME ? ['tests', 'connect', 'saucelabs-mocha'] : []);
|
||||
|
||||
// Requires secret properties from .travis.yaml
|
||||
grunt.registerTask('extensive-tests-and-publish-to-aws', [
|
||||
'default',
|
||||
'shell:integrationTests',
|
||||
'metrics',
|
||||
'publish-to-aws'
|
||||
]);
|
||||
grunt.registerTask('travis', process.env.PUBLISH ? ['default', 'bgShell:integrationTests', 'sauce', 'metrics', 'publish:latest'] : ['default']);
|
||||
|
||||
grunt.registerTask('on-file-change', ['build', 'concat:tests', 'test']);
|
||||
|
||||
// === Primary tasks ===
|
||||
grunt.registerTask('dev', ['clean', 'connect', 'watch']);
|
||||
grunt.registerTask('default', ['clean', 'build', 'test', 'release']);
|
||||
grunt.registerTask('test', ['test:bin', 'test:cov']);
|
||||
grunt.registerTask('bench', ['metrics']);
|
||||
grunt.registerTask('prepare', ['build', 'concat:tests']);
|
||||
grunt.registerTask(
|
||||
'build',
|
||||
'Builds a distributable version of the current project',
|
||||
['parser', 'node', 'amd', 'globals']
|
||||
);
|
||||
grunt.registerTask('integration-tests', [
|
||||
'default',
|
||||
'shell:integrationTests'
|
||||
]);
|
||||
grunt.registerTask('integration-tests', ['default', 'bgShell:integrationTests']);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright (C) 2011-2019 by Yehuda Katz
|
||||
Copyright (C) 2011-2017 by Yehuda Katz
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
+24
-23
@@ -1,29 +1,28 @@
|
||||
[](https://github.com/handlebars-lang/handlebars.js/actions/workflows/ci.yml)
|
||||
[](https://www.jsdelivr.com/package/npm/handlebars)
|
||||
[](https://www.npmjs.com/package/handlebars)
|
||||
[](https://www.npmjs.com/package/handlebars)
|
||||
[](https://bundlephobia.com/package/handlebars)
|
||||
[](https://packagephobia.com/result?p=handlebars)
|
||||
[](https://travis-ci.org/wycats/handlebars.js)
|
||||
[](https://ci.appveyor.com/project/wycats/handlebars-js)
|
||||
[](https://saucelabs.com/u/handlebars)
|
||||
|
||||
Handlebars.js
|
||||
=============
|
||||
|
||||
Handlebars provides the power necessary to let you build **semantic templates** effectively with no frustration.
|
||||
Handlebars is largely compatible with Mustache templates. In most cases it is possible to swap out Mustache with Handlebars and continue using your current templates.
|
||||
Handlebars.js is an extension to the [Mustache templating
|
||||
language](http://mustache.github.com/) created by Chris Wanstrath.
|
||||
Handlebars.js and Mustache are both logicless templating languages that
|
||||
keep the view and the code separated like we all know they should be.
|
||||
|
||||
Checkout the official Handlebars docs site at
|
||||
[handlebarsjs.com](https://handlebarsjs.com) and try our [live demo](https://handlebarsjs.com/playground.html).
|
||||
[http://www.handlebarsjs.com](http://www.handlebarsjs.com) and the live demo at [http://tryhandlebarsjs.com/](http://tryhandlebarsjs.com/).
|
||||
|
||||
Installing
|
||||
----------
|
||||
|
||||
See our [installation documentation](https://handlebarsjs.com/installation/).
|
||||
See our [installation documentation](http://handlebarsjs.com/installation.html).
|
||||
|
||||
Usage
|
||||
-----
|
||||
In general, the syntax of Handlebars.js templates is a superset
|
||||
of Mustache templates. For basic syntax, check out the [Mustache
|
||||
manpage](https://mustache.github.io/mustache.5.html).
|
||||
manpage](http://mustache.github.com/mustache.5.html).
|
||||
|
||||
Once you have a template, use the `Handlebars.compile` method to compile
|
||||
the template into a function. The generated function takes a context
|
||||
@@ -47,25 +46,25 @@ var result = template(data);
|
||||
// </ul>
|
||||
```
|
||||
|
||||
Full documentation and more examples are at [handlebarsjs.com](https://handlebarsjs.com/).
|
||||
Full documentation and more examples are at [handlebarsjs.com](http://handlebarsjs.com/).
|
||||
|
||||
Precompiling Templates
|
||||
----------------------
|
||||
|
||||
Handlebars allows templates to be precompiled and included as javascript code rather than the handlebars template allowing for faster startup time. Full details are located [here](https://handlebarsjs.com/installation/precompilation.html).
|
||||
Handlebars allows templates to be precompiled and included as javascript code rather than the handlebars template allowing for faster startup time. Full details are located [here](http://handlebarsjs.com/precompilation.html).
|
||||
|
||||
Differences Between Handlebars.js and Mustache
|
||||
----------------------------------------------
|
||||
Handlebars.js adds a couple of additional features to make writing
|
||||
templates easier and also changes a tiny detail of how partials work.
|
||||
|
||||
- [Nested Paths](https://handlebarsjs.com/guide/expressions.html#path-expressions)
|
||||
- [Helpers](https://handlebarsjs.com/guide/expressions.html#helpers)
|
||||
- [Block Expressions](https://handlebarsjs.com/guide/block-helpers.html#basic-blocks)
|
||||
- [Literal Values](https://handlebarsjs.com/guide/expressions.html#literal-segments)
|
||||
- [Delimited Comments](https://handlebarsjs.com/guide/#template-comments)
|
||||
- [Nested Paths](http://handlebarsjs.com/#paths)
|
||||
- [Helpers](http://handlebarsjs.com/#helpers)
|
||||
- [Block Expressions](http://handlebarsjs.com/#block-expressions)
|
||||
- [Literal Values](http://handlebarsjs.com/#literals)
|
||||
- [Delimited Comments](http://handlebarsjs.com/#comments)
|
||||
|
||||
Block expressions have the same syntax as mustache sections but should not be confused with one another. Sections are akin to an implicit `each` or `with` statement depending on the input data and helpers are explicit pieces of code that are free to implement whatever behavior they like. The [mustache spec](https://mustache.github.io/mustache.5.html) defines the exact behavior of sections. In the case of name conflicts, helpers are given priority.
|
||||
Block expressions have the same syntax as mustache sections but should not be confused with one another. Sections are akin to an implicit `each` or `with` statement depending on the input data and helpers are explicit pieces of code that are free to implement whatever behavior they like. The [mustache spec](http://mustache.github.io/mustache.5.html) defines the exact behavior of sections. In the case of name conflicts, helpers are given priority.
|
||||
|
||||
### Compatibility
|
||||
|
||||
@@ -90,6 +89,8 @@ Handlebars has been designed to work in any ECMAScript 3 environment. This inclu
|
||||
Older versions and other runtimes are likely to work but have not been formally
|
||||
tested. The compiler requires `JSON.stringify` to be implemented natively or via a polyfill. If using the precompiler this is not necessary.
|
||||
|
||||
[](https://saucelabs.com/u/handlebars)
|
||||
|
||||
Performance
|
||||
-----------
|
||||
|
||||
@@ -101,18 +102,18 @@ does have some big performance advantages. Justin Marney, a.k.a.
|
||||
[gotascii](http://github.com/gotascii), confirmed that with an
|
||||
[independent test](http://sorescode.com/2010/09/12/benchmarks.html). The
|
||||
rewritten Handlebars (current version) is faster than the old version,
|
||||
with many performance tests being 5 to 7 times faster than the Mustache equivalent.
|
||||
with many [performance tests](https://travis-ci.org/wycats/handlebars.js/builds/33392182#L538) being 5 to 7 times faster than the Mustache equivalent.
|
||||
|
||||
|
||||
Upgrading
|
||||
---------
|
||||
|
||||
See [release-notes.md](https://github.com/handlebars-lang/handlebars.js/blob/master/release-notes.md) for upgrade notes.
|
||||
See [release-notes.md](https://github.com/wycats/handlebars.js/blob/master/release-notes.md) for upgrade notes.
|
||||
|
||||
Known Issues
|
||||
------------
|
||||
|
||||
See [FAQ.md](https://github.com/handlebars-lang/handlebars.js/blob/master/FAQ.md) for known issues and common pitfalls.
|
||||
See [FAQ.md](https://github.com/wycats/handlebars.js/blob/master/FAQ.md) for known issues and common pitfalls.
|
||||
|
||||
|
||||
Handlebars in the Wild
|
||||
@@ -164,4 +165,4 @@ License
|
||||
-------
|
||||
Handlebars.js is released under the MIT license.
|
||||
|
||||
[pull-request]: https://github.com/handlebars-lang/handlebars.js/pull/new/master
|
||||
[pull-request]: https://github.com/wycats/handlebars.js/pull/new/master
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# Test against these versions of Node.js
|
||||
environment:
|
||||
matrix:
|
||||
- nodejs_version: "10"
|
||||
|
||||
platform:
|
||||
- x64
|
||||
|
||||
# Install scripts (runs after repo cloning)
|
||||
install:
|
||||
# Get the latest stable version of Node.js
|
||||
- ps: Install-Product node $env:nodejs_version $env:platform
|
||||
# Clone submodules (mustache spec)
|
||||
- cmd: git submodule update --init --recursive
|
||||
# Install modules
|
||||
- cmd: npm install
|
||||
- cmd: npm install -g grunt-cli
|
||||
|
||||
|
||||
# Post-install test scripts
|
||||
test_script:
|
||||
# Output useful info for debugging
|
||||
- cmd: node --version
|
||||
- cmd: npm --version
|
||||
# Run tests
|
||||
- cmd: grunt --stack travis
|
||||
|
||||
# Don't actually build
|
||||
build: off
|
||||
|
||||
on_failure:
|
||||
- cmd: 7z a coverage.zip coverage
|
||||
- cmd: appveyor PushArtifact coverage.zip
|
||||
|
||||
|
||||
# Set build version format here instead of in the admin panel
|
||||
version: "{build}"
|
||||
@@ -0,0 +1,7 @@
|
||||
module.exports = function(api) {
|
||||
api.cache(false);
|
||||
return {
|
||||
presets: ['@babel/preset-env'],
|
||||
plugins: ['@babel/plugin-transform-runtime']
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"globals": {
|
||||
"require": true
|
||||
},
|
||||
"rules": {
|
||||
// Disabling for tests, for now.
|
||||
"no-path-concat": 0,
|
||||
|
||||
"no-var": 0,
|
||||
"no-shadow": 0,
|
||||
"handle-callback-err": 0,
|
||||
"no-console": 0
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
var async = require('neo-async'),
|
||||
fs = require('fs'),
|
||||
zlib = require('zlib');
|
||||
fs = require('fs'),
|
||||
zlib = require('zlib');
|
||||
|
||||
module.exports = function(grunt, callback) {
|
||||
var distFiles = fs.readdirSync('dist'),
|
||||
distSizes = {};
|
||||
distSizes = {};
|
||||
|
||||
async.each(
|
||||
distFiles,
|
||||
function(file, callback) {
|
||||
async.each(distFiles, function(file, callback) {
|
||||
var content;
|
||||
try {
|
||||
content = fs.readFileSync('dist/' + file);
|
||||
@@ -34,10 +32,7 @@ module.exports = function(grunt, callback) {
|
||||
});
|
||||
},
|
||||
function() {
|
||||
grunt.log.writeln(
|
||||
'Distribution sizes: ' + JSON.stringify(distSizes, undefined, 2)
|
||||
);
|
||||
grunt.log.writeln('Distribution sizes: ' + JSON.stringify(distSizes, undefined, 2));
|
||||
callback([distSizes]);
|
||||
}
|
||||
);
|
||||
});
|
||||
};
|
||||
@@ -2,7 +2,7 @@ var fs = require('fs');
|
||||
|
||||
var metrics = fs.readdirSync(__dirname);
|
||||
metrics.forEach(function(metric) {
|
||||
if (metric === 'index.js' || !/(.*)\.js$/.test(metric)) {
|
||||
if (metric === 'index.js' || !(/(.*)\.js$/.test(metric))) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,24 +1,19 @@
|
||||
var _ = require('underscore'),
|
||||
templates = require('./templates');
|
||||
templates = require('./templates');
|
||||
|
||||
module.exports = function(grunt, callback) {
|
||||
// Deferring to here in case we have a build for parser, etc as part of this grunt exec
|
||||
var Handlebars = require('../../lib');
|
||||
var Handlebars = require('../lib');
|
||||
|
||||
var templateSizes = {};
|
||||
_.each(templates, function(info, template) {
|
||||
var src = info.handlebars,
|
||||
compiled = Handlebars.precompile(src, {}),
|
||||
knownHelpers = Handlebars.precompile(src, {
|
||||
knownHelpersOnly: true,
|
||||
knownHelpers: info.helpers
|
||||
});
|
||||
compiled = Handlebars.precompile(src, {}),
|
||||
knownHelpers = Handlebars.precompile(src, {knownHelpersOnly: true, knownHelpers: info.helpers});
|
||||
|
||||
templateSizes[template] = compiled.length;
|
||||
templateSizes['knownOnly_' + template] = knownHelpers.length;
|
||||
});
|
||||
grunt.log.writeln(
|
||||
'Precompiled sizes: ' + JSON.stringify(templateSizes, undefined, 2)
|
||||
);
|
||||
grunt.log.writeln('Precompiled sizes: ' + JSON.stringify(templateSizes, undefined, 2));
|
||||
callback([templateSizes]);
|
||||
};
|
||||
@@ -8,6 +8,5 @@ module.exports = {
|
||||
bar: true
|
||||
},
|
||||
|
||||
handlebars:
|
||||
'{{foo person "person" 1 true foo=bar foo="person" foo=1 foo=true}}'
|
||||
handlebars: '{{foo person "person" 1 true foo=bar foo="person" foo=1 foo=true}}'
|
||||
};
|
||||
@@ -1,12 +1,5 @@
|
||||
module.exports = {
|
||||
context: {
|
||||
names: [
|
||||
{ name: 'Moe' },
|
||||
{ name: 'Larry' },
|
||||
{ name: 'Curly' },
|
||||
{ name: 'Shemp' }
|
||||
]
|
||||
},
|
||||
context: { names: [{name: 'Moe'}, {name: 'Larry'}, {name: 'Curly'}, {name: 'Shemp'}] },
|
||||
handlebars: '{{#each names}}{{name}}{{/each}}',
|
||||
dust: '{#names}{name}{/names}',
|
||||
mustache: '{{#names}}{{name}}{{/names}}',
|
||||
@@ -0,0 +1,4 @@
|
||||
module.exports = {
|
||||
context: { names: [{name: 'Moe'}, {name: 'Larry'}, {name: 'Curly'}, {name: 'Shemp'}] },
|
||||
handlebars: '{{#names}}{{name}}{{/names}}'
|
||||
};
|
||||
@@ -7,9 +7,9 @@ module.exports = {
|
||||
},
|
||||
hasItems: true, // To make things fairer in mustache land due to no `{{if}}` construct on arrays
|
||||
items: [
|
||||
{ name: 'red', current: true, url: '#Red' },
|
||||
{ name: 'green', current: false, url: '#Green' },
|
||||
{ name: 'blue', current: false, url: '#Blue' }
|
||||
{name: 'red', current: true, url: '#Red'},
|
||||
{name: 'green', current: false, url: '#Green'},
|
||||
{name: 'blue', current: false, url: '#Blue'}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
module.exports = {
|
||||
context: { names: [{name: 'Moe'}, {name: 'Larry'}, {name: 'Curly'}, {name: 'Shemp'}] },
|
||||
handlebars: '{{#each names}}{{@index}}{{name}}{{/each}}'
|
||||
};
|
||||
@@ -1,13 +1,5 @@
|
||||
module.exports = {
|
||||
context: {
|
||||
names: [
|
||||
{ name: 'Moe' },
|
||||
{ name: 'Larry' },
|
||||
{ name: 'Curly' },
|
||||
{ name: 'Shemp' }
|
||||
],
|
||||
foo: 'bar'
|
||||
},
|
||||
context: { names: [{name: 'Moe'}, {name: 'Larry'}, {name: 'Curly'}, {name: 'Shemp'}], foo: 'bar' },
|
||||
handlebars: '{{#each names}}{{../foo}}{{/each}}',
|
||||
mustache: '{{#names}}{{foo}}{{/names}}',
|
||||
eco: '<% for item in @names: %><%= @foo %><% end %>'
|
||||
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
context: { names: [{bat: 'foo', name: ['Moe']}, {bat: 'foo', name: ['Larry']}, {bat: 'foo', name: ['Curly']}, {bat: 'foo', name: ['Shemp']}], foo: 'bar' },
|
||||
handlebars: '{{#each names}}{{#each name}}{{../bat}}{{../../foo}}{{/each}}{{/each}}',
|
||||
mustache: '{{#names}}{{#name}}{{bat}}{{foo}}{{/name}}{{/names}}',
|
||||
eco: '<% for item in @names: %><% for child in item.name: %><%= item.bat %><%= @foo %><% end %><% end %>'
|
||||
};
|
||||
@@ -2,7 +2,7 @@ var fs = require('fs');
|
||||
|
||||
var templates = fs.readdirSync(__dirname);
|
||||
templates.forEach(function(template) {
|
||||
if (template === 'index.js' || !/(.*)\.js$/.test(template)) {
|
||||
if (template === 'index.js' || !(/(.*)\.js$/.test(template))) {
|
||||
return;
|
||||
}
|
||||
module.exports[RegExp.$1] = require('./' + RegExp.$1);
|
||||
@@ -1,8 +1,5 @@
|
||||
module.exports = {
|
||||
context: {
|
||||
name: '1',
|
||||
kids: [{ name: '1.1', kids: [{ name: '1.1.1', kids: [] }] }]
|
||||
},
|
||||
context: { name: '1', kids: [{ name: '1.1', kids: [{name: '1.1.1', kids: []}] }] },
|
||||
partials: {
|
||||
mustache: { recursion: '{{name}}{{#kids}}{{>recursion}}{{/kids}}' },
|
||||
handlebars: { recursion: '{{name}}{{#each kids}}{{>recursion}}{{/each}}' }
|
||||
@@ -1,16 +1,8 @@
|
||||
module.exports = {
|
||||
context: {
|
||||
peeps: [
|
||||
{ name: 'Moe', count: 15 },
|
||||
{ name: 'Larry', count: 5 },
|
||||
{ name: 'Curly', count: 1 }
|
||||
]
|
||||
},
|
||||
context: { peeps: [{name: 'Moe', count: 15}, {name: 'Larry', count: 5}, {name: 'Curly', count: 1}] },
|
||||
partials: {
|
||||
mustache: { variables: 'Hello {{name}}! You have {{count}} new messages.' },
|
||||
handlebars: {
|
||||
variables: 'Hello {{name}}! You have {{count}} new messages.'
|
||||
}
|
||||
handlebars: { variables: 'Hello {{name}}! You have {{count}} new messages.' }
|
||||
},
|
||||
|
||||
handlebars: '{{#each peeps}}{{>variables}}{{/each}}',
|
||||
@@ -0,0 +1,7 @@
|
||||
module.exports = {
|
||||
context: { person: { name: {bar: {baz: 'Larry'}}, age: 45 } },
|
||||
handlebars: '{{person.name.bar.baz}}{{person.age}}{{person.foo}}{{animal.age}}',
|
||||
dust: '{person.name.bar.baz}{person.age}{person.foo}{animal.age}',
|
||||
eco: '<%= @person.name.bar.baz %><%= @person.age %><%= @person.foo %><% if @animal: %><%= @animal.age %><% end %>',
|
||||
mustache: '{{person.name.bar.baz}}{{person.age}}{{person.foo}}{{animal.age}}'
|
||||
};
|
||||
@@ -1,7 +1,8 @@
|
||||
module.exports = {
|
||||
context: { name: 'Mick', count: 30 },
|
||||
context: {name: 'Mick', count: 30},
|
||||
handlebars: 'Hello {{name}}! You have {{count}} new messages.',
|
||||
dust: 'Hello {name}! You have {count} new messages.',
|
||||
mustache: 'Hello {{name}}! You have {{count}} new messages.',
|
||||
eco: 'Hello <%= @name %>! You have <%= @count %> new messages.'
|
||||
};
|
||||
|
||||
@@ -1,27 +1,19 @@
|
||||
var _ = require('underscore'),
|
||||
runner = require('./util/template-runner'),
|
||||
eco,
|
||||
dust,
|
||||
Handlebars,
|
||||
Mustache;
|
||||
runner = require('./util/template-runner'),
|
||||
|
||||
eco, dust, Handlebars, Mustache;
|
||||
|
||||
try {
|
||||
dust = require('dustjs-linkedin');
|
||||
} catch (err) {
|
||||
/* NOP */
|
||||
}
|
||||
} catch (err) { /* NOP */ }
|
||||
|
||||
try {
|
||||
Mustache = require('mustache');
|
||||
} catch (err) {
|
||||
/* NOP */
|
||||
}
|
||||
} catch (err) { /* NOP */ }
|
||||
|
||||
try {
|
||||
eco = require('eco');
|
||||
} catch (err) {
|
||||
/* NOP */
|
||||
}
|
||||
} catch (err) { /* NOP */ }
|
||||
|
||||
function error() {
|
||||
throw new Error('EWOT');
|
||||
@@ -30,28 +22,21 @@ function error() {
|
||||
function makeSuite(bench, name, template, handlebarsOnly) {
|
||||
// Create aliases to minimize any impact from having to walk up the closure tree.
|
||||
var templateName = name,
|
||||
context = template.context,
|
||||
partials = template.partials,
|
||||
handlebarsOut,
|
||||
compatOut,
|
||||
dustOut,
|
||||
ecoOut,
|
||||
mustacheOut;
|
||||
|
||||
var handlebar = Handlebars.compile(template.handlebars, { data: false }),
|
||||
compat = Handlebars.compile(template.handlebars, {
|
||||
data: false,
|
||||
compat: true
|
||||
}),
|
||||
options = { helpers: template.helpers };
|
||||
_.each(template.partials && template.partials.handlebars, function(
|
||||
partial,
|
||||
partialName
|
||||
) {
|
||||
Handlebars.registerPartial(
|
||||
partialName,
|
||||
Handlebars.compile(partial, { data: false })
|
||||
);
|
||||
context = template.context,
|
||||
partials = template.partials,
|
||||
|
||||
handlebarsOut,
|
||||
compatOut,
|
||||
dustOut,
|
||||
ecoOut,
|
||||
mustacheOut;
|
||||
|
||||
var handlebar = Handlebars.compile(template.handlebars, {data: false}),
|
||||
compat = Handlebars.compile(template.handlebars, {data: false, compat: true}),
|
||||
options = {helpers: template.helpers};
|
||||
_.each(template.partials && template.partials.handlebars, function(partial, partialName) {
|
||||
Handlebars.registerPartial(partialName, Handlebars.compile(partial, {data: false}));
|
||||
});
|
||||
|
||||
handlebarsOut = handlebar(context, options);
|
||||
@@ -73,9 +58,7 @@ function makeSuite(bench, name, template, handlebarsOnly) {
|
||||
dustOut = false;
|
||||
dust.loadSource(dust.compile(template.dust, templateName));
|
||||
|
||||
dust.render(templateName, context, function(err, out) {
|
||||
dustOut = out;
|
||||
});
|
||||
dust.render(templateName, context, function(err, out) { dustOut = out; });
|
||||
|
||||
bench('dust', function() {
|
||||
dust.render(templateName, context, function() {});
|
||||
@@ -101,7 +84,7 @@ function makeSuite(bench, name, template, handlebarsOnly) {
|
||||
|
||||
if (Mustache) {
|
||||
var mustacheSource = template.mustache,
|
||||
mustachePartials = partials && partials.mustache;
|
||||
mustachePartials = partials && partials.mustache;
|
||||
|
||||
if (mustacheSource) {
|
||||
mustacheOut = Mustache.to_html(mustacheSource, context, mustachePartials);
|
||||
@@ -124,16 +107,9 @@ function makeSuite(bench, name, template, handlebarsOnly) {
|
||||
b = b.replace(/\s/g, '');
|
||||
|
||||
if (handlebarsOut !== b) {
|
||||
throw new Error(
|
||||
'Template output mismatch: ' +
|
||||
name +
|
||||
'\n\nHandlebars: ' +
|
||||
handlebarsOut +
|
||||
'\n\n' +
|
||||
lang +
|
||||
': ' +
|
||||
b
|
||||
);
|
||||
throw new Error('Template output mismatch: ' + name
|
||||
+ '\n\nHandlebars: ' + handlebarsOut
|
||||
+ '\n\n' + lang + ': ' + b);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +121,7 @@ function makeSuite(bench, name, template, handlebarsOnly) {
|
||||
|
||||
module.exports = function(grunt, callback) {
|
||||
// Deferring load incase we are being run inline with the grunt build
|
||||
Handlebars = require('../../lib');
|
||||
Handlebars = require('../lib');
|
||||
|
||||
console.log('Execution Throughput');
|
||||
runner(grunt, makeSuite, function(times, scaled) {
|
||||
@@ -1,5 +1,5 @@
|
||||
var _ = require('underscore'),
|
||||
Benchmark = require('benchmark');
|
||||
Benchmark = require('benchmark');
|
||||
|
||||
function BenchWarmer() {
|
||||
this.benchmarks = [];
|
||||
@@ -11,6 +11,8 @@ function BenchWarmer() {
|
||||
this.errors = {};
|
||||
}
|
||||
|
||||
var print = require('util').print;
|
||||
|
||||
BenchWarmer.prototype = {
|
||||
winners: function(benches) {
|
||||
return Benchmark.filter(benches, 'fastest');
|
||||
@@ -31,21 +33,16 @@ BenchWarmer.prototype = {
|
||||
this.names.push(name);
|
||||
}
|
||||
|
||||
var first = this.first,
|
||||
suiteName = this.suiteName,
|
||||
self = this;
|
||||
var first = this.first, suiteName = this.suiteName, self = this;
|
||||
this.first = false;
|
||||
|
||||
var bench = new Benchmark(fn, {
|
||||
name: this.suiteName + ': ' + name,
|
||||
onComplete: function() {
|
||||
if (first) {
|
||||
self.startLine(suiteName);
|
||||
}
|
||||
if (first) { self.startLine(suiteName); }
|
||||
self.writeBench(bench);
|
||||
self.currentBenches.push(bench);
|
||||
},
|
||||
onError: function() {
|
||||
}, onError: function() {
|
||||
self.errors[this.name] = this;
|
||||
}
|
||||
});
|
||||
@@ -67,7 +64,7 @@ BenchWarmer.prototype = {
|
||||
|
||||
self.startLine('');
|
||||
|
||||
console.log('\n');
|
||||
print('\n');
|
||||
self.printHeader('scaled');
|
||||
_.each(self.scaled, function(value, name) {
|
||||
self.startLine(name);
|
||||
@@ -76,32 +73,28 @@ BenchWarmer.prototype = {
|
||||
self.writeValue(value[lang] || '');
|
||||
});
|
||||
});
|
||||
console.log('\n');
|
||||
print('\n');
|
||||
|
||||
var errors = false,
|
||||
prop,
|
||||
bench;
|
||||
var errors = false, prop, bench;
|
||||
for (prop in self.errors) {
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(self, prop) &&
|
||||
self.errors[prop].error.message !== 'EWOT'
|
||||
) {
|
||||
if (Object.prototype.hasOwnProperty.call(self, prop)
|
||||
&& self.errors[prop].error.message !== 'EWOT') {
|
||||
errors = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (errors) {
|
||||
console.log('\n\nErrors:\n');
|
||||
print('\n\nErrors:\n');
|
||||
Object.keys(self.errors).forEach(function(prop) {
|
||||
if (self.errors[prop].error.message !== 'EWOT') {
|
||||
bench = self.errors[prop];
|
||||
console.log('\n' + bench.name + ':\n');
|
||||
console.log(bench.error.message);
|
||||
print('\n' + bench.name + ':\n');
|
||||
print(bench.error.message);
|
||||
if (bench.error.stack) {
|
||||
console.log(bench.error.stack.join('\n'));
|
||||
print(bench.error.stack.join('\n'));
|
||||
}
|
||||
console.log('\n');
|
||||
print('\n');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -110,43 +103,27 @@ BenchWarmer.prototype = {
|
||||
}
|
||||
});
|
||||
|
||||
console.log('\n');
|
||||
print('\n');
|
||||
},
|
||||
|
||||
scaleTimes: function() {
|
||||
var scaled = (this.scaled = {});
|
||||
_.each(
|
||||
this.times,
|
||||
function(times, name) {
|
||||
var output = (scaled[name] = {});
|
||||
var scaled = this.scaled = {};
|
||||
_.each(this.times, function(times, name) {
|
||||
var output = scaled[name] = {};
|
||||
|
||||
_.each(
|
||||
times,
|
||||
function(time, lang) {
|
||||
output[lang] = (
|
||||
((time - this.minimum) / (this.maximum - this.minimum)) *
|
||||
100
|
||||
).toFixed(2);
|
||||
},
|
||||
this
|
||||
);
|
||||
},
|
||||
this
|
||||
);
|
||||
_.each(times, function(time, lang) {
|
||||
output[lang] = ((time - this.minimum) / (this.maximum - this.minimum) * 100).toFixed(2);
|
||||
}, this);
|
||||
}, this);
|
||||
},
|
||||
|
||||
printHeader: function(title, winners) {
|
||||
var benchSize = 0,
|
||||
names = this.names,
|
||||
i,
|
||||
l;
|
||||
var benchSize = 0, names = this.names, i, l;
|
||||
|
||||
for (i = 0, l = names.length; i < l; i++) {
|
||||
var name = names[i];
|
||||
|
||||
if (benchSize < name.length) {
|
||||
benchSize = name.length;
|
||||
}
|
||||
if (benchSize < name.length) { benchSize = name.length; }
|
||||
}
|
||||
|
||||
this.nameSize = benchSize + 2;
|
||||
@@ -161,24 +138,22 @@ BenchWarmer.prototype = {
|
||||
}
|
||||
|
||||
if (winners) {
|
||||
console.log('WINNER(S)');
|
||||
print('WINNER(S)');
|
||||
horSize = horSize + 'WINNER(S)'.length;
|
||||
}
|
||||
|
||||
console.log('\n' + new Array(horSize + 1).join('-'));
|
||||
print('\n' + new Array(horSize + 1).join('-'));
|
||||
},
|
||||
|
||||
startLine: function(name) {
|
||||
var winners = Benchmark.map(this.winners(this.currentBenches), function(
|
||||
bench
|
||||
) {
|
||||
var winners = Benchmark.map(this.winners(this.currentBenches), function(bench) {
|
||||
return bench.name.split(': ')[1];
|
||||
});
|
||||
|
||||
this.currentBenches = [];
|
||||
|
||||
console.log(winners.join(', '));
|
||||
console.log('\n');
|
||||
print(winners.join(', '));
|
||||
print('\n');
|
||||
|
||||
if (name) {
|
||||
this.writeValue(name);
|
||||
@@ -189,9 +164,9 @@ BenchWarmer.prototype = {
|
||||
|
||||
if (!bench.error) {
|
||||
var count = bench.hz,
|
||||
moe = (count * bench.stats.rme) / 100,
|
||||
minimum,
|
||||
maximum;
|
||||
moe = count * bench.stats.rme / 100,
|
||||
minimum,
|
||||
maximum;
|
||||
|
||||
count = Math.round(count / 1000);
|
||||
moe = Math.round(moe / 1000);
|
||||
@@ -214,7 +189,7 @@ BenchWarmer.prototype = {
|
||||
writeValue: function(out) {
|
||||
var padding = this.benchSize - out.length + 1;
|
||||
out = out + new Array(padding).join(' ');
|
||||
console.log(out);
|
||||
print(out);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
var _ = require('underscore'),
|
||||
BenchWarmer = require('./benchwarmer'),
|
||||
templates = require('../templates');
|
||||
BenchWarmer = require('./benchwarmer'),
|
||||
templates = require('../templates');
|
||||
|
||||
module.exports = function(grunt, makeSuite, callback) {
|
||||
var warmer = new BenchWarmer();
|
||||
|
||||
var handlebarsOnly = grunt.option('handlebars-only'),
|
||||
grep = grunt.option('grep');
|
||||
grep = grunt.option('grep');
|
||||
if (grep) {
|
||||
grep = new RegExp(grep);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
module.exports = {
|
||||
rules: {
|
||||
'no-console': 0,
|
||||
'no-var': 0
|
||||
}
|
||||
};
|
||||
+111
-159
@@ -1,176 +1,128 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
var argv = parseArgs({
|
||||
'f': {
|
||||
'type': 'string',
|
||||
'description': 'Output File',
|
||||
'alias': 'output'
|
||||
},
|
||||
'map': {
|
||||
'type': 'string',
|
||||
'description': 'Source Map File'
|
||||
},
|
||||
'a': {
|
||||
'type': 'boolean',
|
||||
'description': 'Exports amd style (require.js)',
|
||||
'alias': 'amd'
|
||||
},
|
||||
'c': {
|
||||
'type': 'string',
|
||||
'description': 'Exports CommonJS style, path to Handlebars module',
|
||||
'alias': 'commonjs',
|
||||
'default': null
|
||||
},
|
||||
'h': {
|
||||
'type': 'string',
|
||||
'description': 'Path to handlebar.js (only valid for amd-style)',
|
||||
'alias': 'handlebarPath',
|
||||
'default': ''
|
||||
},
|
||||
'k': {
|
||||
'type': 'string',
|
||||
'description': 'Known helpers',
|
||||
'alias': 'known'
|
||||
},
|
||||
'o': {
|
||||
'type': 'boolean',
|
||||
'description': 'Known helpers only',
|
||||
'alias': 'knownOnly'
|
||||
},
|
||||
'm': {
|
||||
'type': 'boolean',
|
||||
'description': 'Minimize output',
|
||||
'alias': 'min'
|
||||
},
|
||||
'n': {
|
||||
'type': 'string',
|
||||
'description': 'Template namespace',
|
||||
'alias': 'namespace',
|
||||
'default': 'Handlebars.templates'
|
||||
},
|
||||
's': {
|
||||
'type': 'boolean',
|
||||
'description': 'Output template function only.',
|
||||
'alias': 'simple'
|
||||
},
|
||||
'N': {
|
||||
'type': 'string',
|
||||
'description': 'Name of passed string templates. Optional if running in a simple mode. Required when operating on multiple templates.',
|
||||
'alias': 'name'
|
||||
},
|
||||
'i': {
|
||||
'type': 'string',
|
||||
'description': 'Generates a template from the passed CLI argument.\n"-" is treated as a special value and causes stdin to be read for the template value.',
|
||||
'alias': 'string'
|
||||
},
|
||||
'r': {
|
||||
'type': 'string',
|
||||
'description': 'Template root. Base value that will be stripped from template names.',
|
||||
'alias': 'root'
|
||||
},
|
||||
'p': {
|
||||
'type': 'boolean',
|
||||
'description': 'Compiling a partial template',
|
||||
'alias': 'partial'
|
||||
},
|
||||
'd': {
|
||||
'type': 'boolean',
|
||||
'description': 'Include data when compiling',
|
||||
'alias': 'data'
|
||||
},
|
||||
'e': {
|
||||
'type': 'string',
|
||||
'description': 'Template extension.',
|
||||
'alias': 'extension',
|
||||
'default': 'handlebars'
|
||||
},
|
||||
'b': {
|
||||
'type': 'boolean',
|
||||
'description': 'Removes the BOM (Byte Order Mark) from the beginning of the templates.',
|
||||
'alias': 'bom'
|
||||
},
|
||||
'v': {
|
||||
'type': 'boolean',
|
||||
'description': 'Prints the current compiler version',
|
||||
'alias': 'version'
|
||||
},
|
||||
'help': {
|
||||
'type': 'boolean',
|
||||
'description': 'Outputs this message'
|
||||
}
|
||||
});
|
||||
var optimist = require('optimist')
|
||||
.usage('Precompile handlebar templates.\nUsage: $0 [template|directory]...', {
|
||||
'f': {
|
||||
'type': 'string',
|
||||
'description': 'Output File',
|
||||
'alias': 'output'
|
||||
},
|
||||
'map': {
|
||||
'type': 'string',
|
||||
'description': 'Source Map File'
|
||||
},
|
||||
'a': {
|
||||
'type': 'boolean',
|
||||
'description': 'Exports amd style (require.js)',
|
||||
'alias': 'amd'
|
||||
},
|
||||
'c': {
|
||||
'type': 'string',
|
||||
'description': 'Exports CommonJS style, path to Handlebars module',
|
||||
'alias': 'commonjs',
|
||||
'default': null
|
||||
},
|
||||
'h': {
|
||||
'type': 'string',
|
||||
'description': 'Path to handlebar.js (only valid for amd-style)',
|
||||
'alias': 'handlebarPath',
|
||||
'default': ''
|
||||
},
|
||||
'k': {
|
||||
'type': 'string',
|
||||
'description': 'Known helpers',
|
||||
'alias': 'known'
|
||||
},
|
||||
'o': {
|
||||
'type': 'boolean',
|
||||
'description': 'Known helpers only',
|
||||
'alias': 'knownOnly'
|
||||
},
|
||||
'm': {
|
||||
'type': 'boolean',
|
||||
'description': 'Minimize output',
|
||||
'alias': 'min'
|
||||
},
|
||||
'n': {
|
||||
'type': 'string',
|
||||
'description': 'Template namespace',
|
||||
'alias': 'namespace',
|
||||
'default': 'Handlebars.templates'
|
||||
},
|
||||
's': {
|
||||
'type': 'boolean',
|
||||
'description': 'Output template function only.',
|
||||
'alias': 'simple'
|
||||
},
|
||||
'N': {
|
||||
'type': 'string',
|
||||
'description': 'Name of passed string templates. Optional if running in a simple mode. Required when operating on multiple templates.',
|
||||
'alias': 'name'
|
||||
},
|
||||
'i': {
|
||||
'type': 'string',
|
||||
'description': 'Generates a template from the passed CLI argument.\n"-" is treated as a special value and causes stdin to be read for the template value.',
|
||||
'alias': 'string'
|
||||
},
|
||||
'r': {
|
||||
'type': 'string',
|
||||
'description': 'Template root. Base value that will be stripped from template names.',
|
||||
'alias': 'root'
|
||||
},
|
||||
'p': {
|
||||
'type': 'boolean',
|
||||
'description': 'Compiling a partial template',
|
||||
'alias': 'partial'
|
||||
},
|
||||
'd': {
|
||||
'type': 'boolean',
|
||||
'description': 'Include data when compiling',
|
||||
'alias': 'data'
|
||||
},
|
||||
'e': {
|
||||
'type': 'string',
|
||||
'description': 'Template extension.',
|
||||
'alias': 'extension',
|
||||
'default': 'handlebars'
|
||||
},
|
||||
'b': {
|
||||
'type': 'boolean',
|
||||
'description': 'Removes the BOM (Byte Order Mark) from the beginning of the templates.',
|
||||
'alias': 'bom'
|
||||
},
|
||||
'v': {
|
||||
'type': 'boolean',
|
||||
'description': 'Prints the current compiler version',
|
||||
'alias': 'version'
|
||||
},
|
||||
|
||||
'help': {
|
||||
'type': 'boolean',
|
||||
'description': 'Outputs this message'
|
||||
}
|
||||
})
|
||||
|
||||
.wrap(120)
|
||||
.check(function(argv) {
|
||||
if (argv.version) {
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
var argv = optimist.argv;
|
||||
argv.files = argv._;
|
||||
delete argv._;
|
||||
|
||||
var Precompiler = require('../dist/cjs/precompiler');
|
||||
Precompiler.loadTemplates(argv, function(err, opts) {
|
||||
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (opts.help || (!opts.templates.length && !opts.version)) {
|
||||
printUsage(argv._spec, 120);
|
||||
optimist.showHelp();
|
||||
} else {
|
||||
Precompiler.cli(opts);
|
||||
}
|
||||
});
|
||||
|
||||
function pad(n) {
|
||||
var str = '';
|
||||
while (str.length < n) {
|
||||
str += ' ';
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
function parseArgs(spec) {
|
||||
var opts = { alias: {}, boolean: [], default: {}, string: [] };
|
||||
|
||||
Object.keys(spec).forEach(function (arg) {
|
||||
var opt = spec[arg];
|
||||
opts[opt.type].push(arg);
|
||||
if ('alias' in opt) opts.alias[arg] = opt.alias;
|
||||
if ('default' in opt) opts.default[arg] = opt.default;
|
||||
});
|
||||
|
||||
var argv = require('minimist')(process.argv.slice(2), opts);
|
||||
argv._spec = spec;
|
||||
return argv;
|
||||
}
|
||||
|
||||
function printUsage(spec, wrap) {
|
||||
var wordwrap = require('wordwrap');
|
||||
|
||||
console.log('Precompile handlebar templates.');
|
||||
console.log('Usage: handlebars [template|directory]...');
|
||||
|
||||
var opts = [];
|
||||
var width = 0;
|
||||
Object.keys(spec).forEach(function (arg) {
|
||||
var opt = spec[arg];
|
||||
|
||||
var name = (arg.length === 1 ? '-' : '--') + arg;
|
||||
if ('alias' in opt) name += ', --' + opt.alias;
|
||||
|
||||
var meta = '[' + opt.type + ']';
|
||||
if ('default' in opt) meta += ' [default: ' + JSON.stringify(opt.default) + ']';
|
||||
|
||||
opts.push({ name: name, desc: opt.description, meta: meta });
|
||||
if (name.length > width) width = name.length;
|
||||
});
|
||||
|
||||
console.log('Options:');
|
||||
opts.forEach(function (opt) {
|
||||
var desc = wordwrap(width + 4, wrap + 1)(opt.desc);
|
||||
|
||||
console.log(' %s%s%s%s%s',
|
||||
opt.name,
|
||||
pad(width - opt.name.length + 2),
|
||||
desc.slice(width + 4),
|
||||
pad(wrap - opt.meta.length - desc.split(/\n/).pop().length),
|
||||
opt.meta
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "handlebars",
|
||||
"version": "4.7.9",
|
||||
"version": "4.5.3",
|
||||
"main": "handlebars.js",
|
||||
"license": "MIT",
|
||||
"dependencies": {}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "components/handlebars.js",
|
||||
"description": "Handlebars.js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be.",
|
||||
"homepage": "https://handlebarsjs.com",
|
||||
"homepage": "http://handlebarsjs.com",
|
||||
"license": "MIT",
|
||||
"type": "component",
|
||||
"keywords": [
|
||||
@@ -11,9 +11,13 @@
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Chris Wanstrath"
|
||||
"name": "Chris Wanstrath",
|
||||
"homepage": "http://chriswanstrath.com"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"robloach/component-installer": "*"
|
||||
},
|
||||
"extra": {
|
||||
"component": {
|
||||
"name": "handlebars",
|
||||
|
||||
@@ -10,7 +10,7 @@ Gem::Specification.new do |gem|
|
||||
gem.date = Time.now.strftime("%Y-%m-%d")
|
||||
gem.description = %q{Handlebars.js source code wrapper for (pre)compilation gems.}
|
||||
gem.summary = %q{Handlebars.js source code wrapper}
|
||||
gem.homepage = "https://github.com/handlebars-lang/handlebars.js/"
|
||||
gem.homepage = "https://github.com/wycats/handlebars.js/"
|
||||
gem.version = package["version"].sub "-", "."
|
||||
gem.license = "MIT"
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
<package>
|
||||
<metadata>
|
||||
<id>handlebars.js</id>
|
||||
<version>4.7.9</version>
|
||||
<version>4.5.3</version>
|
||||
<authors>handlebars.js Authors</authors>
|
||||
<licenseUrl>https://github.com/handlebars-lang/handlebars.js/blob/master/LICENSE</licenseUrl>
|
||||
<projectUrl>https://github.com/handlebars-lang/handlebars.js/</projectUrl>
|
||||
<licenseUrl>https://github.com/wycats/handlebars.js/blob/master/LICENSE</licenseUrl>
|
||||
<projectUrl>https://github.com/wycats/handlebars.js/</projectUrl>
|
||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||
<description>Extension of the Mustache logicless template language</description>
|
||||
<releaseNotes></releaseNotes>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "handlebars",
|
||||
"version": "4.7.9",
|
||||
"version": "4.5.3",
|
||||
"license": "MIT",
|
||||
"jspm": {
|
||||
"main": "handlebars",
|
||||
|
||||
@@ -16,4 +16,4 @@ Decorators are executed when the block program is instantiated and are passed `(
|
||||
|
||||
Decorators may set values on `props` or return a modified function that wraps `program` in particular behaviors. If the decorator returns nothing, then `program` is left unaltered.
|
||||
|
||||
The [inline partial](https://github.com/handlebars-lang/handlebars.js/blob/master/lib/handlebars/decorators/inline.js) implementation provides an example of decorators being used for both metadata and wrapping behaviors.
|
||||
The [inline partial](https://github.com/wycats/handlebars.js/blob/master/lib/handlebars/decorators/inline.js) implementation provides an example of decorators being used for both metadata and wrapping behaviors.
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
Add a new integration test by creating a new subfolder
|
||||
|
||||
Add a file "test.sh" to that runs the test. "test.sh" should exit with a non-zero exit code
|
||||
Add a file "test.sh" to that runs the test. "test.sh" should exit with a non-zero exit code
|
||||
and display an error message, if something goes wrong.
|
||||
|
||||
- An integration test should reflect real-world setups that use handlebars.
|
||||
- It should compile a minimal template and compare the output to an expected output.
|
||||
- It should use "../.." as dependency for Handlebars so that the currently built library is used.
|
||||
* An integration test should reflect real-world setups that use handlebars.
|
||||
* It should compile a minimal template and compare the output to an expected output.
|
||||
* It should use "../.." as dependency for Handlebars so that the currently built library is used.
|
||||
|
||||
Currently, integration tests are only running on Linux, especially in our CI GitHub action.
|
||||
Currently, integration tests are only running on Linux, especially in travis-ci.
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
module.exports = {
|
||||
"extends": "eslint:recommended",
|
||||
"globals": {
|
||||
"self": false
|
||||
},
|
||||
"env": {
|
||||
"node": true
|
||||
},
|
||||
"rules": {
|
||||
'no-console': 'off'
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"handlebars": "file:../../.."
|
||||
"handlebars": "file:../.."
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node run-handlebars.js",
|
||||
+1
-1
@@ -5,7 +5,7 @@ var Handlebars = require('handlebars');
|
||||
console.log('Testing built Handlebars with Node version ' + process.version);
|
||||
|
||||
var template = Handlebars.compile('Author: {{author}}');
|
||||
var output = template({ author: 'Yehuda' });
|
||||
var output = template({author: 'Yehuda'});
|
||||
assert.strictEqual(output, 'Author: Yehuda');
|
||||
|
||||
console.log('Success');
|
||||
+11
-13
@@ -1,28 +1,26 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
cd "$( dirname "$( readlink -f "$0" )" )" || exit 1
|
||||
# shellcheck disable=SC1090
|
||||
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
|
||||
|
||||
# This script tests with precompiler and the built distribution with multiple NodeJS version.
|
||||
# The rest of the travis-build will only work with newer NodeJS versions, because the build
|
||||
# tools don't support older versions.
|
||||
# However, the built distribution should work with older NodeJS versions as well.
|
||||
# This test is simple by design. It merely ensures, that calling Handlebars does not fail with old versions.
|
||||
# It does (almost) not test for correctness, because that is already done in the mocha-tests.
|
||||
# And it does not use any NodeJS based testing framework to make this part independent of the Node version.
|
||||
|
||||
unset npm_config_prefix
|
||||
# And it does not use any NodeJS based testing framwork to make this part independent of the Node version.
|
||||
|
||||
# A list of NodeJS versions is expected as cli-args
|
||||
echo "Handlebars should be able to run in various versions of NodeJS"
|
||||
for node_version_to_test in 0.10 0.12 4 5 6 7 8 9 10 11 12 13 14 15 16 18; do
|
||||
|
||||
for i in 0.10 0.12 4 5 6 7 8 9 10 11 ; do
|
||||
rm target node_modules package-lock.json -rf
|
||||
mkdir target
|
||||
|
||||
nvm install "$node_version_to_test"
|
||||
nvm exec "$node_version_to_test" npm install
|
||||
nvm exec "$node_version_to_test" npm run test
|
||||
nvm exec "$node_version_to_test" npm run test-precompile
|
||||
nvm install "$i"
|
||||
nvm exec "$i" npm install
|
||||
nvm exec "$i" npm run test || exit 1
|
||||
nvm exec "$i" npm run test-precompile || exit 1
|
||||
|
||||
echo Success
|
||||
done
|
||||
done
|
||||
+4
-6
@@ -1,15 +1,13 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
cd "$( dirname "$( readlink -f "$0" )" )"
|
||||
cd "$( dirname "$( readlink -f "$0" )" )" || exit 1
|
||||
|
||||
for i in */test.sh ; do
|
||||
(
|
||||
echo "----------------------------------------"
|
||||
echo "-- Running integration test: $i"
|
||||
echo "----------------------------------------"
|
||||
cd "$( dirname "$i" )"
|
||||
./test.sh
|
||||
cd "$( dirname "$i" )" || exit 1
|
||||
./test.sh || exit 1
|
||||
)
|
||||
done
|
||||
done
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
"@roundingwellos/babel-plugin-handlebars-inline-precompile": "^3.0.1",
|
||||
"babel-loader": "^8.0.6",
|
||||
"babel-plugin-istanbul": "^5.2.0",
|
||||
"handlebars": "file:../../..",
|
||||
"handlebars": "file:../..",
|
||||
"handlebars-loader": "^1.7.1",
|
||||
"nyc": "^14.1.1",
|
||||
"webpack": "^4.39.3",
|
||||
+3
-3
@@ -1,12 +1,12 @@
|
||||
import * as Handlebars from 'handlebars/runtime';
|
||||
import hbs from 'handlebars-inline-precompile';
|
||||
import { assertEquals } from '../../webpack-test/src/lib/assert';
|
||||
import {assertEquals} from '../../webpack-test/src/lib/assert';
|
||||
|
||||
Handlebars.registerHelper('loud', function(text) {
|
||||
return text.toUpperCase();
|
||||
return text.toUpperCase();
|
||||
});
|
||||
|
||||
const template = hbs`{{loud name}}`;
|
||||
const output = template({ name: 'yehuda' });
|
||||
const output = template({name: 'yehuda'});
|
||||
|
||||
assertEquals(output, 'YEHUDA');
|
||||
@@ -0,0 +1,5 @@
|
||||
export function assertEquals(actual, expected) {
|
||||
if (actual !== expected) {
|
||||
throw new Error(`Expected "${actual}" to equal "${expected}"`);
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -7,5 +7,10 @@ rm dist package-lock.json -rf
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
node dist/bundle.js
|
||||
echo "Success"
|
||||
for i in dist/*-test.js ; do
|
||||
echo "----------------------"
|
||||
echo "-- Running $i"
|
||||
echo "----------------------"
|
||||
node "$i"
|
||||
echo "Success"
|
||||
done
|
||||
@@ -0,0 +1,33 @@
|
||||
const fs = require('fs');
|
||||
|
||||
const testFiles = fs.readdirSync('src');
|
||||
const entryPoints = {};
|
||||
testFiles
|
||||
.filter(file => file.match(/-test.js$/))
|
||||
.forEach(file => {
|
||||
entryPoints[file] = `./src/${file}`;
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
entry: entryPoints,
|
||||
mode: 'production',
|
||||
output: {
|
||||
filename: '[name]',
|
||||
path: __dirname + '/dist'
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.js?$/,
|
||||
exclude: /node_modules/,
|
||||
use: {
|
||||
loader: 'babel-loader',
|
||||
options: { cacheDirectory: false },
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
optimization: {
|
||||
minimize: false
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "webpack-test",
|
||||
"description": "Various tests with Handlebars and Webpack",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"build": "webpack --config webpack.config.js",
|
||||
"test": "node dist/main.js"
|
||||
},
|
||||
"private": true,
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"handlebars": "file:../..",
|
||||
"handlebars-loader": "^1.7.1",
|
||||
"webpack": "^4.39.3",
|
||||
"webpack-cli": "^3.3.7"
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import Handlebars from 'handlebars/dist/handlebars';
|
||||
|
||||
import { assertEquals } from './lib/assert';
|
||||
import {assertEquals} from './lib/assert';
|
||||
|
||||
const template = Handlebars.compile('Author: {{author}}');
|
||||
assertEquals(template({ author: 'Yehuda' }), 'Author: Yehuda');
|
||||
assertEquals(template({author: 'Yehuda'}), 'Author: Yehuda');
|
||||
@@ -0,0 +1,6 @@
|
||||
import Handlebars from 'handlebars';
|
||||
import {assertEquals} from './lib/assert';
|
||||
|
||||
|
||||
const template = Handlebars.compile('Author: {{author}}');
|
||||
assertEquals(template({author: 'Yehuda'}), 'Author: Yehuda');
|
||||
@@ -0,0 +1,8 @@
|
||||
import {assertEquals} from './lib/assert';
|
||||
|
||||
import testTemplate from './test-template.handlebars';
|
||||
assertEquals(testTemplate({author: 'Yehuda'}).trim(), 'Author: Yehuda');
|
||||
|
||||
|
||||
const testTemplateRequire = require('./test-template.handlebars');
|
||||
assertEquals(testTemplateRequire({author: 'Yehuda'}).trim(), 'Author: Yehuda');
|
||||
+3
-3
@@ -1,10 +1,10 @@
|
||||
import * as HandlebarsViaImport from 'handlebars';
|
||||
const HandlebarsViaRequire = require('handlebars');
|
||||
import { assertEquals } from './lib/assert';
|
||||
import {assertEquals} from './lib/assert';
|
||||
|
||||
HandlebarsViaImport.registerHelper('loud', function(text) {
|
||||
return text.toUpperCase();
|
||||
return text.toUpperCase();
|
||||
});
|
||||
|
||||
const template = HandlebarsViaRequire.compile('Author: {{loud author}}');
|
||||
assertEquals(template({ author: 'Yehuda' }), 'Author: YEHUDA');
|
||||
assertEquals(template({author: 'Yehuda'}), 'Author: YEHUDA');
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import * as Handlebars from 'handlebars/dist/handlebars';
|
||||
|
||||
import { assertEquals } from './lib/assert';
|
||||
import {assertEquals} from './lib/assert';
|
||||
|
||||
const template = Handlebars.compile('Author: {{author}}');
|
||||
assertEquals(template({ author: 'Yehuda' }), 'Author: Yehuda');
|
||||
assertEquals(template({author: 'Yehuda'}), 'Author: Yehuda');
|
||||
@@ -0,0 +1,5 @@
|
||||
import * as Handlebars from 'handlebars';
|
||||
import {assertEquals} from './lib/assert';
|
||||
|
||||
const template = Handlebars.compile('Author: {{author}}');
|
||||
assertEquals(template({author: 'Yehuda'}), 'Author: Yehuda');
|
||||
@@ -0,0 +1,5 @@
|
||||
export function assertEquals(actual, expected) {
|
||||
if (actual !== expected) {
|
||||
throw new Error(`Expected "${actual}" to equal "${expected}"`);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@ set -e
|
||||
|
||||
# Cleanup: package-lock and "npm ci" is not working with local dependencies
|
||||
rm dist package-lock.json -rf
|
||||
npm install --legacy-peer-deps
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
for i in dist/*-test.js ; do
|
||||
@@ -0,0 +1,22 @@
|
||||
const fs = require('fs');
|
||||
|
||||
const testFiles = fs.readdirSync('src');
|
||||
const entryPoints = {};
|
||||
testFiles
|
||||
.filter(file => file.match(/-test.js$/))
|
||||
.forEach(file => {
|
||||
entryPoints[file] = `./src/${file}`;
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
entry: entryPoints,
|
||||
output: {
|
||||
filename: '[name]',
|
||||
path: __dirname + '/dist'
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{test: /\.handlebars$/, loader: 'handlebars-loader'}
|
||||
]
|
||||
}
|
||||
};
|
||||
@@ -1,8 +0,0 @@
|
||||
module.exports = {
|
||||
env: {
|
||||
// Handlebars should not use node or browser-specific APIs
|
||||
'shared-node-browser': true,
|
||||
node: false,
|
||||
browser: false
|
||||
}
|
||||
};
|
||||
+3
-10
@@ -2,21 +2,16 @@ import runtime from './handlebars.runtime';
|
||||
|
||||
// Compiler imports
|
||||
import AST from './handlebars/compiler/ast';
|
||||
import {
|
||||
parser as Parser,
|
||||
parse,
|
||||
parseWithoutProcessing
|
||||
} from './handlebars/compiler/base';
|
||||
import { parser as Parser, parse, parseWithoutProcessing } from './handlebars/compiler/base';
|
||||
import { Compiler, compile, precompile } from './handlebars/compiler/compiler';
|
||||
import JavaScriptCompiler from './handlebars/compiler/javascript-compiler';
|
||||
import Visitor from './handlebars/compiler/visitor';
|
||||
|
||||
import noConflict from './handlebars/no-conflict';
|
||||
|
||||
let _create = runtime.create;
|
||||
function create() {
|
||||
let hb = _create();
|
||||
|
||||
let hb = runtime.create();
|
||||
hb.create = create;
|
||||
hb.compile = function(input, options) {
|
||||
return compile(input, options, hb);
|
||||
};
|
||||
@@ -35,8 +30,6 @@ function create() {
|
||||
}
|
||||
|
||||
let inst = create();
|
||||
inst.create = create;
|
||||
|
||||
noConflict(inst);
|
||||
|
||||
inst.Visitor = Visitor;
|
||||
|
||||
+31
-10
@@ -4,31 +4,52 @@ import * as base from './handlebars/base';
|
||||
// (This is done to easily share code between commonjs and browse envs)
|
||||
import SafeString from './handlebars/safe-string';
|
||||
import Exception from './handlebars/exception';
|
||||
import * as Utils from './handlebars/utils';
|
||||
import * as runtime from './handlebars/runtime';
|
||||
import {
|
||||
extend,
|
||||
toString,
|
||||
isFunction,
|
||||
isArray,
|
||||
indexOf,
|
||||
escapeExpression,
|
||||
isEmpty,
|
||||
createFrame,
|
||||
blockParams,
|
||||
appendContextPath
|
||||
} from './handlebars/utils';
|
||||
import {checkRevision, template, wrapProgram, resolvePartial, invokePartial, noop} from './handlebars/runtime';
|
||||
|
||||
import noConflict from './handlebars/no-conflict';
|
||||
|
||||
// For compatibility and usage outside of module systems, make the Handlebars object a namespace
|
||||
function create() {
|
||||
export function create() {
|
||||
let hb = new base.HandlebarsEnvironment();
|
||||
|
||||
Utils.extend(hb, base);
|
||||
extend(hb, base);
|
||||
hb.SafeString = SafeString;
|
||||
hb.Exception = Exception;
|
||||
hb.Utils = Utils;
|
||||
hb.escapeExpression = Utils.escapeExpression;
|
||||
|
||||
hb.VM = runtime;
|
||||
hb.Utils = {
|
||||
extend,
|
||||
toString,
|
||||
isFunction,
|
||||
isArray,
|
||||
indexOf,
|
||||
escapeExpression,
|
||||
isEmpty,
|
||||
createFrame,
|
||||
blockParams,
|
||||
appendContextPath
|
||||
};
|
||||
hb.escapeExpression = escapeExpression;
|
||||
hb.create = create;
|
||||
hb.VM = {checkRevision, template, wrapProgram, resolvePartial, invokePartial, noop};
|
||||
hb.template = function(spec) {
|
||||
return runtime.template(spec, hb);
|
||||
return template(spec, hb);
|
||||
};
|
||||
|
||||
return hb;
|
||||
}
|
||||
|
||||
let inst = create();
|
||||
inst.create = create;
|
||||
|
||||
noConflict(inst);
|
||||
|
||||
|
||||
+8
-22
@@ -1,11 +1,10 @@
|
||||
import { createFrame, extend, toString } from './utils';
|
||||
import {createFrame, extend, toString} from './utils';
|
||||
import Exception from './exception';
|
||||
import { registerDefaultHelpers } from './helpers';
|
||||
import { registerDefaultDecorators } from './decorators';
|
||||
import {registerDefaultHelpers} from './helpers';
|
||||
import {registerDefaultDecorators} from './decorators';
|
||||
import logger from './logger';
|
||||
import { resetLoggedProperties } from './internal/proto-access';
|
||||
|
||||
export const VERSION = '4.7.9';
|
||||
export const VERSION = '4.5.3';
|
||||
export const COMPILER_REVISION = 8;
|
||||
export const LAST_COMPATIBLE_COMPILER_REVISION = 7;
|
||||
|
||||
@@ -39,9 +38,7 @@ HandlebarsEnvironment.prototype = {
|
||||
|
||||
registerHelper: function(name, fn) {
|
||||
if (toString.call(name) === objectType) {
|
||||
if (fn) {
|
||||
throw new Exception('Arg not supported with multiple helpers');
|
||||
}
|
||||
if (fn) { throw new Exception('Arg not supported with multiple helpers'); }
|
||||
extend(this.helpers, name);
|
||||
} else {
|
||||
this.helpers[name] = fn;
|
||||
@@ -56,9 +53,7 @@ HandlebarsEnvironment.prototype = {
|
||||
extend(this.partials, name);
|
||||
} else {
|
||||
if (typeof partial === 'undefined') {
|
||||
throw new Exception(
|
||||
`Attempting to register a partial called "${name}" as undefined`
|
||||
);
|
||||
throw new Exception(`Attempting to register a partial called "${name}" as undefined`);
|
||||
}
|
||||
this.partials[name] = partial;
|
||||
}
|
||||
@@ -69,9 +64,7 @@ HandlebarsEnvironment.prototype = {
|
||||
|
||||
registerDecorator: function(name, fn) {
|
||||
if (toString.call(name) === objectType) {
|
||||
if (fn) {
|
||||
throw new Exception('Arg not supported with multiple decorators');
|
||||
}
|
||||
if (fn) { throw new Exception('Arg not supported with multiple decorators'); }
|
||||
extend(this.decorators, name);
|
||||
} else {
|
||||
this.decorators[name] = fn;
|
||||
@@ -79,16 +72,9 @@ HandlebarsEnvironment.prototype = {
|
||||
},
|
||||
unregisterDecorator: function(name) {
|
||||
delete this.decorators[name];
|
||||
},
|
||||
/**
|
||||
* Reset the memory of illegal property accesses that have already been logged.
|
||||
* @deprecated should only be used in handlebars test-cases
|
||||
*/
|
||||
resetLoggedPropertyAccesses() {
|
||||
resetLoggedProperties();
|
||||
}
|
||||
};
|
||||
|
||||
export let log = logger.log;
|
||||
|
||||
export { createFrame, logger };
|
||||
export {createFrame, logger};
|
||||
|
||||
@@ -5,28 +5,24 @@ let AST = {
|
||||
// * it is an eligible helper, and
|
||||
// * it has at least one parameter or hash segment
|
||||
helperExpression: function(node) {
|
||||
return (
|
||||
node.type === 'SubExpression' ||
|
||||
((node.type === 'MustacheStatement' ||
|
||||
node.type === 'BlockStatement') &&
|
||||
!!((node.params && node.params.length) || node.hash))
|
||||
);
|
||||
return (node.type === 'SubExpression')
|
||||
|| ((node.type === 'MustacheStatement' || node.type === 'BlockStatement')
|
||||
&& !!((node.params && node.params.length) || node.hash));
|
||||
},
|
||||
|
||||
scopedId: function(path) {
|
||||
return /^\.|this\b/.test(path.original);
|
||||
return (/^\.|this\b/).test(path.original);
|
||||
},
|
||||
|
||||
// an ID is simple if it only has one part, and that part is not
|
||||
// `..` or `this`.
|
||||
simpleId: function(path) {
|
||||
return (
|
||||
path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth
|
||||
);
|
||||
return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Must be exported as an object rather than the root of the module as the jison lexer
|
||||
// must modify the object to operate properly.
|
||||
export default AST;
|
||||
|
||||
@@ -10,9 +10,7 @@ extend(yy, Helpers);
|
||||
|
||||
export function parseWithoutProcessing(input, options) {
|
||||
// Just return if an already-compiled AST was passed in.
|
||||
if (input.type === 'Program') {
|
||||
return input;
|
||||
}
|
||||
if (input.type === 'Program') { return input; }
|
||||
|
||||
parser.yy = yy;
|
||||
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
/* global define, require */
|
||||
import { isArray } from '../utils';
|
||||
import {isArray} from '../utils';
|
||||
|
||||
let SourceNode;
|
||||
|
||||
try {
|
||||
/* istanbul ignore next */
|
||||
if (typeof define !== 'function' || !define.amd) {
|
||||
// We don't support this in AMD environments. For these environments, we assume that
|
||||
// they are running on the browser and thus have no need for the source-map library.
|
||||
let SourceMap = require('source-map');
|
||||
SourceNode = SourceMap.SourceNode;
|
||||
}
|
||||
// the 'source-map' map package is ignored in 'umd' and 'amd' builds (via webpack-config)
|
||||
let SourceMap = require('source-map');
|
||||
SourceNode = SourceMap.SourceNode;
|
||||
} catch (err) {
|
||||
/* NOP */
|
||||
}
|
||||
@@ -38,7 +33,7 @@ if (!SourceNode) {
|
||||
this.src = chunks + this.src;
|
||||
},
|
||||
toStringWithSourceMap: function() {
|
||||
return { code: this.toString() };
|
||||
return {code: this.toString()};
|
||||
},
|
||||
toString: function() {
|
||||
return this.src;
|
||||
@@ -46,6 +41,7 @@ if (!SourceNode) {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
function castChunk(chunk, codeGen, loc) {
|
||||
if (isArray(chunk)) {
|
||||
let ret = [];
|
||||
@@ -61,6 +57,7 @@ function castChunk(chunk, codeGen, loc) {
|
||||
return chunk;
|
||||
}
|
||||
|
||||
|
||||
function CodeGen(srcFile) {
|
||||
this.srcFile = srcFile;
|
||||
this.source = [];
|
||||
@@ -92,22 +89,17 @@ CodeGen.prototype = {
|
||||
},
|
||||
|
||||
empty: function() {
|
||||
let loc = this.currentLocation || { start: {} };
|
||||
let loc = this.currentLocation || {start: {}};
|
||||
return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
|
||||
},
|
||||
wrap: function(chunk, loc = this.currentLocation || { start: {} }) {
|
||||
wrap: function(chunk, loc = this.currentLocation || {start: {}}) {
|
||||
if (chunk instanceof SourceNode) {
|
||||
return chunk;
|
||||
}
|
||||
|
||||
chunk = castChunk(chunk, this, loc);
|
||||
|
||||
return new SourceNode(
|
||||
loc.start.line,
|
||||
loc.start.column,
|
||||
this.srcFile,
|
||||
chunk
|
||||
);
|
||||
return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
|
||||
},
|
||||
|
||||
functionCall: function(fn, type, params) {
|
||||
@@ -116,17 +108,13 @@ CodeGen.prototype = {
|
||||
},
|
||||
|
||||
quotedString: function(str) {
|
||||
return (
|
||||
'"' +
|
||||
(str + '')
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/\r/g, '\\r')
|
||||
.replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
|
||||
.replace(/\u2029/g, '\\u2029') +
|
||||
'"'
|
||||
);
|
||||
return '"' + (str + '')
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/\r/g, '\\r')
|
||||
.replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
|
||||
.replace(/\u2029/g, '\\u2029') + '"';
|
||||
},
|
||||
|
||||
objectLiteral: function(obj) {
|
||||
@@ -145,6 +133,7 @@ CodeGen.prototype = {
|
||||
return ret;
|
||||
},
|
||||
|
||||
|
||||
generateList: function(entries) {
|
||||
let ret = this.empty();
|
||||
|
||||
@@ -169,3 +158,4 @@ CodeGen.prototype = {
|
||||
};
|
||||
|
||||
export default CodeGen;
|
||||
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
/* eslint-disable new-cap */
|
||||
|
||||
import Exception from '../exception';
|
||||
import {
|
||||
isArray,
|
||||
indexOf,
|
||||
extend,
|
||||
sanitizeDepth,
|
||||
sanitizeParts
|
||||
} from '../utils';
|
||||
import {isArray, indexOf, extend} from '../utils';
|
||||
import AST from './ast';
|
||||
|
||||
const slice = [].slice;
|
||||
@@ -30,11 +24,8 @@ Compiler.prototype = {
|
||||
|
||||
for (let i = 0; i < len; i++) {
|
||||
let opcode = this.opcodes[i],
|
||||
otherOpcode = other.opcodes[i];
|
||||
if (
|
||||
opcode.opcode !== otherOpcode.opcode ||
|
||||
!argEquals(opcode.args, otherOpcode.args)
|
||||
) {
|
||||
otherOpcode = other.opcodes[i];
|
||||
if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -63,28 +54,24 @@ Compiler.prototype = {
|
||||
|
||||
options.blockParams = options.blockParams || [];
|
||||
|
||||
options.knownHelpers = extend(
|
||||
Object.create(null),
|
||||
{
|
||||
helperMissing: true,
|
||||
blockHelperMissing: true,
|
||||
each: true,
|
||||
if: true,
|
||||
unless: true,
|
||||
with: true,
|
||||
log: true,
|
||||
lookup: true
|
||||
},
|
||||
options.knownHelpers
|
||||
);
|
||||
options.knownHelpers = extend(Object.create(null), {
|
||||
'helperMissing': true,
|
||||
'blockHelperMissing': true,
|
||||
'each': true,
|
||||
'if': true,
|
||||
'unless': true,
|
||||
'with': true,
|
||||
'log': true,
|
||||
'lookup': true
|
||||
}, options.knownHelpers);
|
||||
|
||||
return this.accept(program);
|
||||
},
|
||||
|
||||
compileProgram: function(program) {
|
||||
let childCompiler = new this.compiler(), // eslint-disable-line new-cap
|
||||
result = childCompiler.compile(program, this.options),
|
||||
guid = this.guid++;
|
||||
result = childCompiler.compile(program, this.options),
|
||||
guid = this.guid++;
|
||||
|
||||
this.usePartial = this.usePartial || result.usePartial;
|
||||
|
||||
@@ -110,7 +97,7 @@ Compiler.prototype = {
|
||||
this.options.blockParams.unshift(program.blockParams);
|
||||
|
||||
let body = program.body,
|
||||
bodyLength = body.length;
|
||||
bodyLength = body.length;
|
||||
for (let i = 0; i < bodyLength; i++) {
|
||||
this.accept(body[i]);
|
||||
}
|
||||
@@ -127,7 +114,7 @@ Compiler.prototype = {
|
||||
transformLiteralToPath(block);
|
||||
|
||||
let program = block.program,
|
||||
inverse = block.inverse;
|
||||
inverse = block.inverse;
|
||||
|
||||
program = program && this.compileProgram(program);
|
||||
inverse = inverse && this.compileProgram(inverse);
|
||||
@@ -162,7 +149,7 @@ Compiler.prototype = {
|
||||
DecoratorBlock(decorator) {
|
||||
let program = decorator.program && this.compileProgram(decorator.program);
|
||||
let params = this.setupFullMustacheParams(decorator, program, undefined),
|
||||
path = decorator.path;
|
||||
path = decorator.path;
|
||||
|
||||
this.useDecorators = true;
|
||||
this.opcode('registerDecorator', params.length, path.original);
|
||||
@@ -178,20 +165,17 @@ Compiler.prototype = {
|
||||
|
||||
let params = partial.params;
|
||||
if (params.length > 1) {
|
||||
throw new Exception(
|
||||
'Unsupported number of partial arguments: ' + params.length,
|
||||
partial
|
||||
);
|
||||
throw new Exception('Unsupported number of partial arguments: ' + params.length, partial);
|
||||
} else if (!params.length) {
|
||||
if (this.options.explicitPartialContext) {
|
||||
this.opcode('pushLiteral', 'undefined');
|
||||
} else {
|
||||
params.push({ type: 'PathExpression', parts: [], depth: 0 });
|
||||
params.push({type: 'PathExpression', parts: [], depth: 0});
|
||||
}
|
||||
}
|
||||
|
||||
let partialName = partial.name.original,
|
||||
isDynamic = partial.name.type === 'SubExpression';
|
||||
isDynamic = partial.name.type === 'SubExpression';
|
||||
if (isDynamic) {
|
||||
this.accept(partial.name);
|
||||
}
|
||||
@@ -224,6 +208,7 @@ Compiler.prototype = {
|
||||
this.DecoratorBlock(decorator);
|
||||
},
|
||||
|
||||
|
||||
ContentStatement: function(content) {
|
||||
if (content.value) {
|
||||
this.opcode('appendContent', content.value);
|
||||
@@ -246,10 +231,10 @@ Compiler.prototype = {
|
||||
},
|
||||
ambiguousSexpr: function(sexpr, program, inverse) {
|
||||
let path = sexpr.path,
|
||||
name = path.parts[0],
|
||||
isBlock = program != null || inverse != null;
|
||||
name = path.parts[0],
|
||||
isBlock = program != null || inverse != null;
|
||||
|
||||
this.opcode('getContext', sanitizeDepth(path.depth));
|
||||
this.opcode('getContext', path.depth);
|
||||
|
||||
this.opcode('pushProgram', program);
|
||||
this.opcode('pushProgram', inverse);
|
||||
@@ -269,57 +254,40 @@ Compiler.prototype = {
|
||||
|
||||
helperSexpr: function(sexpr, program, inverse) {
|
||||
let params = this.setupFullMustacheParams(sexpr, program, inverse),
|
||||
path = sexpr.path,
|
||||
name = path.parts[0];
|
||||
path = sexpr.path,
|
||||
name = path.parts[0];
|
||||
|
||||
if (this.options.knownHelpers[name]) {
|
||||
this.opcode('invokeKnownHelper', params.length, name);
|
||||
} else if (this.options.knownHelpersOnly) {
|
||||
throw new Exception(
|
||||
'You specified knownHelpersOnly, but used the unknown helper ' + name,
|
||||
sexpr
|
||||
);
|
||||
throw new Exception('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
|
||||
} else {
|
||||
path.strict = true;
|
||||
path.falsy = true;
|
||||
|
||||
this.accept(path);
|
||||
this.opcode(
|
||||
'invokeHelper',
|
||||
params.length,
|
||||
path.original,
|
||||
AST.helpers.simpleId(path)
|
||||
);
|
||||
this.opcode('invokeHelper', params.length, path.original, AST.helpers.simpleId(path));
|
||||
}
|
||||
},
|
||||
|
||||
PathExpression: function(path) {
|
||||
// Sanitize untrusted AST values at the compiler boundary.
|
||||
// javascript-compiler.js trusts all opcode arguments to be safe.
|
||||
const depth = sanitizeDepth(path.depth);
|
||||
const parts = sanitizeParts(path.parts);
|
||||
this.addDepth(path.depth);
|
||||
this.opcode('getContext', path.depth);
|
||||
|
||||
this.addDepth(depth);
|
||||
this.opcode('getContext', depth);
|
||||
|
||||
let name = parts[0],
|
||||
scoped = AST.helpers.scopedId(path),
|
||||
blockParamId = !depth && !scoped && this.blockParamIndex(name);
|
||||
let name = path.parts[0],
|
||||
scoped = AST.helpers.scopedId(path),
|
||||
blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
|
||||
|
||||
if (blockParamId) {
|
||||
this.opcode(
|
||||
'lookupBlockParam',
|
||||
[Number(blockParamId[0]), Number(blockParamId[1])],
|
||||
parts
|
||||
);
|
||||
this.opcode('lookupBlockParam', blockParamId, path.parts);
|
||||
} else if (!name) {
|
||||
// Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
|
||||
this.opcode('pushContext');
|
||||
} else if (path.data) {
|
||||
this.options.data = true;
|
||||
this.opcode('lookupData', depth, parts, path.strict);
|
||||
this.opcode('lookupData', path.depth, path.parts, path.strict);
|
||||
} else {
|
||||
this.opcode('lookupOnContext', parts, path.falsy, path.strict, scoped);
|
||||
this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -328,11 +296,11 @@ Compiler.prototype = {
|
||||
},
|
||||
|
||||
NumberLiteral: function(number) {
|
||||
this.opcode('pushLiteral', Number(number.value));
|
||||
this.opcode('pushLiteral', number.value);
|
||||
},
|
||||
|
||||
BooleanLiteral: function(bool) {
|
||||
this.opcode('pushLiteral', bool.value === true ? 'true' : 'false');
|
||||
this.opcode('pushLiteral', bool.value);
|
||||
},
|
||||
|
||||
UndefinedLiteral: function() {
|
||||
@@ -345,8 +313,8 @@ Compiler.prototype = {
|
||||
|
||||
Hash: function(hash) {
|
||||
let pairs = hash.pairs,
|
||||
i = 0,
|
||||
l = pairs.length;
|
||||
i = 0,
|
||||
l = pairs.length;
|
||||
|
||||
this.opcode('pushHash');
|
||||
|
||||
@@ -361,11 +329,7 @@ Compiler.prototype = {
|
||||
|
||||
// HELPERS
|
||||
opcode: function(name) {
|
||||
this.opcodes.push({
|
||||
opcode: name,
|
||||
args: slice.call(arguments, 1),
|
||||
loc: this.sourceNode[0].loc
|
||||
});
|
||||
this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
|
||||
},
|
||||
|
||||
addDepth: function(depth) {
|
||||
@@ -394,7 +358,7 @@ Compiler.prototype = {
|
||||
// An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
|
||||
if (isEligible && !isHelper) {
|
||||
let name = sexpr.path.parts[0],
|
||||
options = this.options;
|
||||
options = this.options;
|
||||
if (options.knownHelpers[name]) {
|
||||
isHelper = true;
|
||||
} else if (options.knownHelpersOnly) {
|
||||
@@ -419,16 +383,18 @@ Compiler.prototype = {
|
||||
|
||||
pushParam: function(val) {
|
||||
let value = val.value != null ? val.value : val.original || '';
|
||||
let depth = sanitizeDepth(val.depth);
|
||||
|
||||
if (this.stringParams) {
|
||||
if (value.replace) {
|
||||
value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
|
||||
value = value
|
||||
.replace(/^(\.?\.\/)*/g, '')
|
||||
.replace(/\//g, '.');
|
||||
}
|
||||
if (depth) {
|
||||
this.addDepth(depth);
|
||||
|
||||
if (val.depth) {
|
||||
this.addDepth(val.depth);
|
||||
}
|
||||
this.opcode('getContext', depth);
|
||||
this.opcode('getContext', val.depth || 0);
|
||||
this.opcode('pushStringParam', value, val.type);
|
||||
|
||||
if (val.type === 'SubExpression') {
|
||||
@@ -440,7 +406,7 @@ Compiler.prototype = {
|
||||
if (this.trackIds) {
|
||||
let blockParamIndex;
|
||||
if (val.parts && !AST.helpers.scopedId(val) && !val.depth) {
|
||||
blockParamIndex = this.blockParamIndex(val.parts[0]);
|
||||
blockParamIndex = this.blockParamIndex(val.parts[0]);
|
||||
}
|
||||
if (blockParamIndex) {
|
||||
let blockParamChild = val.parts.slice(1).join('.');
|
||||
@@ -449,9 +415,9 @@ Compiler.prototype = {
|
||||
value = val.original || value;
|
||||
if (value.replace) {
|
||||
value = value
|
||||
.replace(/^this(?:\.|$)/, '')
|
||||
.replace(/^\.\//, '')
|
||||
.replace(/^\.$/, '');
|
||||
.replace(/^this(?:\.|$)/, '')
|
||||
.replace(/^\.\//, '')
|
||||
.replace(/^\.$/, '');
|
||||
}
|
||||
|
||||
this.opcode('pushId', val.type, value);
|
||||
@@ -478,13 +444,9 @@ Compiler.prototype = {
|
||||
},
|
||||
|
||||
blockParamIndex: function(name) {
|
||||
for (
|
||||
let depth = 0, len = this.options.blockParams.length;
|
||||
depth < len;
|
||||
depth++
|
||||
) {
|
||||
for (let depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
|
||||
let blockParams = this.options.blockParams[depth],
|
||||
param = blockParams && indexOf(blockParams, name);
|
||||
param = blockParams && indexOf(blockParams, name);
|
||||
if (blockParams && param >= 0) {
|
||||
return [depth, param];
|
||||
}
|
||||
@@ -493,14 +455,8 @@ Compiler.prototype = {
|
||||
};
|
||||
|
||||
export function precompile(input, options, env) {
|
||||
if (
|
||||
input == null ||
|
||||
(typeof input !== 'string' && input.type !== 'Program')
|
||||
) {
|
||||
throw new Exception(
|
||||
'You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' +
|
||||
input
|
||||
);
|
||||
if (input == null || (typeof input !== 'string' && input.type !== 'Program')) {
|
||||
throw new Exception('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
|
||||
}
|
||||
|
||||
options = options || {};
|
||||
@@ -512,19 +468,13 @@ export function precompile(input, options, env) {
|
||||
}
|
||||
|
||||
let ast = env.parse(input, options),
|
||||
environment = new env.Compiler().compile(ast, options);
|
||||
environment = new env.Compiler().compile(ast, options);
|
||||
return new env.JavaScriptCompiler().compile(environment, options);
|
||||
}
|
||||
|
||||
export function compile(input, options = {}, env) {
|
||||
if (
|
||||
input == null ||
|
||||
(typeof input !== 'string' && input.type !== 'Program')
|
||||
) {
|
||||
throw new Exception(
|
||||
'You must pass a string or Handlebars AST to Handlebars.compile. You passed ' +
|
||||
input
|
||||
);
|
||||
if (input == null || (typeof input !== 'string' && input.type !== 'Program')) {
|
||||
throw new Exception('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
|
||||
}
|
||||
|
||||
options = extend({}, options);
|
||||
@@ -539,13 +489,8 @@ export function compile(input, options = {}, env) {
|
||||
|
||||
function compileInput() {
|
||||
let ast = env.parse(input, options),
|
||||
environment = new env.Compiler().compile(ast, options),
|
||||
templateSpec = new env.JavaScriptCompiler().compile(
|
||||
environment,
|
||||
options,
|
||||
undefined,
|
||||
true
|
||||
);
|
||||
environment = new env.Compiler().compile(ast, options),
|
||||
templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
|
||||
return env.template(templateSpec);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,9 @@ function validateClose(open, close) {
|
||||
close = close.path ? close.path.original : close;
|
||||
|
||||
if (open.path.original !== close) {
|
||||
let errorNode = { loc: open.path.loc };
|
||||
let errorNode = {loc: open.path.loc};
|
||||
|
||||
throw new Exception(
|
||||
open.path.original + " doesn't match " + close,
|
||||
errorNode
|
||||
);
|
||||
throw new Exception(open.path.original + " doesn't match " + close, errorNode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,26 +38,27 @@ export function stripFlags(open, close) {
|
||||
}
|
||||
|
||||
export function stripComment(comment) {
|
||||
return comment.replace(/^\{\{~?!-?-?/, '').replace(/-?-?~?\}\}$/, '');
|
||||
return comment.replace(/^\{\{~?!-?-?/, '')
|
||||
.replace(/-?-?~?\}\}$/, '');
|
||||
}
|
||||
|
||||
export function preparePath(data, parts, loc) {
|
||||
loc = this.locInfo(loc);
|
||||
|
||||
let original = data ? '@' : '',
|
||||
dig = [],
|
||||
depth = 0;
|
||||
dig = [],
|
||||
depth = 0;
|
||||
|
||||
for (let i = 0, l = parts.length; i < l; i++) {
|
||||
let part = parts[i].part,
|
||||
// If we have [] syntax then we do not treat path references as operators,
|
||||
// i.e. foo.[this] resolves to approximately context.foo['this']
|
||||
isLiteral = parts[i].original !== part;
|
||||
// If we have [] syntax then we do not treat path references as operators,
|
||||
// i.e. foo.[this] resolves to approximately context.foo['this']
|
||||
isLiteral = parts[i].original !== part;
|
||||
original += (parts[i].separator || '') + part;
|
||||
|
||||
if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
|
||||
if (dig.length > 0) {
|
||||
throw new Exception('Invalid path: ' + original, { loc });
|
||||
throw new Exception('Invalid path: ' + original, {loc});
|
||||
} else if (part === '..') {
|
||||
depth++;
|
||||
}
|
||||
@@ -82,9 +80,9 @@ export function preparePath(data, parts, loc) {
|
||||
export function prepareMustache(path, params, hash, open, strip, locInfo) {
|
||||
// Must use charAt to support IE pre-10
|
||||
let escapeFlag = open.charAt(3) || open.charAt(2),
|
||||
escaped = escapeFlag !== '{' && escapeFlag !== '&';
|
||||
escaped = escapeFlag !== '{' && escapeFlag !== '&';
|
||||
|
||||
let decorator = /\*/.test(open);
|
||||
let decorator = (/\*/.test(open));
|
||||
return {
|
||||
type: decorator ? 'Decorator' : 'MustacheStatement',
|
||||
path,
|
||||
@@ -120,30 +118,21 @@ export function prepareRawBlock(openRawBlock, contents, close, locInfo) {
|
||||
};
|
||||
}
|
||||
|
||||
export function prepareBlock(
|
||||
openBlock,
|
||||
program,
|
||||
inverseAndProgram,
|
||||
close,
|
||||
inverted,
|
||||
locInfo
|
||||
) {
|
||||
export function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
|
||||
if (close && close.path) {
|
||||
validateClose(openBlock, close);
|
||||
}
|
||||
|
||||
let decorator = /\*/.test(openBlock.open);
|
||||
let decorator = (/\*/.test(openBlock.open));
|
||||
|
||||
program.blockParams = openBlock.blockParams;
|
||||
|
||||
let inverse, inverseStrip;
|
||||
let inverse,
|
||||
inverseStrip;
|
||||
|
||||
if (inverseAndProgram) {
|
||||
if (decorator) {
|
||||
throw new Exception(
|
||||
'Unexpected inverse block on decorator',
|
||||
inverseAndProgram
|
||||
);
|
||||
throw new Exception('Unexpected inverse block on decorator', inverseAndProgram);
|
||||
}
|
||||
|
||||
if (inverseAndProgram.chain) {
|
||||
@@ -177,7 +166,7 @@ export function prepareBlock(
|
||||
export function prepareProgram(statements, loc) {
|
||||
if (!loc && statements.length) {
|
||||
const firstLoc = statements[0].loc,
|
||||
lastLoc = statements[statements.length - 1].loc;
|
||||
lastLoc = statements[statements.length - 1].loc;
|
||||
|
||||
/* istanbul ignore else */
|
||||
if (firstLoc && lastLoc) {
|
||||
@@ -203,6 +192,7 @@ export function prepareProgram(statements, loc) {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
export function preparePartialBlock(open, program, close, locInfo) {
|
||||
validateClose(open, close);
|
||||
|
||||
@@ -217,3 +207,4 @@ export function preparePartialBlock(open, program, close, locInfo) {
|
||||
loc: this.locInfo(locInfo)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { COMPILER_REVISION, REVISION_CHANGES } from '../base';
|
||||
import Exception from '../exception';
|
||||
import { isArray } from '../utils';
|
||||
import {isArray} from '../utils';
|
||||
import CodeGen from './code-gen';
|
||||
import {dangerousPropertyRegex} from '../helpers/lookup';
|
||||
|
||||
function Literal(value) {
|
||||
this.value = value;
|
||||
@@ -12,21 +13,28 @@ function JavaScriptCompiler() {}
|
||||
JavaScriptCompiler.prototype = {
|
||||
// PUBLIC API: You can override these methods in a subclass to provide
|
||||
// alternative compiled forms for name lookup and buffering semantics
|
||||
nameLookup: function(parent, name /*, type */) {
|
||||
return this.internalNameLookup(parent, name);
|
||||
nameLookup: function(parent, name/* , type*/) {
|
||||
if (dangerousPropertyRegex.test(name)) {
|
||||
const isEnumerable = [ this.aliasable('container.propertyIsEnumerable'), '.call(', parent, ',', JSON.stringify(name), ')'];
|
||||
return ['(', isEnumerable, '?', _actualLookup(), ' : undefined)'];
|
||||
}
|
||||
return _actualLookup();
|
||||
|
||||
function _actualLookup() {
|
||||
if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
|
||||
return [parent, '.', name];
|
||||
} else {
|
||||
return [parent, '[', JSON.stringify(name), ']'];
|
||||
}
|
||||
}
|
||||
},
|
||||
depthedLookup: function(name) {
|
||||
return [
|
||||
this.aliasable('container.lookup'),
|
||||
'(depths, ',
|
||||
JSON.stringify(name),
|
||||
')'
|
||||
];
|
||||
return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
|
||||
},
|
||||
|
||||
compilerInfo: function() {
|
||||
const revision = COMPILER_REVISION,
|
||||
versions = REVISION_CHANGES[revision];
|
||||
versions = REVISION_CHANGES[revision];
|
||||
return [revision, versions];
|
||||
},
|
||||
|
||||
@@ -54,12 +62,6 @@ JavaScriptCompiler.prototype = {
|
||||
return this.quotedString('');
|
||||
},
|
||||
// END PUBLIC API
|
||||
internalNameLookup: function(parent, name) {
|
||||
this.lookupPropertyFunctionIsUsed = true;
|
||||
return ['lookupProperty(', parent, ',', JSON.stringify(name), ')'];
|
||||
},
|
||||
|
||||
lookupPropertyFunctionIsUsed: false,
|
||||
|
||||
compile: function(environment, options, context, asObject) {
|
||||
this.environment = environment;
|
||||
@@ -89,18 +91,14 @@ JavaScriptCompiler.prototype = {
|
||||
|
||||
this.compileChildren(environment, options);
|
||||
|
||||
this.useDepths =
|
||||
this.useDepths ||
|
||||
environment.useDepths ||
|
||||
environment.useDecorators ||
|
||||
this.options.compat;
|
||||
this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
|
||||
this.useBlockParams = this.useBlockParams || environment.useBlockParams;
|
||||
|
||||
let opcodes = environment.opcodes,
|
||||
opcode,
|
||||
firstLoc,
|
||||
i,
|
||||
l;
|
||||
opcode,
|
||||
firstLoc,
|
||||
i,
|
||||
l;
|
||||
|
||||
for (i = 0, l = opcodes.length; i < l; i++) {
|
||||
opcode = opcodes[i];
|
||||
@@ -122,28 +120,13 @@ JavaScriptCompiler.prototype = {
|
||||
if (!this.decorators.isEmpty()) {
|
||||
this.useDecorators = true;
|
||||
|
||||
this.decorators.prepend([
|
||||
'var decorators = container.decorators, ',
|
||||
this.lookupPropertyFunctionVarDeclaration(),
|
||||
';\n'
|
||||
]);
|
||||
this.decorators.prepend('var decorators = container.decorators;\n');
|
||||
this.decorators.push('return fn;');
|
||||
|
||||
if (asObject) {
|
||||
this.decorators = Function.apply(this, [
|
||||
'fn',
|
||||
'props',
|
||||
'container',
|
||||
'depth0',
|
||||
'data',
|
||||
'blockParams',
|
||||
'depths',
|
||||
this.decorators.merge()
|
||||
]);
|
||||
this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
|
||||
} else {
|
||||
this.decorators.prepend(
|
||||
'function(fn, props, container, depth0, data, blockParams, depths) {\n'
|
||||
);
|
||||
this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
|
||||
this.decorators.push('}\n');
|
||||
this.decorators = this.decorators.merge();
|
||||
}
|
||||
@@ -163,12 +146,14 @@ JavaScriptCompiler.prototype = {
|
||||
ret.useDecorators = true;
|
||||
}
|
||||
|
||||
let { programs, decorators } = this.context;
|
||||
let {programs, decorators} = this.context;
|
||||
for (i = 0, l = programs.length; i < l; i++) {
|
||||
ret[i] = programs[i];
|
||||
if (decorators[i]) {
|
||||
ret[i + '_d'] = decorators[i];
|
||||
ret.useDecorators = true;
|
||||
if (programs[i]) {
|
||||
ret[i] = programs[i];
|
||||
if (decorators[i]) {
|
||||
ret[i + '_d'] = decorators[i];
|
||||
ret.useDecorators = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,11 +176,11 @@ JavaScriptCompiler.prototype = {
|
||||
if (!asObject) {
|
||||
ret.compiler = JSON.stringify(ret.compiler);
|
||||
|
||||
this.source.currentLocation = { start: { line: 1, column: 0 } };
|
||||
this.source.currentLocation = {start: {line: 1, column: 0}};
|
||||
ret = this.objectLiteral(ret);
|
||||
|
||||
if (options.srcName) {
|
||||
ret = ret.toStringWithSourceMap({ file: options.destName });
|
||||
ret = ret.toStringWithSourceMap({file: options.destName});
|
||||
ret.map = ret.map && ret.map.toString();
|
||||
} else {
|
||||
ret = ret.toString();
|
||||
@@ -236,15 +221,11 @@ JavaScriptCompiler.prototype = {
|
||||
Object.keys(this.aliases).forEach(alias => {
|
||||
let node = this.aliases[alias];
|
||||
if (node.children && node.referenceCount > 1) {
|
||||
varDeclarations += ', alias' + ++aliasCount + '=' + alias;
|
||||
varDeclarations += ', alias' + (++aliasCount) + '=' + alias;
|
||||
node.children[0] = 'alias' + aliasCount;
|
||||
}
|
||||
});
|
||||
|
||||
if (this.lookupPropertyFunctionIsUsed) {
|
||||
varDeclarations += ', ' + this.lookupPropertyFunctionVarDeclaration();
|
||||
}
|
||||
|
||||
let params = ['container', 'depth0', 'helpers', 'partials', 'data'];
|
||||
|
||||
if (this.useBlockParams || this.useDepths) {
|
||||
@@ -262,23 +243,18 @@ JavaScriptCompiler.prototype = {
|
||||
|
||||
return Function.apply(this, params);
|
||||
} else {
|
||||
return this.source.wrap([
|
||||
'function(',
|
||||
params.join(','),
|
||||
') {\n ',
|
||||
source,
|
||||
'}'
|
||||
]);
|
||||
return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
|
||||
}
|
||||
},
|
||||
mergeSource: function(varDeclarations) {
|
||||
let isSimple = this.environment.isSimple,
|
||||
appendOnly = !this.forceBuffer,
|
||||
appendFirst,
|
||||
sourceSeen,
|
||||
bufferStart,
|
||||
bufferEnd;
|
||||
this.source.each(line => {
|
||||
appendOnly = !this.forceBuffer,
|
||||
appendFirst,
|
||||
|
||||
sourceSeen,
|
||||
bufferStart,
|
||||
bufferEnd;
|
||||
this.source.each((line) => {
|
||||
if (line.appendToBuffer) {
|
||||
if (bufferStart) {
|
||||
line.prepend(' + ');
|
||||
@@ -304,6 +280,7 @@ JavaScriptCompiler.prototype = {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
if (appendOnly) {
|
||||
if (bufferStart) {
|
||||
bufferStart.prepend('return ');
|
||||
@@ -312,8 +289,7 @@ JavaScriptCompiler.prototype = {
|
||||
this.source.push('return "";');
|
||||
}
|
||||
} else {
|
||||
varDeclarations +=
|
||||
', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
|
||||
varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
|
||||
|
||||
if (bufferStart) {
|
||||
bufferStart.prepend('return buffer + ');
|
||||
@@ -324,25 +300,12 @@ JavaScriptCompiler.prototype = {
|
||||
}
|
||||
|
||||
if (varDeclarations) {
|
||||
this.source.prepend(
|
||||
'var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n')
|
||||
);
|
||||
this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
|
||||
}
|
||||
|
||||
return this.source.merge();
|
||||
},
|
||||
|
||||
lookupPropertyFunctionVarDeclaration: function() {
|
||||
return `
|
||||
lookupProperty = container.lookupProperty || function(parent, propertyName) {
|
||||
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
|
||||
return parent[propertyName];
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
`.trim();
|
||||
},
|
||||
|
||||
// [blockValue]
|
||||
//
|
||||
// On stack, before: hash, inverse, program, value
|
||||
@@ -353,10 +316,8 @@ JavaScriptCompiler.prototype = {
|
||||
// replace it on the stack with the result of properly
|
||||
// invoking blockHelperMissing.
|
||||
blockValue: function(name) {
|
||||
let blockHelperMissing = this.aliasable(
|
||||
'container.hooks.blockHelperMissing'
|
||||
),
|
||||
params = [this.contextName(0)];
|
||||
let blockHelperMissing = this.aliasable('container.hooks.blockHelperMissing'),
|
||||
params = [this.contextName(0)];
|
||||
this.setupHelperArgs(name, 0, params);
|
||||
|
||||
let blockName = this.popStack();
|
||||
@@ -373,10 +334,8 @@ JavaScriptCompiler.prototype = {
|
||||
// On stack, after, if lastHelper: value
|
||||
ambiguousBlockValue: function() {
|
||||
// We're being a bit cheeky and reusing the options value from the prior exec
|
||||
let blockHelperMissing = this.aliasable(
|
||||
'container.hooks.blockHelperMissing'
|
||||
),
|
||||
params = [this.contextName(0)];
|
||||
let blockHelperMissing = this.aliasable('container.hooks.blockHelperMissing'),
|
||||
params = [this.contextName(0)];
|
||||
this.setupHelperArgs('', 0, params, true);
|
||||
|
||||
this.flushInline();
|
||||
@@ -385,14 +344,9 @@ JavaScriptCompiler.prototype = {
|
||||
params.splice(1, 0, current);
|
||||
|
||||
this.pushSource([
|
||||
'if (!',
|
||||
this.lastHelper,
|
||||
') { ',
|
||||
current,
|
||||
' = ',
|
||||
this.source.functionCall(blockHelperMissing, 'call', params),
|
||||
'}'
|
||||
]);
|
||||
'if (!', this.lastHelper, ') { ',
|
||||
current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params),
|
||||
'}']);
|
||||
},
|
||||
|
||||
// [appendContent]
|
||||
@@ -422,24 +376,14 @@ JavaScriptCompiler.prototype = {
|
||||
// Otherwise, the empty string is appended
|
||||
append: function() {
|
||||
if (this.isInline()) {
|
||||
this.replaceStack(current => [' != null ? ', current, ' : ""']);
|
||||
this.replaceStack((current) => [' != null ? ', current, ' : ""']);
|
||||
|
||||
this.pushSource(this.appendToBuffer(this.popStack()));
|
||||
} else {
|
||||
let local = this.popStack();
|
||||
this.pushSource([
|
||||
'if (',
|
||||
local,
|
||||
' != null) { ',
|
||||
this.appendToBuffer(local, undefined, true),
|
||||
' }'
|
||||
]);
|
||||
this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
|
||||
if (this.environment.isSimple) {
|
||||
this.pushSource([
|
||||
'else { ',
|
||||
this.appendToBuffer("''", undefined, true),
|
||||
' }'
|
||||
]);
|
||||
this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -451,14 +395,8 @@ JavaScriptCompiler.prototype = {
|
||||
//
|
||||
// Escape `value` and append it to the buffer
|
||||
appendEscaped: function() {
|
||||
this.pushSource(
|
||||
this.appendToBuffer([
|
||||
this.aliasable('container.escapeExpression'),
|
||||
'(',
|
||||
this.popStack(),
|
||||
')'
|
||||
])
|
||||
);
|
||||
this.pushSource(this.appendToBuffer(
|
||||
[this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
|
||||
},
|
||||
|
||||
// [getContext]
|
||||
@@ -533,24 +471,16 @@ JavaScriptCompiler.prototype = {
|
||||
this.resolvePath('data', parts, 0, true, strict);
|
||||
},
|
||||
|
||||
resolvePath: function(type, parts, startPartIndex, falsy, strict) {
|
||||
resolvePath: function(type, parts, i, falsy, strict) {
|
||||
if (this.options.strict || this.options.assumeObjects) {
|
||||
this.push(
|
||||
strictLookup(
|
||||
this.options.strict && strict,
|
||||
this,
|
||||
parts,
|
||||
startPartIndex,
|
||||
type
|
||||
)
|
||||
);
|
||||
this.push(strictLookup(this.options.strict && strict, this, parts, type));
|
||||
return;
|
||||
}
|
||||
|
||||
let len = parts.length;
|
||||
for (let i = startPartIndex; i < len; i++) {
|
||||
for (; i < len; i++) {
|
||||
/* eslint-disable no-loop-func */
|
||||
this.replaceStack(current => {
|
||||
this.replaceStack((current) => {
|
||||
let lookup = this.nameLookup(current, parts[i], type);
|
||||
// We want to ensure that zero and false are handled properly if the context (falsy flag)
|
||||
// needs to have the special handling for these values.
|
||||
@@ -573,14 +503,7 @@ JavaScriptCompiler.prototype = {
|
||||
// If the `value` is a lambda, replace it on the stack by
|
||||
// the return value of the lambda
|
||||
resolvePossibleLambda: function() {
|
||||
this.push([
|
||||
this.aliasable('container.lambda'),
|
||||
'(',
|
||||
this.popStack(),
|
||||
', ',
|
||||
this.contextName(0),
|
||||
')'
|
||||
]);
|
||||
this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
|
||||
},
|
||||
|
||||
// [pushStringParam]
|
||||
@@ -620,7 +543,7 @@ JavaScriptCompiler.prototype = {
|
||||
if (this.hash) {
|
||||
this.hashes.push(this.hash);
|
||||
}
|
||||
this.hash = { values: {}, types: [], contexts: [], ids: [] };
|
||||
this.hash = {values: {}, types: [], contexts: [], ids: []};
|
||||
},
|
||||
popHash: function() {
|
||||
let hash = this.hash;
|
||||
@@ -684,25 +607,11 @@ JavaScriptCompiler.prototype = {
|
||||
// and inserts the decorator into the decorators list.
|
||||
registerDecorator(paramSize, name) {
|
||||
let foundDecorator = this.nameLookup('decorators', name, 'decorator'),
|
||||
options = this.setupHelperArgs(name, paramSize);
|
||||
options = this.setupHelperArgs(name, paramSize);
|
||||
|
||||
// Store the resolved decorator in a variable and verify it is a function before
|
||||
// calling it. Without this, unregistered decorators can cause an unhandled TypeError
|
||||
// (calling undefined), which crashes the process — enabling Denial of Service.
|
||||
this.decorators.push(['var decorator = ', foundDecorator, ';']);
|
||||
this.decorators.push([
|
||||
'if (typeof decorator !== "function") { throw new Error(',
|
||||
this.quotedString('Missing decorator: "' + name + '"'),
|
||||
'); }'
|
||||
]);
|
||||
this.decorators.push([
|
||||
'fn = ',
|
||||
this.decorators.functionCall('decorator', '', [
|
||||
'fn',
|
||||
'props',
|
||||
'container',
|
||||
options
|
||||
]),
|
||||
this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]),
|
||||
' || fn;'
|
||||
]);
|
||||
},
|
||||
@@ -718,32 +627,21 @@ JavaScriptCompiler.prototype = {
|
||||
// If the helper is not found, `helperMissing` is called.
|
||||
invokeHelper: function(paramSize, name, isSimple) {
|
||||
let nonHelper = this.popStack(),
|
||||
helper = this.setupHelper(paramSize, name);
|
||||
helper = this.setupHelper(paramSize, name);
|
||||
|
||||
let possibleFunctionCalls = [];
|
||||
|
||||
if (isSimple) {
|
||||
// direct call to helper
|
||||
if (isSimple) { // direct call to helper
|
||||
possibleFunctionCalls.push(helper.name);
|
||||
}
|
||||
// call a function from the input object
|
||||
possibleFunctionCalls.push(nonHelper);
|
||||
if (!this.options.strict) {
|
||||
possibleFunctionCalls.push(
|
||||
this.aliasable('container.hooks.helperMissing')
|
||||
);
|
||||
possibleFunctionCalls.push(this.aliasable('container.hooks.helperMissing'));
|
||||
}
|
||||
|
||||
let functionLookupCode = [
|
||||
'(',
|
||||
this.itemsSeparatedBy(possibleFunctionCalls, '||'),
|
||||
')'
|
||||
];
|
||||
let functionCall = this.source.functionCall(
|
||||
functionLookupCode,
|
||||
'call',
|
||||
helper.callParams
|
||||
);
|
||||
let functionLookupCode = ['(', this.itemsSeparatedBy(possibleFunctionCalls, '||'), ')'];
|
||||
let functionCall = this.source.functionCall(functionLookupCode, 'call', helper.callParams);
|
||||
this.push(functionCall);
|
||||
},
|
||||
|
||||
@@ -787,31 +685,22 @@ JavaScriptCompiler.prototype = {
|
||||
this.emptyHash();
|
||||
let helper = this.setupHelper(0, name, helperCall);
|
||||
|
||||
let helperName = (this.lastHelper = this.nameLookup(
|
||||
'helpers',
|
||||
name,
|
||||
'helper'
|
||||
));
|
||||
let helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
|
||||
|
||||
let lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
|
||||
if (!this.options.strict) {
|
||||
lookup[0] = '(helper = ';
|
||||
lookup.push(
|
||||
' != null ? helper : ',
|
||||
this.aliasable('container.hooks.helperMissing')
|
||||
' != null ? helper : ',
|
||||
this.aliasable('container.hooks.helperMissing')
|
||||
);
|
||||
}
|
||||
|
||||
this.push([
|
||||
'(',
|
||||
lookup,
|
||||
helper.paramsInit ? ['),(', helper.paramsInit] : [],
|
||||
'),',
|
||||
'(typeof helper === ',
|
||||
this.aliasable('"function"'),
|
||||
' ? ',
|
||||
this.source.functionCall('helper', 'call', helper.callParams),
|
||||
' : helper))'
|
||||
'(', lookup,
|
||||
(helper.paramsInit ? ['),(', helper.paramsInit] : []), '),',
|
||||
'(typeof helper === ', this.aliasable('"function"'), ' ? ',
|
||||
this.source.functionCall('helper', 'call', helper.callParams), ' : helper))'
|
||||
]);
|
||||
},
|
||||
|
||||
@@ -824,7 +713,7 @@ JavaScriptCompiler.prototype = {
|
||||
// and pushes the result of the invocation back.
|
||||
invokePartial: function(isDynamic, name, indent) {
|
||||
let params = [],
|
||||
options = this.setupParams(name, 1, params);
|
||||
options = this.setupParams(name, 1, params);
|
||||
|
||||
if (isDynamic) {
|
||||
name = this.popStack();
|
||||
@@ -861,9 +750,9 @@ JavaScriptCompiler.prototype = {
|
||||
// Pops a value off the stack and assigns it to the current hash
|
||||
assignToHash: function(key) {
|
||||
let value = this.popStack(),
|
||||
context,
|
||||
type,
|
||||
id;
|
||||
context,
|
||||
type,
|
||||
id;
|
||||
|
||||
if (this.trackIds) {
|
||||
id = this.popStack();
|
||||
@@ -889,13 +778,8 @@ JavaScriptCompiler.prototype = {
|
||||
pushId: function(type, name, child) {
|
||||
if (type === 'BlockParam') {
|
||||
this.pushStackLiteral(
|
||||
'blockParams[' +
|
||||
name[0] +
|
||||
'].path[' +
|
||||
name[1] +
|
||||
']' +
|
||||
(child ? ' + ' + JSON.stringify('.' + child) : '')
|
||||
);
|
||||
'blockParams[' + name[0] + '].path[' + name[1] + ']'
|
||||
+ (child ? ' + ' + JSON.stringify('.' + child) : ''));
|
||||
} else if (type === 'PathExpression') {
|
||||
this.pushString(name);
|
||||
} else if (type === 'SubExpression') {
|
||||
@@ -910,9 +794,7 @@ JavaScriptCompiler.prototype = {
|
||||
compiler: JavaScriptCompiler,
|
||||
|
||||
compileChildren: function(environment, options) {
|
||||
let children = environment.children,
|
||||
child,
|
||||
compiler;
|
||||
let children = environment.children, child, compiler;
|
||||
|
||||
for (let i = 0, l = children.length; i < l; i++) {
|
||||
child = children[i];
|
||||
@@ -921,16 +803,11 @@ JavaScriptCompiler.prototype = {
|
||||
let existing = this.matchExistingProgram(child);
|
||||
|
||||
if (existing == null) {
|
||||
// Placeholder to prevent name conflicts for nested children
|
||||
let index = this.context.programs.push('') - 1;
|
||||
this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
|
||||
let index = this.context.programs.length;
|
||||
child.index = index;
|
||||
child.name = 'program' + index;
|
||||
this.context.programs[index] = compiler.compile(
|
||||
child,
|
||||
options,
|
||||
this.context,
|
||||
!this.precompile
|
||||
);
|
||||
this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
|
||||
this.context.decorators[index] = compiler.decorators;
|
||||
this.context.environments[index] = child;
|
||||
|
||||
@@ -958,7 +835,7 @@ JavaScriptCompiler.prototype = {
|
||||
|
||||
programExpression: function(guid) {
|
||||
let child = this.environment.children[guid],
|
||||
programParams = [child.index, 'data', child.blockParams];
|
||||
programParams = [child.index, 'data', child.blockParams];
|
||||
|
||||
if (this.useBlockParams || this.useDepths) {
|
||||
programParams.push('blockParams');
|
||||
@@ -993,11 +870,7 @@ JavaScriptCompiler.prototype = {
|
||||
pushSource: function(source) {
|
||||
if (this.pendingContent) {
|
||||
this.source.push(
|
||||
this.appendToBuffer(
|
||||
this.source.quotedString(this.pendingContent),
|
||||
this.pendingLocation
|
||||
)
|
||||
);
|
||||
this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
|
||||
this.pendingContent = undefined;
|
||||
}
|
||||
|
||||
@@ -1008,9 +881,9 @@ JavaScriptCompiler.prototype = {
|
||||
|
||||
replaceStack: function(callback) {
|
||||
let prefix = ['('],
|
||||
stack,
|
||||
createdStack,
|
||||
usedLiteral;
|
||||
stack,
|
||||
createdStack,
|
||||
usedLiteral;
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (!this.isInline()) {
|
||||
@@ -1047,9 +920,7 @@ JavaScriptCompiler.prototype = {
|
||||
|
||||
incrStack: function() {
|
||||
this.stackSlot++;
|
||||
if (this.stackSlot > this.stackVars.length) {
|
||||
this.stackVars.push('stack' + this.stackSlot);
|
||||
}
|
||||
if (this.stackSlot > this.stackVars.length) { this.stackVars.push('stack' + this.stackSlot); }
|
||||
return this.topStackName();
|
||||
},
|
||||
topStackName: function() {
|
||||
@@ -1076,9 +947,9 @@ JavaScriptCompiler.prototype = {
|
||||
|
||||
popStack: function(wrapped) {
|
||||
let inline = this.isInline(),
|
||||
item = (inline ? this.inlineStack : this.compileStack).pop();
|
||||
item = (inline ? this.inlineStack : this.compileStack).pop();
|
||||
|
||||
if (!wrapped && item instanceof Literal) {
|
||||
if (!wrapped && (item instanceof Literal)) {
|
||||
return item.value;
|
||||
} else {
|
||||
if (!inline) {
|
||||
@@ -1093,8 +964,8 @@ JavaScriptCompiler.prototype = {
|
||||
},
|
||||
|
||||
topStack: function() {
|
||||
let stack = this.isInline() ? this.inlineStack : this.compileStack,
|
||||
item = stack[stack.length - 1];
|
||||
let stack = (this.isInline() ? this.inlineStack : this.compileStack),
|
||||
item = stack[stack.length - 1];
|
||||
|
||||
/* istanbul ignore if */
|
||||
if (item instanceof Literal) {
|
||||
@@ -1136,13 +1007,9 @@ JavaScriptCompiler.prototype = {
|
||||
|
||||
setupHelper: function(paramSize, name, blockHelper) {
|
||||
let params = [],
|
||||
paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
|
||||
paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
|
||||
let foundHelper = this.nameLookup('helpers', name, 'helper'),
|
||||
callContext = this.aliasable(
|
||||
`${this.contextName(0)} != null ? ${this.contextName(
|
||||
0
|
||||
)} : (container.nullContext || {})`
|
||||
);
|
||||
callContext = this.aliasable(`${this.contextName(0)} != null ? ${this.contextName(0)} : (container.nullContext || {})`);
|
||||
|
||||
return {
|
||||
params: params,
|
||||
@@ -1154,11 +1021,11 @@ JavaScriptCompiler.prototype = {
|
||||
|
||||
setupParams: function(helper, paramSize, params) {
|
||||
let options = {},
|
||||
contexts = [],
|
||||
types = [],
|
||||
ids = [],
|
||||
objectArgs = !params,
|
||||
param;
|
||||
contexts = [],
|
||||
types = [],
|
||||
ids = [],
|
||||
objectArgs = !params,
|
||||
param;
|
||||
|
||||
if (objectArgs) {
|
||||
params = [];
|
||||
@@ -1176,7 +1043,7 @@ JavaScriptCompiler.prototype = {
|
||||
}
|
||||
|
||||
let inverse = this.popStack(),
|
||||
program = this.popStack();
|
||||
program = this.popStack();
|
||||
|
||||
// Avoid setting fn and inverse if neither are set. This allows
|
||||
// helpers to do a check for `if (options.fn)`
|
||||
@@ -1239,6 +1106,7 @@ JavaScriptCompiler.prototype = {
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
(function() {
|
||||
const reservedWords = (
|
||||
'break else new var' +
|
||||
@@ -1259,45 +1127,31 @@ JavaScriptCompiler.prototype = {
|
||||
' null true false'
|
||||
).split(' ');
|
||||
|
||||
const compilerWords = (JavaScriptCompiler.RESERVED_WORDS = {});
|
||||
const compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
|
||||
|
||||
for (let i = 0, l = reservedWords.length; i < l; i++) {
|
||||
compilerWords[reservedWords[i]] = true;
|
||||
}
|
||||
})();
|
||||
}());
|
||||
|
||||
/**
|
||||
* @deprecated May be removed in the next major version
|
||||
*/
|
||||
JavaScriptCompiler.isValidJavaScriptVariableName = function(name) {
|
||||
return (
|
||||
!JavaScriptCompiler.RESERVED_WORDS[name] &&
|
||||
/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name)
|
||||
);
|
||||
return !JavaScriptCompiler.RESERVED_WORDS[name] && (/^[a-zA-Z_$][0-9a-zA-Z_$]*$/).test(name);
|
||||
};
|
||||
|
||||
function strictLookup(requireTerminal, compiler, parts, startPartIndex, type) {
|
||||
function strictLookup(requireTerminal, compiler, parts, type) {
|
||||
let stack = compiler.popStack(),
|
||||
len = parts.length;
|
||||
i = 0,
|
||||
len = parts.length;
|
||||
if (requireTerminal) {
|
||||
len--;
|
||||
}
|
||||
|
||||
for (let i = startPartIndex; i < len; i++) {
|
||||
for (; i < len; i++) {
|
||||
stack = compiler.nameLookup(stack, parts[i], type);
|
||||
}
|
||||
|
||||
if (requireTerminal) {
|
||||
return [
|
||||
compiler.aliasable('container.strict'),
|
||||
'(',
|
||||
stack,
|
||||
', ',
|
||||
compiler.quotedString(parts[len]),
|
||||
', ',
|
||||
JSON.stringify(compiler.source.currentLocation),
|
||||
' )'
|
||||
];
|
||||
return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ', ', JSON.stringify(compiler.source.currentLocation), ' )'];
|
||||
} else {
|
||||
return stack;
|
||||
}
|
||||
|
||||
@@ -24,14 +24,13 @@ PrintVisitor.prototype.pad = function(string) {
|
||||
|
||||
PrintVisitor.prototype.Program = function(program) {
|
||||
let out = '',
|
||||
body = program.body,
|
||||
i,
|
||||
l;
|
||||
body = program.body,
|
||||
i, l;
|
||||
|
||||
if (program.blockParams) {
|
||||
let blockParams = 'BLOCK PARAMS: [';
|
||||
for (i = 0, l = program.blockParams.length; i < l; i++) {
|
||||
blockParams += ' ' + program.blockParams[i];
|
||||
blockParams += ' ' + program.blockParams[i];
|
||||
}
|
||||
blockParams += ' ]';
|
||||
out += this.pad(blockParams);
|
||||
@@ -53,14 +52,11 @@ PrintVisitor.prototype.Decorator = function(mustache) {
|
||||
return this.pad('{{ DIRECTIVE ' + this.SubExpression(mustache) + ' }}');
|
||||
};
|
||||
|
||||
PrintVisitor.prototype.BlockStatement = PrintVisitor.prototype.DecoratorBlock = function(
|
||||
block
|
||||
) {
|
||||
PrintVisitor.prototype.BlockStatement =
|
||||
PrintVisitor.prototype.DecoratorBlock = function(block) {
|
||||
let out = '';
|
||||
|
||||
out += this.pad(
|
||||
(block.type === 'DecoratorBlock' ? 'DIRECTIVE ' : '') + 'BLOCK:'
|
||||
);
|
||||
out += this.pad((block.type === 'DecoratorBlock' ? 'DIRECTIVE ' : '') + 'BLOCK:');
|
||||
this.padding++;
|
||||
out += this.pad(this.SubExpression(block));
|
||||
if (block.program) {
|
||||
@@ -70,16 +66,12 @@ PrintVisitor.prototype.BlockStatement = PrintVisitor.prototype.DecoratorBlock =
|
||||
this.padding--;
|
||||
}
|
||||
if (block.inverse) {
|
||||
if (block.program) {
|
||||
this.padding++;
|
||||
}
|
||||
if (block.program) { this.padding++; }
|
||||
out += this.pad('{{^}}');
|
||||
this.padding++;
|
||||
out += this.accept(block.inverse);
|
||||
this.padding--;
|
||||
if (block.program) {
|
||||
this.padding--;
|
||||
}
|
||||
if (block.program) { this.padding--; }
|
||||
}
|
||||
this.padding--;
|
||||
|
||||
@@ -123,8 +115,8 @@ PrintVisitor.prototype.CommentStatement = function(comment) {
|
||||
|
||||
PrintVisitor.prototype.SubExpression = function(sexpr) {
|
||||
let params = sexpr.params,
|
||||
paramStrings = [],
|
||||
hash;
|
||||
paramStrings = [],
|
||||
hash;
|
||||
|
||||
for (let i = 0, l = params.length; i < l; i++) {
|
||||
paramStrings.push(this.accept(params[i]));
|
||||
@@ -142,6 +134,7 @@ PrintVisitor.prototype.PathExpression = function(id) {
|
||||
return (id.data ? '@' : '') + 'PATH:' + path;
|
||||
};
|
||||
|
||||
|
||||
PrintVisitor.prototype.StringLiteral = function(string) {
|
||||
return '"' + string.value + '"';
|
||||
};
|
||||
@@ -164,7 +157,7 @@ PrintVisitor.prototype.NullLiteral = function() {
|
||||
|
||||
PrintVisitor.prototype.Hash = function(hash) {
|
||||
let pairs = hash.pairs,
|
||||
joinedPairs = [];
|
||||
joinedPairs = [];
|
||||
|
||||
for (let i = 0, l = pairs.length; i < l; i++) {
|
||||
joinedPairs.push(this.accept(pairs[i]));
|
||||
|
||||
@@ -15,14 +15,7 @@ Visitor.prototype = {
|
||||
// Hacky sanity check: This may have a few false positives for type for the helper
|
||||
// methods but will generally do the right thing without a lot of overhead.
|
||||
if (value && !Visitor.prototype[value.type]) {
|
||||
throw new Exception(
|
||||
'Unexpected node type "' +
|
||||
value.type +
|
||||
'" found when accepting ' +
|
||||
name +
|
||||
' on ' +
|
||||
node.type
|
||||
);
|
||||
throw new Exception('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
|
||||
}
|
||||
node[name] = value;
|
||||
}
|
||||
|
||||
@@ -14,18 +14,18 @@ WhitespaceControl.prototype.Program = function(program) {
|
||||
let body = program.body;
|
||||
for (let i = 0, l = body.length; i < l; i++) {
|
||||
let current = body[i],
|
||||
strip = this.accept(current);
|
||||
strip = this.accept(current);
|
||||
|
||||
if (!strip) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
|
||||
_isNextWhitespace = isNextWhitespace(body, i, isRoot),
|
||||
openStandalone = strip.openStandalone && _isPrevWhitespace,
|
||||
closeStandalone = strip.closeStandalone && _isNextWhitespace,
|
||||
inlineStandalone =
|
||||
strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
|
||||
_isNextWhitespace = isNextWhitespace(body, i, isRoot),
|
||||
|
||||
openStandalone = strip.openStandalone && _isPrevWhitespace,
|
||||
closeStandalone = strip.closeStandalone && _isNextWhitespace,
|
||||
inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
|
||||
|
||||
if (strip.close) {
|
||||
omitRight(body, i, true);
|
||||
@@ -41,7 +41,7 @@ WhitespaceControl.prototype.Program = function(program) {
|
||||
// If we are on a standalone node, save the indent info for partials
|
||||
if (current.type === 'PartialStatement') {
|
||||
// Pull out the whitespace from the final line
|
||||
current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
|
||||
current.indent = (/([ \t]+$)/).exec(body[i - 1].original)[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,17 +62,17 @@ WhitespaceControl.prototype.Program = function(program) {
|
||||
return program;
|
||||
};
|
||||
|
||||
WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function(
|
||||
block
|
||||
) {
|
||||
WhitespaceControl.prototype.BlockStatement =
|
||||
WhitespaceControl.prototype.DecoratorBlock =
|
||||
WhitespaceControl.prototype.PartialBlockStatement = function(block) {
|
||||
this.accept(block.program);
|
||||
this.accept(block.inverse);
|
||||
|
||||
// Find the inverse program that is involed with whitespace stripping.
|
||||
let program = block.program || block.inverse,
|
||||
inverse = block.program && block.inverse,
|
||||
firstInverse = inverse,
|
||||
lastInverse = inverse;
|
||||
inverse = block.program && block.inverse,
|
||||
firstInverse = inverse,
|
||||
lastInverse = inverse;
|
||||
|
||||
if (inverse && inverse.chained) {
|
||||
firstInverse = inverse.body[0].program;
|
||||
@@ -112,11 +112,9 @@ WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.Decorat
|
||||
}
|
||||
|
||||
// Find standalone else statments
|
||||
if (
|
||||
!this.options.ignoreStandalone &&
|
||||
isPrevWhitespace(program.body) &&
|
||||
isNextWhitespace(firstInverse.body)
|
||||
) {
|
||||
if (!this.options.ignoreStandalone
|
||||
&& isPrevWhitespace(program.body)
|
||||
&& isNextWhitespace(firstInverse.body)) {
|
||||
omitLeft(program.body);
|
||||
omitRight(firstInverse.body);
|
||||
}
|
||||
@@ -127,15 +125,13 @@ WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.Decorat
|
||||
return strip;
|
||||
};
|
||||
|
||||
WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function(
|
||||
mustache
|
||||
) {
|
||||
WhitespaceControl.prototype.Decorator =
|
||||
WhitespaceControl.prototype.MustacheStatement = function(mustache) {
|
||||
return mustache.strip;
|
||||
};
|
||||
|
||||
WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function(
|
||||
node
|
||||
) {
|
||||
WhitespaceControl.prototype.PartialStatement =
|
||||
WhitespaceControl.prototype.CommentStatement = function(node) {
|
||||
/* istanbul ignore next */
|
||||
let strip = node.strip || {};
|
||||
return {
|
||||
@@ -145,6 +141,7 @@ WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.Comme
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
function isPrevWhitespace(body, i, isRoot) {
|
||||
if (i === undefined) {
|
||||
i = body.length;
|
||||
@@ -153,15 +150,13 @@ function isPrevWhitespace(body, i, isRoot) {
|
||||
// Nodes that end with newlines are considered whitespace (but are special
|
||||
// cased for strip operations)
|
||||
let prev = body[i - 1],
|
||||
sibling = body[i - 2];
|
||||
sibling = body[i - 2];
|
||||
if (!prev) {
|
||||
return isRoot;
|
||||
}
|
||||
|
||||
if (prev.type === 'ContentStatement') {
|
||||
return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(
|
||||
prev.original
|
||||
);
|
||||
return (sibling || !isRoot ? (/\r?\n\s*?$/) : (/(^|\r?\n)\s*?$/)).test(prev.original);
|
||||
}
|
||||
}
|
||||
function isNextWhitespace(body, i, isRoot) {
|
||||
@@ -170,15 +165,13 @@ function isNextWhitespace(body, i, isRoot) {
|
||||
}
|
||||
|
||||
let next = body[i + 1],
|
||||
sibling = body[i + 2];
|
||||
sibling = body[i + 2];
|
||||
if (!next) {
|
||||
return isRoot;
|
||||
}
|
||||
|
||||
if (next.type === 'ContentStatement') {
|
||||
return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(
|
||||
next.original
|
||||
);
|
||||
return (sibling || !isRoot ? (/^\s*?\r?\n/) : (/^\s*?(\r?\n|$)/)).test(next.original);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,19 +184,12 @@ function isNextWhitespace(body, i, isRoot) {
|
||||
// content is met.
|
||||
function omitRight(body, i, multiple) {
|
||||
let current = body[i == null ? 0 : i + 1];
|
||||
if (
|
||||
!current ||
|
||||
current.type !== 'ContentStatement' ||
|
||||
(!multiple && current.rightStripped)
|
||||
) {
|
||||
if (!current || current.type !== 'ContentStatement' || (!multiple && current.rightStripped)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let original = current.value;
|
||||
current.value = current.value.replace(
|
||||
multiple ? /^\s+/ : /^[ \t]*\r?\n?/,
|
||||
''
|
||||
);
|
||||
current.value = current.value.replace(multiple ? (/^\s+/) : (/^[ \t]*\r?\n?/), '');
|
||||
current.rightStripped = current.value !== original;
|
||||
}
|
||||
|
||||
@@ -216,17 +202,13 @@ function omitRight(body, i, multiple) {
|
||||
// content is met.
|
||||
function omitLeft(body, i, multiple) {
|
||||
let current = body[i == null ? body.length - 1 : i - 1];
|
||||
if (
|
||||
!current ||
|
||||
current.type !== 'ContentStatement' ||
|
||||
(!multiple && current.leftStripped)
|
||||
) {
|
||||
if (!current || current.type !== 'ContentStatement' || (!multiple && current.leftStripped)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// We omit the last node if it's whitespace only and not preceded by a non-content node.
|
||||
let original = current.value;
|
||||
current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
|
||||
current.value = current.value.replace(multiple ? (/\s+$/) : (/[ \t]+$/), '');
|
||||
current.leftStripped = current.value !== original;
|
||||
return current.leftStripped;
|
||||
}
|
||||
|
||||
@@ -3,3 +3,4 @@ import registerInline from './decorators/inline';
|
||||
export function registerDefaultDecorators(instance) {
|
||||
registerInline(instance);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { extend } from '../utils';
|
||||
import {extend} from '../utils';
|
||||
|
||||
export default function(instance) {
|
||||
instance.registerDecorator('inline', function(fn, props, container, options) {
|
||||
|
||||
@@ -1,20 +1,12 @@
|
||||
const errorProps = [
|
||||
'description',
|
||||
'fileName',
|
||||
'lineNumber',
|
||||
'endLineNumber',
|
||||
'message',
|
||||
'name',
|
||||
'number',
|
||||
'stack'
|
||||
];
|
||||
|
||||
const errorProps = ['description', 'fileName', 'lineNumber', 'endLineNumber', 'message', 'name', 'number', 'stack'];
|
||||
|
||||
function Exception(message, node) {
|
||||
let loc = node && node.loc,
|
||||
line,
|
||||
endLineNumber,
|
||||
column,
|
||||
endColumn;
|
||||
line,
|
||||
endLineNumber,
|
||||
column,
|
||||
endColumn;
|
||||
|
||||
if (loc) {
|
||||
line = loc.start.line;
|
||||
|
||||
@@ -20,8 +20,7 @@ export function moveHelperToHooks(instance, helperName, keepHelper) {
|
||||
if (instance.helpers[helperName]) {
|
||||
instance.hooks[helperName] = instance.helpers[helperName];
|
||||
if (!keepHelper) {
|
||||
// Using delete is slow
|
||||
instance.helpers[helperName] = undefined;
|
||||
delete instance.helpers[helperName];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { appendContextPath, createFrame, isArray } from '../utils';
|
||||
import {appendContextPath, createFrame, isArray} from '../utils';
|
||||
|
||||
export default function(instance) {
|
||||
instance.registerHelper('blockHelperMissing', function(context, options) {
|
||||
let inverse = options.inverse,
|
||||
fn = options.fn;
|
||||
fn = options.fn;
|
||||
|
||||
if (context === true) {
|
||||
return fn(this);
|
||||
@@ -22,11 +22,8 @@ export default function(instance) {
|
||||
} else {
|
||||
if (options.data && options.ids) {
|
||||
let data = createFrame(options.data);
|
||||
data.contextPath = appendContextPath(
|
||||
options.data.contextPath,
|
||||
options.name
|
||||
);
|
||||
options = { data: data };
|
||||
data.contextPath = appendContextPath(options.data.contextPath, options.name);
|
||||
options = {data: data};
|
||||
}
|
||||
|
||||
return fn(context, options);
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
import {
|
||||
appendContextPath,
|
||||
blockParams,
|
||||
createFrame,
|
||||
isArray,
|
||||
isFunction
|
||||
} from '../utils';
|
||||
import {appendContextPath, blockParams, createFrame, isArray, isFunction} from '../utils';
|
||||
import Exception from '../exception';
|
||||
|
||||
export default function(instance) {
|
||||
@@ -14,20 +8,17 @@ export default function(instance) {
|
||||
}
|
||||
|
||||
let fn = options.fn,
|
||||
inverse = options.inverse,
|
||||
i = 0,
|
||||
ret = '',
|
||||
data,
|
||||
contextPath;
|
||||
inverse = options.inverse,
|
||||
i = 0,
|
||||
ret = '',
|
||||
data,
|
||||
contextPath;
|
||||
|
||||
if (options.data && options.ids) {
|
||||
contextPath =
|
||||
appendContextPath(options.data.contextPath, options.ids[0]) + '.';
|
||||
contextPath = appendContextPath(options.data.contextPath, options.ids[0]) + '.';
|
||||
}
|
||||
|
||||
if (isFunction(context)) {
|
||||
context = context.call(this);
|
||||
}
|
||||
if (isFunction(context)) { context = context.call(this); }
|
||||
|
||||
if (options.data) {
|
||||
data = createFrame(options.data);
|
||||
@@ -45,15 +36,10 @@ export default function(instance) {
|
||||
}
|
||||
}
|
||||
|
||||
ret =
|
||||
ret +
|
||||
fn(context[field], {
|
||||
data: data,
|
||||
blockParams: blockParams(
|
||||
[context[field], field],
|
||||
[contextPath + field, null]
|
||||
)
|
||||
});
|
||||
ret = ret + fn(context[field], {
|
||||
data: data,
|
||||
blockParams: blockParams([context[field], field], [contextPath + field, null])
|
||||
});
|
||||
}
|
||||
|
||||
if (context && typeof context === 'object') {
|
||||
@@ -63,9 +49,9 @@ export default function(instance) {
|
||||
execIteration(i, i, i === context.length - 1);
|
||||
}
|
||||
}
|
||||
} else if (typeof Symbol === 'function' && context[Symbol.iterator]) {
|
||||
} else if (global.Symbol && context[global.Symbol.iterator]) {
|
||||
const newContext = [];
|
||||
const iterator = context[Symbol.iterator]();
|
||||
const iterator = context[global.Symbol.iterator]();
|
||||
for (let it = iterator.next(); !it.done; it = iterator.next()) {
|
||||
newContext.push(it.value);
|
||||
}
|
||||
|
||||
@@ -7,9 +7,7 @@ export default function(instance) {
|
||||
return undefined;
|
||||
} else {
|
||||
// Someone is actually trying to call something, blow up.
|
||||
throw new Exception(
|
||||
'Missing helper: "' + arguments[arguments.length - 1].name + '"'
|
||||
);
|
||||
throw new Exception('Missing helper: "' + arguments[arguments.length - 1].name + '"');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user