Compare commits

...

214 Commits

Author SHA1 Message Date
Hannah Wolfe e6ad93ea01 v4.7.6 2020-04-03 18:56:22 +01:00
Hannah Wolfe 2bf4fc6fd3 Update release notes 2020-04-03 18:55:39 +01:00
Hannah Wolfe b64202bc91 Update release-notes.md
- indicate changes have been reverted
2020-04-03 18:47:56 +01:00
Douglas Christopher Wilson c2f1e62031 Switch cmd parser to latest minimist 2020-04-03 18:44:30 +01:00
Hannah Wolfe 08e9a11a34 Revert "chore: set Node.js compatibility to v6+"
This reverts commit 309d2b49a1.
2020-04-03 18:44:30 +01:00
Hannah Wolfe 1fd2edee2a v4.7.5 2020-04-02 20:09:49 +01:00
Hannah Wolfe 3c9c2f5cf2 Update release notes 2020-04-02 20:09:16 +01:00
Hannah Wolfe 16487a088e chore: downgrade yargs to v14
- allows us to support Node v6 and v8 for now
2020-04-02 19:28:36 +01:00
Hannah Wolfe 309d2b49a1 chore: set Node.js compatibility to v6+
- drop support for versions less than Node v6 via engines
- update integration tests to also test newer versions
2020-04-02 19:28:35 +01:00
Nils Knappmeier 645ac73844 test: fix integration tests
- They should fail, if any test fails
- Use "set -e" instead of "|| exit 1", because it suffices to be specified
  at the top of each file
2020-04-02 19:25:37 +01:00
Nils Knappmeier b454b02147 docs: update release-docs in CONTRIBUTING.md
- remove ember testing
- add docs for updating the website.
- add list of required accesses to publish
2020-04-02 14:10:47 +02:00
Hannah Wolfe 7adc19ab40 v4.7.4 2020-04-01 18:20:30 +01:00
Hannah Wolfe 9dd8d10e12 Update release notes 2020-04-01 18:19:34 +01:00
Hannah Wolfe 4671c4b383 Use tmp directory for files written during tests
- Add spec/tmp directory with .gitkeep file to indicate the folder is intentional
- Add the folder contents to .gitignore
- Use this folder to output the sourcemap file during bin tests. This file is a sideeffect of the main test
2020-04-01 18:04:14 +01:00
DeeDeeG e46baa1fe2 tasks/test-bin.js: Delete duplicate test
Per comment by @ErisDS on the GitHub PR:
https://github.com/wycats/handlebars.js/pull/1666#issuecomment-606805248
2020-04-01 17:25:35 +01:00
Hannah Wolfe c491b4ea25 Revert "Update release-notes.md"
This reverts commit 738391a064.
Think this needs to be left to the release tool :|
2020-04-01 17:21:20 +01:00
Hannah Wolfe 738391a064 Update release-notes.md 2020-03-31 17:05:33 +01:00
Aori Nevo 80c4516fda chore: add unit tests for cli options (#1666)
- adds full unit tests for all cli options
- demonstrates that nothing changes between minimist and yargs except a minor order change in the --help text
- proves b9c4b253e works the same as before

Co-authored-by: fabb <fabb@users.noreply.github.com>
2020-03-31 16:54:11 +01:00
Avi Vahl d79212a662 fix: migrate from optimist to yargs (#1666)
closes #1658

- adapted code from master to latest yargs (`.option` calls).

```
4.x:
found 188 vulnerabilities (169 low, 4 moderate, 14 high, 1 critical) in 5815 scanned packages

4.x with this PR:
found 32 vulnerabilities (17 low, 1 moderate, 13 high, 1 critical) in 5829 scanned packages
```
2020-03-31 16:54:11 +01:00
Avi Vahl b440c38886 chore: ignore external @types in tests
- some indirect dependencies install @types packages which are not compatible with the older typescript.
- adjusted test's tsconfig to not pick these up automatically, as the actual .d.ts does not depend on these external types.
2020-03-31 16:53:54 +01:00
Eli Skeggs 2dba7eee3f docs: fix comparison link 2020-03-05 15:10:10 +01:00
Nils Knappmeier c9789691af v4.7.3 2020-02-05 06:10:33 +01:00
Nils Knappmeier 9278f217e0 Update release notes 2020-02-05 06:10:09 +01:00
roydukkey d78cc73d3c Fixes spelling and punctuation
(cherry picked from commit fd3ca85d13)
2020-02-05 06:06:42 +01:00
ismailjones 4de51fe26b Add Type Definition for Handlebars.VERSION, Fixes #1647 2020-02-04 23:32:10 +01:00
papasmile a32d05f2fc Include Type Definition for runtime.js in Package 2020-02-04 21:58:49 +01:00
Nils Knappmeier ad63f5189f chore: add missing "await" in aws-s3 publishing code
closes #1644
2020-01-21 21:52:23 +01:00
Nils Knappmeier 586e672c8b v4.7.2 2020-01-13 21:53:14 +01:00
Nils Knappmeier f0c6c4cc1f Update release notes 2020-01-13 21:52:50 +01:00
Nils Knappmeier a4fd391ba1 chore: execute saucelabs-task only if access-key exists
- up to now, the existance of the SAUCE_USERNAME was checked
  but this variable is even present in pull-requests from other
  repos. This means that builds fail, because the access key
  is not there.
  This change looks for SAUCE_ACCESS_KEY instead, which is
  a secure variable, only present in build originating from
  the handlebars.js repo.
2020-01-13 21:47:51 +01:00
Nils Knappmeier 9d5aa363cf fix: don't wrap helpers that are not functions
- helpers should always be a function, but in #1639 one seems to
  be undefined. This was not a problem before 4.6 because helpers
  weren't wrapped then.
  Now, we must take care only to wrap helpers (when adding
  the "lookupProperty" function to the options), if they
  are really functions.
2020-01-13 21:39:01 +01:00
Nils Knappmeier 14ba3d0c43 v4.7.1 2020-01-12 13:21:08 +01:00
Nils Knappmeier 4cddfe7017 Update release notes 2020-01-12 13:20:37 +01:00
Nils Knappmeier f152dfc892 fix: fix log output in case of illegal property access
- fix link url to handlebarsjs.com
2020-01-12 13:09:19 +01:00
Nils Knappmeier 3c1e252169 fix: log error for illegal property access only once per property 2020-01-12 13:06:56 +01:00
Nils Knappmeier 0d5c807017 v4.7.0 2020-01-10 17:24:06 +01:00
Nils Knappmeier 1f0834b1a2 Update release notes 2020-01-10 17:23:31 +01:00
Nils Knappmeier 575d8772e2 fix: use "logger" instead of console.error
... to be graceful with older browser without "console"
2020-01-10 17:06:57 +01:00
Nils Knappmeier 7af1c12db6 feat: default options for controlling proto access
This commmit adds the runtime options
- `allowProtoPropertiesByDefault` (boolean, default: false) and
- `allowProtoMethodsByDefault` (boolean, default: false)`
which can be used to allow access to prototype properties and
functions in general.

Specific properties and methods can still be disabled from access
via `allowedProtoProperties` and `allowedProtoMethods` by
setting the corresponding values to false.

The methods `constructor`, `__defineGetter__`, `__defineSetter__`, `__lookupGetter__`
and the property `__proto__` will be disabled, even if the allow...ByDefault-options
are set to true. In order to allow access to those properties and methods, they have
to be explicitly set to true in the 'allowedProto...'-options.

A warning is logged when the a proto-access it attempted and denied
by default (i.e. if no option is set by the user to make the access
decision explicit)
2020-01-10 16:55:45 +01:00
Nils Knappmeier 91a1b5d2f4 v4.6.0 2020-01-08 23:45:15 +01:00
Nils Knappmeier 770d746e60 Update release notes 2020-01-08 23:44:46 +01:00
Nils Knappmeier d7f0dcf2bb refactor: fix typo in private test method 2020-01-08 23:17:23 +01:00
Nils Knappmeier 187d611e8c test: add path to nodeJs when running test:bin
- this allows the test to be run in a debugger
  without the complete PATH
2020-01-08 23:17:23 +01:00
Nils Knappmeier d337f40d0e test: show diff when test:bin fails 2020-01-08 23:17:23 +01:00
Nils Knappmeier d03b6ecfc4 feat: access control to prototype properties via whitelist
Disallow access to prototype properties and methods by default.
Access to properties is always checked via
`Object.prototype.hasOwnProperty.call(parent, propertyName)`.

New runtime options:
- **allowedProtoMethods**: a string-to-boolean map of property-names that are allowed if they are methods of the parent object.
- **allowedProtoProperties**: a string-to-boolean map of property-names that are allowed if they are properties but not methods of the parent object.

```js
const template = handlebars.compile('{{aString.trim}}')
const result = template({ aString: '  abc  ' })
// result is empty, because trim is defined at String prototype
```

```js
const template = handlebars.compile('{{aString.trim}}')
const result = template({ aString: '  abc  ' }, {
  allowedProtoMethods: {
    trim: true
  }
})
// result = 'abc'
```

Implementation details: The method now "container.lookupProperty"
handles the prototype-checks and the white-lists. It is used in
- JavaScriptCompiler#nameLookup
- The "lookup"-helper (passed to all helpers as "options.lookupProperty")
- The "lookup" function at the container, which is used for recursive lookups in "compat" mode

Compatibility:
- **Old precompiled templates work with new runtimes**: The "options.lookupPropery"-function is passed to the helper by a wrapper, not by the compiled templated.
- **New templates work with old runtimes**: The template contains a function that is used as fallback if the "lookupProperty"-function cannot be found at the container. However, the runtime-options "allowedProtoProperties" and "allowedProtoMethods" only work with the newest runtime.

BREAKING CHANGE:
- access to prototype properties is forbidden completely by default
2020-01-08 23:17:23 +01:00
Nils Knappmeier 164b7ff0de chore: ignore .nyc_output 2019-12-14 18:41:06 +01:00
Nils Knappmeier ac4655ee95 chore: disable "dot-notation" rule
- I don't think it makes much sense. In some cases,
  it is more readable to wrap property access in quotes,
  some times not, but there is no universal rule
  for that.
- a promises "catch"-function should not be wrapped, but it has to
  be, if "allow-keywords" is set to false
- an "if"-helper should be wrapped, but it is not allowed to be
  if "allow-keywords" is set to true (default).
2019-12-14 18:41:06 +01:00
Nils Knappmeier 14b621caf5 test/style: remove or hide unused code in git.js, add tests 2019-12-14 18:41:06 +01:00
Nils Knappmeier 1ec1737d24 test/style: refactor remaining grunt tasks to use promises instead of callbacks 2019-12-14 18:41:06 +01:00
Nils Knappmeier 1ebce2b53c test/style: use nyc instead of istanbul, npm audit fix 2019-12-14 18:41:06 +01:00
Nils Knappmeier 3a5b65e02b test/style: refactor parser task 2019-12-14 18:41:06 +01:00
Nils Knappmeier dde108e283 test/style: refactor test-task to make it more readable 2019-12-14 18:41:06 +01:00
Nils Knappmeier dc5495216d chore: change eslint-rules for tasks/
- use es2017 rules as NodeJS supports it today
- add "prefer-const"
2019-12-14 18:41:06 +01:00
Marcos Marado d1fb07b32b Update (C) year in the LICENSE file
Welcome to 2019!
2019-12-08 16:21:38 +01:00
Nils Knappmeier 04b19848cc chore: try to fix saucelabs credentials (#1627) 2019-12-08 16:17:15 +01:00
Nils Knappmeier c40d9f33ad chore: active linting and formatting on commit 2019-12-05 08:01:33 +01:00
Nils Knappmeier 8901c28e9a chore: fix task name in build 2019-12-03 22:59:04 +01:00
Nils Knappmeier e97685e989 style: reformat all files using prettier 2019-12-03 22:37:15 +01:00
Nils Knappmeier e913dc5f12 chore: restructure build commands
- move dtslint (checkTypes) away from Gruntfile.js
  (as it disturbs debugging `grunt`)
  and call it directly as npm-script in travis-ci
- re-group task definition in Gruntfile.js
- use a multi-job travis build to
  run linting, format, dtslint and tests
  in parallel
- run only "npm test" on appveyor
- rename Grunt-tasks for be more descriptive
- SAUCE_USERNAME is not a secret variable anymore
  it can be easily guessed anyway and the
  [secure] value messes up with a lot of the
  log output

- linting on commit disable during transition
2019-12-03 22:21:30 +01:00
Nils Knappmeier 1f61f21250 chore: configure prettier and eslint
- add prettier to do formatting
- add eslint-config-prettier to
  disable rules conflicting with prettier
- remove eslint from grunt workflow
- use lint-stage to lint and format
  on precommit
- use eslint and prettier in travis directly
- remove rules that are already part of
  the "recommended" ruleset

That rational is that eslint and prettier should be run in
Travis-CI, on commit and as IDE integration (highlighting
errors directlry). They don't need to be run along with
test-cases. Getting linting errors when running the tests
because of missing semicolons is just annoying, but doesn't
help the overall code-quality.
2019-12-02 22:40:05 +01:00
Nils Knappmeier 587e7a3e63 remove yarn.lock 2019-12-02 22:40:04 +01:00
ole-martin edcc84f292 Update readme.md with updated links (#1620)
* Update readme.md with updated links

Fix http->https where possible and update links doc links

* Update README.markdown

* Fix precompilation link
2019-12-02 22:03:52 +01:00
ole-martin 23d58e79bb fix(runtime.js): partials compile not caching (#1600)
Reintroduce "merge" function, no called "mergeIfNeeded", that only creates a new partials
object if both "env.partials" and "options.partials" are set.

closes #1598
2019-11-18 21:21:03 +01:00
Nils Knappmeier c819c8b533 v4.5.3 2019-11-18 08:10:26 +01:00
Nils Knappmeier 827c9d0747 Update release notes 2019-11-18 08:09:48 +01:00
Nils Knappmeier f7f05d7558 fix: add "no-prototype-builtins" eslint-rule and fix all occurences 2019-11-18 07:33:45 +01:00
Nils Knappmeier 1988878087 fix: add more properties required to be enumerable
- __defineGetter__, __defineSetter__, __lookupGetter__, __proto__
2019-11-18 07:33:45 +01:00
Nils Knappmeier 886ba86c2f test/chore: add chai/expect and sinon to "runtime"-environment 2019-11-17 22:18:20 +01:00
Nils Knappmeier 0817dad7e7 test: add sinon as global variable to eslint in the specs 2019-11-15 17:22:29 +01:00
Nils Knappmeier 93516a0b07 test: add sinon.js for spies, deprecate current assertions
- the goal is to get overall cleaner test.
- chai and sinon are standard libraries for testing
  assertions and spies. We should not use custom ones.
2019-11-15 16:38:28 +01:00
Nils Knappmeier 93e284ed9b chore: add chai and dirty-chai for better test assertions 2019-11-15 16:38:28 +01:00
Nils Knappmeier c02b05fa81 fix: use !== 0 instead of != 0 2019-11-15 16:38:28 +01:00
Nils Knappmeier 8de121d21c v4.5.2 2019-11-13 22:07:27 +01:00
Nils Knappmeier 6914090086 Update release notes 2019-11-13 22:06:51 +01:00
Nils Knappmeier d54137810a fix: use String(field) in lookup when checking for "constructor"
closes #1603
2019-11-13 22:02:05 +01:00
Nils Knappmeier c2ac79c970 test: add fluent API for testing Handlebars
use "expectTemplate(template)....toCompileTo(output)"
2019-11-13 22:02:05 +01:00
Nils Knappmeier 7ef86173ab v4.5.1 2019-10-29 05:42:23 +01:00
Nils Knappmeier b75e3e1f40 Update release notes 2019-10-29 05:41:43 +01:00
Nils Knappmeier 5e9d17f8fa fix: move "eslint-plugin-compat" to devDependencies 2019-10-29 05:17:03 +01:00
Nils Knappmeier b24797da01 v4.5.0 2019-10-28 19:47:51 +01:00
Nils Knappmeier a243067883 Update release notes 2019-10-28 19:47:08 +01:00
Nils Knappmeier 088e61812a chore: add eslint-plugin-compat and eslint-plugin-es5
- tests are not compiled with babel and must thus be in
  es5
- we don't use polyfills, so we need to make sure no
  functions aren't used that are not supported by popular browsers. (like Object.assign in Safari and IE11)
- Boths are errors that usually only appear when running
  tests in SauceLabs, which happens only on _after_
  merging a PR.
2019-10-28 19:17:57 +01:00
Kabir Baidhya 7052e88068 Resolve deprecation warning message from eslint while running eslint (#1586)
* Resolve eslint deprecation warning

  There was a DeprecationWarning message from eslint saying that `ecmaFeatures` property has 
  been deprecated.
  Moved it under the `parserOptions` as per recommended here - 
  https://eslint.org/docs/user-guide/migrating-to-2.0.0.
* Set escmaVersion = 6
* Use ES6 built-in global variables
* Remove flags in favor of ecmaVersion
2019-10-28 18:32:49 +01:00
Kabir Baidhya b8913fcc65 Add missing types for the Exception class properties (#1583)
* Convert Exception to a class
* Add node param type declaration
* Test the types
2019-10-28 15:58:59 +01:00
Robert Jackson 62ed3c25c7 Add Handlebars.parseWithoutProcessing (#1584)
When authoring tooling that parses Handlebars files and emits Handlebars
files, you often want to preserve the **exact** formatting of the input.
The changes in this commit add a new method to the `Handlebars`
namespace: `parseWithoutProcessing`. Unlike, `Handlebars.parse` (which
will mutate the parsed AST to apply whitespace control) this method will
parse the template and return it directly (**without** processing
😉).

For example, parsing the following template:

```hbs
 {{#foo}}
   {{~bar~}} {{baz~}}
 {{/foo}}
```

Using `Handlebars.parse`, the AST returned would have truncated the
following whitespace:

* The whitespace prior to the `{{#foo}}`
* The newline following `{{#foo}}`
* The leading whitespace before `{{~bar~}}`
* The whitespace between `{{~bar~}}` and `{{baz~}}`
* The newline after `{{baz~}}`
* The whitespace prior to the `{{/foo}}`

When `Handlebars.parse` is used from  `Handlebars.precompile` or
`Handlebars.compile`, this whitespace stripping is **very** important
(these behaviors are intentional, and generally lead to better rendered
output).

When the same template is parsed with
`Handlebars.parseWithoutProcessing` none of those modifications to the
AST are made. This enables "codemod tooling" (e.g. `prettier` and
`ember-template-recast`) to preserve the **exact** initial formatting.
Prior to these changes, those tools would have to _manually_ reconstruct
the whitespace that is lost prior to emitting source.
2019-10-28 00:28:28 +01:00
kpdecker 7fcf9d24f8 Use objects for hash value tracking
The use of arrays was incorrect for the data type and causing problems when hash keys conflicted with array behaviors.

Fixes #1194

(cherry picked from commit 768ddbd661)
2019-10-27 17:27:37 +01:00
Hannah Wolfe c76ded8f0f fix: add guard to if & unless helpers (#1549)
fixes #1548

- add a guard to show readable syntax error for if / unless helper
- prevents against 3 different errors that can be generated by different systax errors
2019-10-27 15:41:35 +01:00
Nils Knappmeier a15d01d383 Merge branch '4.4.x' into 4.x 2019-10-22 00:00:18 +02:00
Nils Knappmeier 8e1cce7918 v4.4.5 2019-10-20 23:08:10 +02:00
Nils Knappmeier def79fd5d6 Update release notes 2019-10-20 23:07:22 +02:00
Nils Knappmeier fd2e5c983d fix: non-eager matching raw-block-contents
In 4.4.4 the block-contents was matched with an eager match, which means
that with multiple raw-blocks of the same kind, the block was spanned
over the first ending-tag until the last one.
This commit replaces this by a non-eager match.

closes #1579
2019-10-20 22:57:13 +02:00
Nils Knappmeier 8d5530ee2c fix: non-eager matching raw-block-contents
In 4.4.4 the block-contents was matched with an eager match, which means
that with multiple raw-blocks of the same kind, the block was spanned
over the first ending-tag until the last one.
This commit replaces this by a non-eager match.

closes #1579
2019-10-20 22:56:24 +02:00
Nils Knappmeier 2ab261eab7 v4.4.4 2019-10-20 21:33:00 +02:00
Nils Knappmeier 143ac806da Update release notes 2019-10-20 21:32:09 +02:00
Nils Knappmeier f1752fe66f fix: prevent zero length tokens in raw-blocks (#1577)
This comment ensures that the lexer is not stuck on zero-length tokens, in raw-blocks like {{{{a}}}} {{{{/a}}}}
2019-10-20 21:24:55 +02:00
Nils Knappmeier aaab6099f2 fix: prevent zero length tokens in raw-blocks (#1577)
This comment ensures that the lexer is not stuck on zero-length tokens, in raw-blocks like {{{{a}}}} {{{{/a}}}}
2019-10-20 21:23:02 +02:00
sohibe feb60f85c9 show source location for the strict lookup exceptions 2019-10-09 06:50:04 +02:00
Nils Knappmeier 0b593bfe5d chore: link to s3 bucket with https, add "npm ci" to build instructions 2019-10-08 22:19:01 +02:00
Nils Knappmeier 2e53fba68f v4.4.3 2019-10-08 22:05:35 +02:00
Nils Knappmeier ba570c42cf Update release notes 2019-10-08 22:04:57 +02:00
Alexander Schramm 0440af2147 added missing type fields in typings and tests for them 2019-10-08 19:44:06 +02:00
Nils Knappmeier b793350fec v4.4.2 2019-10-02 22:44:36 +02:00
Nils Knappmeier 26d0f7a80d Update release notes 2019-10-02 22:44:03 +02:00
Nils Knappmeier b7eada0149 chore: fix grunt-saucelabs dependency 2019-10-02 22:42:52 +02:00
Nils Knappmeier b8e769fcb6 v4.4.1 2019-10-02 21:52:34 +02:00
Nils Knappmeier 9cb31653a4 Update release notes 2019-10-02 21:51:56 +02:00
Nils Knappmeier c53f340374 chore: use @knappi/grunt-saucelabs instead of github-dependency
- mostly because installing dependencies from github takes really
  long in this case.
2019-10-02 21:46:16 +02:00
Nils Knappmeier 059b330579 v4.4.0 2019-09-29 15:29:13 +02:00
Nils Knappmeier 8f6047cdfd Update release notes 2019-09-29 15:28:36 +02:00
antelle cf7545ef5a Added support for iterable objects in {{#each}} helper (#1557)
* Added support for iterable object in {{#each}} helper
Currently {{#each}} helper supports either arrays, or objects,
however nowadays you can define custom iterable objects by overriding
a special method called Symbol.iterator, which results in empty result
being rendered.
* improved a test for iterables in {{#each}} returning empty result
* #each helper: using ES5 instead of generator functions in tests
* #each helper: using ES5 in the helper itself
2019-09-29 14:57:47 +02:00
Nils Knappmeier c958cc8955 v4.3.4 2019-09-28 13:25:05 +02:00
Nils Knappmeier b250b2d53a Update release notes 2019-09-28 13:24:18 +02:00
Nils Knappmeier ff4d827c09 fix: harden "propertyIsEnumerable"-check
- "container" is an internal object that is most likely
  not accessible through templateing (unlike the proto of "Object", which might be.)
  In order to prevent overriding this method, we
  use "propertyIsEnumerable" from the constructor.
2019-09-28 10:36:49 +02:00
Nils Knappmeier e4738491b3 v4.3.3 2019-09-27 07:46:55 +02:00
Nils Knappmeier 54f7e11b28 Update release notes 2019-09-27 07:46:12 +02:00
Nils Knappmeier 8742bde701 fix test case for browsers that do not support __defineGetter__ 2019-09-27 00:09:04 +02:00
Nils Knappmeier 2357140c68 v4.3.2 2019-09-26 23:58:48 +02:00
Nils Knappmeier c5cbeac039 Update release notes 2019-09-26 23:58:13 +02:00
Nils Knappmeier 213c0bbe3c Use Object.prototype.propertyIsEnumerable to check for constructors
- context.propertyIsEnumerable can be replaced
  via __definedGetter__
- This is a fix specific to counter a known RCE exploit.
  Other fixes will follow.

closes #1563
2019-09-26 23:55:24 +02:00
Nils Knappmeier 050cca0866 v4.3.1 2019-09-25 00:32:32 +02:00
Nils Knappmeier 2d5579078b Update release notes 2019-09-25 00:31:48 +02:00
Nils Knappmeier e3639e2407 fix saucelabs tests (internet explorer) 2019-09-25 00:18:02 +02:00
Nils Knappmeier c2a17c7b30 fix saucelabs tests (internet explorer) 2019-09-25 00:00:51 +02:00
Nils Knappmeier 1266838829 do not break on precompiled templates from Handlebars >=4.0.0 <4.3.0
- The version-range above have compiler version 7 and
  precompiled templates expecte the (block)
  HelperMissing-functions in "helpers" and not in "container.hooks".
- Handlebars now accepts precompiled templates of version 7.
- If a precompiled template with version 7 is loaded,
  the (block)HelperMissing-functions are kept in "helpers"
2019-09-24 23:45:09 +02:00
Nils Knappmeier 64ecb9ea84 add test for #1560 2019-09-24 22:28:52 +02:00
Matt Hinchliffe 93444c58db Ensure allowCallsToHelperMissing runtime option is optional in typings 2019-09-24 22:27:16 +02:00
Nils Knappmeier d148d7cb1f check "allowCallsToHelperMissing" 2019-09-24 08:37:37 +02:00
Nils Knappmeier a89081d440 v4.3.0 2019-09-24 08:04:35 +02:00
Nils Knappmeier bba65605b1 Update release notes 2019-09-24 08:03:52 +02:00
Nils Knappmeier 06b7224ed9 adjust compiler revision 2019-09-24 07:31:19 +02:00
Nils Knappmeier 2078c727c6 Disallow calling "helperMissing" and "blockHelperMissing" directly
closes #1558
2019-09-24 07:31:19 +02:00
Nils Knappmeier fff3e40402 v4.2.1 2019-09-20 19:40:48 +02:00
Nils Knappmeier 35bcd4405f Update release notes 2019-09-20 19:40:10 +02:00
Caleb Mazalevskis 00b4f2ff98 Fix some small typos. 2019-09-20 19:01:03 +02:00
Nils Knappmeier e47b5ec192 integration-tests for various webpack-scenarios
related to #1553

- registering helpers on an instance retrieved via
  `import`, compiling the template on an instance
   retrieved via `require`
- using `@roundingwellos/babel-plugin-handlebars-inline-precompile` to load plugins inline
2019-09-20 18:58:17 +02:00
Paul Falgout c55a7bed78 fix: use cjs for browser fields
We should not be using pre-built files for the `browser`.  Resolves https://github.com/wycats/handlebars.js/issues/1553
2019-09-20 18:54:42 +02:00
Nils Knappmeier 164c7ceea4 v4.2.0 2019-09-03 21:58:07 +02:00
Nils Knappmeier 6ab48d8def Update release notes 2019-09-03 21:57:30 +02:00
Nils Knappmeier 8ac20285f6 Merge pull request #1534 from AndrewLeedham/4.x
Add VM TS mapping
2019-09-03 21:45:31 +02:00
Nils Knappmeier 888750ec27 fix typings of resolvePartial-options
- derived from the object structure seen in the debugger

closes #1534
2019-09-03 21:40:21 +02:00
Andrew Leedham 133b96a2ff Add "Handlebars.VM.resolvePartial" to type definitions
- Handlebars.VM is actually not part of the API,
  but Handlebars.VM.resolvePartial is mentioned
  in the documentation and is thus now treated
  as part of the API.

Closes #1534
2019-09-03 21:33:35 +02:00
Nils Knappmeier f119497312 chore: attempt to fix saucelabs problems with custom lib
- custom "grunt-saucelabs"
- which uses custom "sauce-tunnel"
- which uses current "sauce connect proxy"
2019-08-31 23:58:21 +02:00
Nils Knappmeier 62b64ecc3d chore: add comment to integration test 2019-08-31 23:53:28 +02:00
Nils Knappmeier a57b6824e0 add webpack test 2019-08-31 21:00:14 +02:00
Nils Knappmeier a26633f204 chore: fix integration tests 2019-08-31 19:27:11 +02:00
Nils Knappmeier f9cce4dd02 chore: add framework for various integration tests 2019-08-31 13:18:47 +02:00
Nils Knappmeier 16572cd848 feat: enhance typescript definition for knownHelpers
- Add support for custom helpers while keeping
  the list of builtin-helpers to maintain for
  autocompletion support

closes #1544
2019-08-29 22:53:09 +02:00
Nils Knappmeier f98c6a5425 v4.1.2-0 2019-08-25 18:06:35 +02:00
Nils Knappmeier fde409ace6 Update release notes 2019-08-25 18:05:56 +02:00
Nils Knappmeier 9aaace76dc Merge pull request #1540 from ouijan/browser-resolution
added browser to package.json, resolves #1102
2019-08-25 17:48:26 +02:00
Toby Harris 5eb59a5302 added browser to package.json, resolves #1102 2019-08-22 10:36:13 +10:00
Nils Knappmeier 10b5fcf92e v4.1.2 2019-04-13 16:19:22 +02:00
Nils Knappmeier dd0144c771 Update release notes 2019-04-13 16:18:37 +02:00
Nils Knappmeier 594f1e30dd chore: add missing typescript dependency, add package-lock.json
I suspect that the current problems with
saucelabs are due to a change transitive
dependency, but I'm not sure. I'm not
adding the package-lock.json to ensure
that this does not happen in the future.
2019-04-13 16:04:43 +02:00
Nils Knappmeier 871acccbb1 test: remove safari from saucelabs 2019-04-13 15:55:52 +02:00
Nils Knappmeier cd38583216 fix: prevent RCE through the "lookup"-helper
- The "lookup" helper could also be used to run a remote code execution
  by manipulating the template. The same check as for regular
  path queries now also is done in the "lookup"-helper
2019-04-11 23:08:57 +02:00
Nils Knappmeier c454d946e3 Merge pull request #1515 from zimmi88/4.x-typings-lint
Port over linting and test for typings
2019-03-27 15:11:23 +01:00
Nils Knappmeier 9cfb5ddad9 Merge pull request #1516 from phil-davis/revert-double-release-notes
Revert duplicate "Update release notes"
2019-03-20 22:53:21 +01:00
Phil Davis be44246221 Remove triplicate of v4.0.12 release notes 2019-03-20 18:19:30 +05:45
Phil Davis 002561be94 Revert "Update release notes"
This reverts commit 25b2e11dd9.
2019-03-20 18:10:47 +05:45
Timothy Lindvall 3fb6687013 Port over linting and test for typings
- Move typings from lib/ to types/.
- Add dtslint for validating types.
- Use grunt-bg-shell to call out to dtslint during build step.
2019-03-19 16:07:05 -07:00
Nils Knappmeier f691db546e v4.1.1 2019-03-16 22:28:38 +01:00
Nils Knappmeier 25b2e11dd9 Update release notes 2019-03-16 22:28:03 +01:00
Nils Knappmeier e5c39375ac Update release notes 2019-03-16 22:24:34 +01:00
Nils Knappmeier aef72870b6 Merge pull request #1511 from wycats/saucelabs
Fix Saucelabs tests
2019-03-15 23:16:23 +01:00
Nils Knappmeier 684f1032c6 chore: reactivate saucelabs-tests 2019-03-15 23:01:49 +01:00
Nils Knappmeier 7840ab66a5 test: make security testcase internet explorer compatible
Internet Explorer does not support the 'class Testclass {}' notation,
and tests are not compiled using babel.

closes #1497
2019-03-15 23:01:49 +01:00
Nils Knappmeier 4108b8330b Merge pull request #1504 from liqiang372/deprecate-substr-method
deprecate substr method and use existing strip function in grammar
2019-03-14 20:23:58 +01:00
Qiang Li 445ae12fa4 deprecate substr method and use existing strip function in grammar 2019-03-13 14:24:19 -07:00
Nils Knappmeier 5cedd62d7b fix: add "runtime.d.ts" to allow "require('handlebars/runtime')"
see #1499
2019-02-22 00:30:51 +01:00
Nils Knappmeier 40fb115e53 Revert "chore: re-activate saucelabs"
This reverts commit b2e2cfe56d.
2019-02-19 10:49:24 +01:00
Nils Knappmeier b2e2cfe56d chore: re-activate saucelabs 2019-02-19 10:31:42 +01:00
Nils Knappmeier 037bfbf4d9 Merge pull request #1500 from wycats/neo-async
Use `neo-async` instead of `async
2019-02-19 09:49:49 +01:00
Nils Knappmeier 048f2ce7d2 refactor: replace "async" with "neo-async"
The main reason is that neo-async takes a lot less space due to the missing lodash-dependency.
The other is speed.

closes #1431
2019-02-18 19:26:38 +01:00
Nils Knappmeier b92589a3b0 test: add test for NodeJS compatibility
The test is a simple addition to the existing tests. It should ensure
that the built Handlebars artifact only uses language features that are
available in old versions of NodeJS. A simple program and the
precompiler are started with NodeJS 0.10 to 11
2019-02-18 19:20:39 +01:00
Nils Knappmeier 1c62d4c5d0 Merge branch 'issue-1495' into 4.x 2019-02-07 11:03:35 +01:00
Nils Knappmeier 7caca944b1 v4.1.0 2019-02-07 10:46:32 +01:00
Nils Knappmeier 7bd34fb466 Update release notes 2019-02-07 10:46:01 +01:00
Nils Knappmeier b02e9a25ee test: run appveyor tests in Node 10 2019-02-07 10:19:53 +01:00
Nils Knappmeier f1c8b2e2a2 chore: disable sauce-labs
Related to #1497
2019-02-07 10:19:53 +01:00
Nils Knappmeier dbc50ac705 chore: bump version of grunt-saucelabs 2019-02-07 10:19:53 +01:00
Nils Knappmeier c6a8fc1c04 chore: add .idea and yarn-error.log to .gitignore 2019-02-07 10:19:53 +01:00
Nils Knappmeier 42841c41a4 fix: disallow access to the constructor in templates to prevent RCE
This commit fixes a Remote Code Execution (RCE) reported by
npm-security. Access to non-enumerable "constructor"-properties
is now prohibited by the compiled template-code, because this
the first step on the way to creating and execution arbitrary
JavaScript code.
The vulnerability affects systems where an attacker is allowed to
inject templates into the Handlebars setup.
Further details of the attack may be disclosed by npm-security.

Closes #1267
Closes #1495
2019-02-07 10:19:53 +01:00
Nils Knappmeier 56fc6768d1 test: run appveyor tests in Node 10 2019-02-07 10:14:44 +01:00
Nils Knappmeier ee3022228b chore: disable sauce-labs
Related to #1497
2019-02-07 10:04:17 +01:00
Nils Knappmeier 05e6293bb3 chore: bump version of grunt-saucelabs 2019-02-07 09:53:09 +01:00
Nils Knappmeier 2db0d123c8 chore: add .idea and yarn-error.log to .gitignore 2019-02-07 08:49:52 +01:00
Nils Knappmeier edc6220d51 fix: disallow access to the constructor in templates to prevent RCE
This commit fixes a Remote Code Execution (RCE) reported by
npm-security. Access to non-enumerable "constructor"-properties
is now prohibited by the compiled template-code, because this
the first step on the way to creating and execution arbitrary
JavaScript code.
The vulnerability affects systems where an attacker is allowed to
inject templates into the Handlebars setup.
Further details of the attack may be disclosed by npm-security.

Closes #1267
Closes #1495
2019-02-07 08:49:41 +01:00
Nils Knappmeier bacd473fe6 chore: fix components/handlebars package.json and auto-update on release 2019-01-02 01:07:05 +01:00
Timothy Lindvall 27ac1ee396 Feat: Import TypeScript typings
- Import typings from DefinitelyTyped into repo.
- Update typings header to cite contributors from history and git blame.
- Update package.json to add typings field.
2018-12-21 23:27:58 +01:00
Nils Knappmeier 78dd89c13a chore: Use node 10 to build handlebars
Node 10 is LTS now...
2018-12-15 23:40:08 +01:00
Nils Knappmeier 6b87c21fc4 chore/doc: Add more release docs 2018-12-15 23:37:40 +01:00
Nils Knappmeier 8d22e6f501 v4.0.12 2018-09-04 20:44:38 +02:00
Nils Knappmeier 3c970cc9c1 Update release notes 2018-09-04 20:44:07 +02:00
Nils Knappmeier abba3c7526 Update release notes 2018-09-04 20:37:53 +02:00
Nils Knappmeier 4bf1c4ff66 Update release notes 2018-09-04 20:36:06 +02:00
Nils Knappmeier 41b6a11d11 Merge branch '4.x' of github.com:wycats/handlebars.js into 4.x 2018-09-04 20:08:57 +02:00
Nils Knappmeier 2d28f920b0 bump grunt-plugin-dependencies to 1.x versions 2018-09-04 18:53:01 +02:00
Nils Knappmeier 29b174468d style: omit linting error caused by removing "if" 2018-09-04 18:53:01 +02:00
Nils Knappmeier d130ed2bc1 chore: bump various dependencies
- grunt -> 1
- grunt-contrib-watch -> 1
- mocha -> 5
  - in common.js: define "global" , see mochajs/mocha#1159
  - in builtins.js: revert "console.log" to old value just
    after using the mock (in log-helper tests), because
    mocha calls "console.log" on failure, before
    "afterEach"
2018-09-04 18:53:01 +02:00
Nils Knappmeier 2145c14994 bump grunt-plugin-dependencies to 1.x versions 2018-09-04 00:18:46 +02:00
Nils Knappmeier 8359722e5d style: omit linting error caused by removing "if" 2018-09-04 00:16:01 +02:00
Nils Knappmeier a1d864d4a7 chore: bump various dependencies
- grunt -> 1
- grunt-contrib-watch -> 1
- mocha -> 5
  - in common.js: define "global" , see mochajs/mocha#1159
  - in builtins.js: revert "console.log" to old value just
    after using the mock (in log-helper tests), because
    mocha calls "console.log" on failure, before
    "afterEach"
2018-09-04 00:15:02 +02:00
Qiang Li 0ddff8b388 unnecessary check
(cherry picked from commit e1fa310)
2018-05-31 23:16:26 +02:00
Nils Knappmeier 288e986161 Docs: Document branches in the CONTRIBUTING guide 2018-05-31 23:15:24 +02:00
Nils Knappmeier 30df8a1ac7 Testcase for accessing @root from a partial-block
related to #1445
2018-05-31 23:12:08 +02:00
Nils Knappmeier cda544bca9 Add package.json to components shim
This is an attempt to provide a valid package.json-file to the shim
repository for bower, in order to support `bower-away`

see components/handlebars.js#24
2017-11-28 22:13:17 +01:00
aaharu 69c6ca528d Use files field 2017-11-26 02:08:20 +09:00
Nils Knappmeier a4e39bdfd0 Fix release-notes (links to contributors` pages) 2017-11-09 10:46:39 +01:00
Nils Knappmeier b86b9189fa Fix release-notes (links to github-repo) 2017-11-09 10:44:20 +01:00
tim d3d39423a3 upgrade uglify-js 2017-10-21 23:04:23 +02:00
Nils Knappmeier 73d5637564 Update dependencies "async" to 2.5.0 and "source-map" to 0.6.1 2017-10-21 16:09:33 +02:00
Nils Knappmeier 7729aa956b Update grunt-eslint to 20.1.0 2017-10-21 15:42:27 +02:00
Nils Knappmeier 8947dd077c Update jsfiddle to 4.0.11 2017-10-17 23:15:53 +02:00
182 changed files with 21754 additions and 3056 deletions
+25
View File
@@ -0,0 +1,25 @@
.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/
/integration-testing/*/dist/
# Third-party or files that must remain unchanged
/spec/expected/
/spec/vendor
# JS-Snippets
src/*.js
-200
View File
@@ -1,200 +0,0 @@
{
"globals": {
"self": false
},
"env": {
"node": true
},
"ecmaFeatures": {
// Enabling features that can be implemented without polyfills. Want to avoid polyfills at this time.
"arrowFunctions": true,
"blockBindings": true,
"defaultParams": true,
"destructuring": true,
"modules": true,
"objectLiteralComputedProperties": true,
"objectLiteralDuplicateProperties": true,
"objectLiteralShorthandMethods": true,
"objectLiteralShorthandProperties": true,
"restParams": true,
"spread": true,
"templateStrings": true
},
"rules": {
// Possible Errors //
//-----------------//
"comma-dangle": [2, "never"],
"no-cond-assign": [2, "except-parens"],
// Allow for debugging
"no-console": 1,
"no-constant-condition": 2,
"no-control-regex": 2,
// Allow for debugging
"no-debugger": 1,
"no-dupe-args": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-empty": 2,
"no-empty-character-class": 2,
"no-ex-assign": 2,
"no-extra-boolean-cast": 2,
"no-extra-parens": 0,
"no-extra-semi": 2,
"no-func-assign": 0,
// Stylistic... might consider disallowing in the future
"no-inner-declarations": 0,
"no-invalid-regexp": 2,
"no-irregular-whitespace": 2,
"no-negated-in-lhs": 2,
"no-obj-calls": 2,
"no-regex-spaces": 2,
"quote-props": [2, "as-needed", {"keywords": true}],
"no-sparse-arrays": 0,
// Optimizer and coverage will handle/highlight this and can be useful for debugging
"no-unreachable": 1,
"use-isnan": 2,
"valid-jsdoc": 0,
"valid-typeof": 2,
// Best Practices //
//----------------//
"block-scoped-var": 0,
"complexity": 0,
"consistent-return": 0,
"curly": 2,
"default-case": 1,
"dot-notation": [2, {"allowKeywords": false}],
"eqeqeq": 0,
"guard-for-in": 1,
"no-alert": 2,
"no-caller": 2,
"no-div-regex": 1,
"no-else-return": 0,
"no-empty-label": 2,
"no-eq-null": 0,
"no-eval": 2,
"no-extend-native": 2,
"no-extra-bind": 2,
"no-fallthrough": 2,
"no-floating-decimal": 2,
"no-implied-eval": 2,
"no-iterator": 2,
"no-labels": 2,
"no-lone-blocks": 2,
"no-loop-func": 2,
"no-multi-spaces": 2,
"no-multi-str": 1,
"no-native-reassign": 2,
"no-new": 2,
"no-new-func": 2,
"no-new-wrappers": 2,
"no-octal": 2,
"no-octal-escape": 2,
"no-param-reassign": 0,
"no-process-env": 2,
"no-proto": 2,
"no-redeclare": 2,
"no-return-assign": 2,
"no-script-url": 2,
"no-self-compare": 2,
"no-sequences": 2,
"no-throw-literal": 2,
"no-unused-expressions": 2,
"no-void": 0,
"no-warning-comments": 1,
"no-with": 2,
"radix": 2,
"vars-on-top": 0,
"wrap-iife": 2,
"yoda": 0,
// Strict //
//--------//
"strict": 0,
// Variables //
//-----------//
"no-catch-shadow": 2,
"no-delete-var": 2,
"no-label-var": 2,
"no-shadow": 0,
"no-shadow-restricted-names": 2,
"no-undef": 2,
"no-undef-init": 2,
"no-undefined": 0,
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}],
"no-use-before-define": [2, "nofunc"],
// Node.js //
//---------//
// Others left to environment defaults
"no-mixed-requires": 0,
// Stylistic //
//-----------//
"indent": 0,
"brace-style": [2, "1tbs", {"allowSingleLine": true}],
"camelcase": 2,
"comma-spacing": [2, {"before": false, "after": true}],
"comma-style": [2, "last"],
"consistent-this": [1, "self"],
"eol-last": 2,
"func-names": 0,
"func-style": [2, "declaration"],
"key-spacing": [2, {
"beforeColon": false,
"afterColon": true
}],
"max-nested-callbacks": 0,
"new-cap": 2,
"new-parens": 2,
"newline-after-var": 0,
"no-array-constructor": 2,
"no-continue": 0,
"no-inline-comments": 0,
"no-lonely-if": 2,
"no-mixed-spaces-and-tabs": 2,
"no-multiple-empty-lines": 0,
"no-nested-ternary": 1,
"no-new-object": 2,
"no-spaced-func": 2,
"no-ternary": 0,
"no-trailing-spaces": 2,
"no-underscore-dangle": 0,
"no-extra-parens": [2, "functions"],
"one-var": 0,
"operator-assignment": 0,
"padded-blocks": 0,
"quote-props": 0,
"quotes": [2, "single", "avoid-escape"],
"semi": 2,
"semi-spacing": [2, {"before": false, "after": true}],
"sort-vars": 0,
"space-after-keywords": [2, "always"],
"space-before-blocks": [2, "always"],
"space-before-function-paren": [2, {"anonymous": "never", "named": "never"}],
"space-in-brackets": 0,
"space-in-parens": [2, "never"],
"space-infix-ops": 2,
"space-return-throw-case": 2,
"space-unary-ops": 2,
"spaced-comment": [2, "always", {"markers": [","]}],
"wrap-regex": 1,
"no-var": 1
}
}
+66
View File
@@ -0,0 +1,66 @@
module.exports = {
extends: ['eslint:recommended', 'plugin:compat/recommended', 'prettier'],
globals: {
self: false
},
env: {
node: true,
es6: true
},
rules: {
'no-console': 'warn',
// 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',
// Variables //
//-----------//
'no-label-var': 'error',
'no-undef-init': 'error',
'no-use-before-define': ['error', 'nofunc'],
// ECMAScript 6 //
//--------------//
'no-var': 'error'
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 6,
ecmaFeatures: {}
}
};
+13 -5
View File
@@ -1,12 +1,20 @@
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
/handlebars-release.tgz
.nyc_output
# Generated files
lib/handlebars/compiler/parser.js
/coverage/
/dist/
/integration-testing/*/dist/
/spec/tmp/*
-2
View File
@@ -1,2 +0,0 @@
instrumentation:
excludes: ['**/spec/**', '**/handlebars/compiler/parser.js']
-25
View File
@@ -1,25 +0,0 @@
.DS_Store
.gitignore
.rvmrc
.eslintrc
.travis.yml
.rspec
Gemfile
Gemfile.lock
Rakefile
Gruntfile.js
*.gemspec
*.nuspec
*.log
bench/*
configurations/*
components/*
coverage/*
dist/cdnjs/*
dist/components/*
spec/*
src/*
tasks/*
tmp/*
publish/*
vendor/*
+22
View File
@@ -0,0 +1,22 @@
.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/
/integration-testing/*/dist/
# Third-party or files that must remain unchanged
/spec/expected/
/spec/vendor
+33 -21
View File
@@ -1,27 +1,39 @@
language: node_js
before_install:
- npm install -g grunt-cli
script:
- grunt --stack travis
jobs:
include:
- stage: test
name: check javascript (eslint)
node_js: lts/*
script: npm run lint
- stage: test
name: check formatting (prettier)
node_js: lts/*
script: npm run check-format
- stage: test
name: check typescript definitions (dtslint)
node_js: lts/*
script: npm run dtslint
- stage: test
name: extensive tests and publish to aws
script: npm run extensive-tests-and-publish-to-aws
env:
- S3_BUCKET_NAME=builds.handlebarsjs.com
- secure: ckyEe5dzjdFDjmZ6wIrhGm0CFBEnKq8c1dYptfgVV/Q5/nJFGzu8T0yTjouS/ERxzdT2H327/63VCxhFnLCRHrsh4rlW/rCy4XI3O/0TeMLgFPa4TXkO8359qZ4CB44TBb3NsJyQXNMYdJpPLTCVTMpuiqqkFFOr+6OeggR7ufA=
- secure: Nm4AgSfsgNB21kgKrF9Tl7qVZU8YYREhouQunFracTcZZh2NZ2XH5aHuSiXCj88B13Cr/jGbJKsZ4T3QS3wWYtz6lkyVOx3H3iI+TMtqhD9RM3a7A4O+4vVN8IioB2YjhEu0OKjwgX5gp+0uF+pLEi7Hpj6fupD3AbbL5uYcKg8=
- SAUCE_USERNAME=handlebars
- secure: 1VkLQhbsEug4ZMQ52tTOus/WLvW3Etqe7GbCzZfzsI8d2ygJPjFfzU8fNm4pVVwoTI21MaM5AQq7SVPu8DWN1YbDjJycMdY1zO3DsB9aZBxTal98fIB7ZIUce9r5z2EP6mETrsbYjZkeckzIBI0A4UVa+F2BO4KbRDXP1Db3u3I=
node_js: '10'
- stage: test
name: test with latest nodejs-lts
node_js: lts/*
script: npm run test
- stage: test
name: test with active nodejs
node_js: node
script: npm run test
cache: npm
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: '5'
env:
- PUBLISH=true
- secure: pLTzghtVll9yGKJI0AaB0uI8GypfWxLTaIB0ZL8//yN3nAEIKMhf/RRilYTsn/rKj2NUa7vt2edYILi3lttOUlCBOwTc9amiRms1W8Lwr/3IdWPeBLvLuH1zNJRm2lBAwU4LBSqaOwhGaxOQr6KHTnWudhNhgOucxpZfvfI/dFw=
- secure: yERYCf7AwL11D9uMtacly/THGV8BlzsMmrt+iQVvGA3GaY6QMmfYqf6P6cCH98sH5etd1Y+1e6YrPeMjqI6lyRllT7FptoyOdHulazQe86VQN4sc0EpqMlH088kB7gGjTut9Z+X9ViooT5XEh9WA5jXEI9pXhQJNoIHkWPuwGuY=
- node_js: '4'
cache:
directories:
- node_modules
git:
depth: 100
+54 -15
View File
@@ -10,11 +10,18 @@ Pull requests containing only failing tests demonstrating the issue are welcomed
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
should merge the branch `4.x` into the master branch regularly.
## Pull Requests
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)
@@ -25,8 +32,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`.
@@ -45,11 +52,13 @@ If you notice any problems, please report them to the GitHub issue tracker at
##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
@@ -57,31 +66,47 @@ git clone https://github.com/mustache/spec.git mustache
```
From the root directory, run the tests.
```sh
npm test
```
## Ember testing
## Linting and Formatting
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.
Handlebars uses `eslint` to enforce best-practices and `prettier` to auto-format files.
We do linting and formatting in two phases:
```sh
npm link
grunt build release
cp dist/*.js $emberRepoDir/bower_components/handlebars/
- Committed files are linted and formatted in a pre-commit hook. In this stage eslint-errors are forbidden,
while warnings are allowed.
- The travis-ci job also lints all files and checks if they are formatted correctly. In this stage, warnings
are forbidden.
cd $emberRepoDir
npm link handlebars
npm test
```
You can use the following scripts to make sure that the travis-job does not fail:
## Releasing
- **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 travis does in its build-job, excluding the "integration-test".
- **npm run integration-test** 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).
## Releasing the latest version
Before attempting the release Handlebars, please make sure that you have the following authorizations:
- Push-access to `wycats/handlebars.js`
- Publishing rights on npmjs.com for the `handlebars` package
- Publishing rights on gemfury for the `handlebars-source` package
- Push-access to the repo for legacy package managers: `components/handlebars`
- Push-access to the production-repo of the handlebars site: `handlebars-lang/handlebarsjs.com-github-pages`
_When releasing a previous version of Handlebars, please look into the CONTRIBUNG.md in the corresponding branch._
Handlebars utilizes the [release yeoman generator][generator-release] to perform most release tasks.
A full release may be completed with the following:
```
npm ci
yo release
npm publish
yo release:publish components handlebars.js dist/components/
@@ -91,9 +116,23 @@ gem build handlebars-source.gemspec
gem push handlebars-source-*.gem
```
After this point 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.
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)
When everything is OK, the **handlebars site** needs to be updated.
Go to the master branch of the repo [handlebars-lang/handlebarsjs.com-github-pages](https://github.com/handlebars-lang/handlebarsjs.com-github-pages/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).
[generator-release]: https://github.com/walmartlabs/generator-release
[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/113/
[jsfiddle]: https://jsfiddle.net/9D88g/180/
+134 -73
View File
@@ -1,44 +1,42 @@
/* eslint-disable no-process-env */
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
eslint: {
options: {
},
files: [
'*.js',
'bench/**/*.js',
'tasks/**/*.js',
'lib/**/!(*.min|parser).js',
'spec/**/!(*.amd|json2|require).js'
]
},
clean: ['tmp', 'dist', 'lib/handlebars/compiler/parser.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'}
{
expand: true,
cwd: 'components/',
src: ['**'],
dest: 'dist/components'
},
{ expand: true, cwd: 'dist/', src: ['*.js'], dest: 'dist/components' }
]
}
},
@@ -53,24 +51,28 @@ module.exports = function(grunt) {
options: {
modules: 'amd'
},
files: [{
expand: true,
cwd: 'lib/',
src: '**/!(index).js',
dest: 'dist/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/'
}]
files: [
{
cwd: 'lib/',
expand: true,
src: '**/!(index).js',
dest: 'dist/cjs/'
}
]
}
},
webpack: {
@@ -79,7 +81,12 @@ module.exports = function(grunt) {
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' }
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader:
'babel-loader?optional=runtime&loose=es6.modules&auxiliaryCommentBefore=istanbul%20ignore%20next'
}
]
},
output: {
@@ -128,15 +135,17 @@ module.exports = function(grunt) {
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: 'dist/',
expand: true,
src: ['handlebars*.js', '!*.min.js'],
dest: 'dist/',
rename: function(dest, src) {
return dest + src.replace(/\.js$/, '.min.js');
}
}
}]
]
}
},
@@ -160,32 +169,53 @@ module.exports = function(grunt) {
all: {
options: {
build: process.env.TRAVIS_JOB_ID,
urls: ['http://localhost:9999/spec/?headless=true', 'http://localhost:9999/spec/amd.html?headless=true'],
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'}
{ 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'],
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'}
]
browsers: [{ browserName: 'chrome' }]
}
}
},
bgShell: {
integrationTests: {
cmd: './integration-testing/run-integration-tests.sh',
bg: false,
fail: true
}
},
watch: {
scripts: {
options: {
@@ -193,25 +223,11 @@ module.exports = function(grunt) {
},
files: ['src/*', 'lib/**/*.js', 'spec/**/*.js'],
tasks: ['build', 'amd', 'tests', 'test']
tasks: ['on-file-change']
}
}
});
// Build a new version of the library
this.registerTask('build', 'Builds a distributable version of the current project', [
'eslint',
'parser',
'node',
'globals']);
this.registerTask('amd', ['babel:amd', 'requirejs']);
this.registerTask('node', ['babel:cjs']);
this.registerTask('globals', ['webpack']);
this.registerTask('tests', ['concat:tests']);
this.registerTask('release', 'Build final packages', ['eslint', 'amd', 'uglify', 'test:min', 'copy:dist', 'copy:components', 'copy:cdnjs']);
// Load tasks from npm
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-concat');
@@ -221,17 +237,62 @@ module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('grunt-eslint');
grunt.loadNpmTasks('grunt-saucelabs');
grunt.loadNpmTasks('grunt-bg-shell');
grunt.loadNpmTasks('@knappi/grunt-saucelabs');
grunt.loadNpmTasks('grunt-webpack');
grunt.task.loadTasks('tasks');
this.registerTask(
'build',
'Builds a distributable version of the current project',
['parser', 'node', 'globals']
);
this.registerTask('node', ['babel:cjs']);
this.registerTask('globals', ['webpack']);
this.registerTask('release', 'Build final packages', [
'amd',
'uglify',
'test:min',
'copy:dist',
'copy:components',
'copy:cdnjs'
]);
this.registerTask('amd', ['babel:amd', 'requirejs']);
this.registerTask('test', ['test:bin', 'test:cov']);
grunt.registerTask('bench', ['metrics']);
grunt.registerTask('sauce', process.env.SAUCE_USERNAME ? ['tests', 'connect', 'saucelabs-mocha'] : []);
grunt.registerTask('travis', process.env.PUBLISH ? ['default', 'sauce', 'metrics', 'publish:latest'] : ['default']);
if (process.env.SAUCE_ACCESS_KEY) {
grunt.registerTask('sauce', ['concat:tests', 'connect', 'saucelabs-mocha']);
} else {
grunt.registerTask('sauce', []);
}
// Requires secret properties (saucelabs-credentials etc.) from .travis.yaml
grunt.registerTask('extensive-tests-and-publish-to-aws', [
'default',
'bgShell:integrationTests',
'sauce',
'metrics',
'publish-to-aws'
]);
grunt.registerTask('on-file-change', [
'build',
'amd',
'concat:tests',
'test'
]);
// === Primary tasks ===
grunt.registerTask('dev', ['clean', 'connect', 'watch']);
grunt.registerTask('default', ['clean', 'build', 'test', 'release']);
grunt.registerTask('integration-tests', [
'default',
'bgShell:integrationTests'
]);
};
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (C) 2011-2017 by Yehuda Katz
Copyright (C) 2011-2019 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
+9 -9
View File
@@ -11,12 +11,12 @@ 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
[http://www.handlebarsjs.com](http://www.handlebarsjs.com) and the live demo at [http://tryhandlebarsjs.com/](http://tryhandlebarsjs.com/).
[https://handlebarsjs.com/](https://handlebarsjs.com) and the live demo at [http://tryhandlebarsjs.com/](http://tryhandlebarsjs.com/).
Installing
----------
See our [installation documentation](http://handlebarsjs.com/installation.html).
See our [installation documentation](https://handlebarsjs.com/installation/).
Usage
-----
@@ -46,23 +46,23 @@ var result = template(data);
// </ul>
```
Full documentation and more examples are at [handlebarsjs.com](http://handlebarsjs.com/).
Full documentation and more examples are at [handlebarsjs.com](https://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](http://handlebarsjs.com/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](https://handlebarsjs.com/installation/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](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)
- [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)
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.
+4 -6
View File
@@ -1,8 +1,7 @@
# Test against these versions of Node.js
environment:
matrix:
- nodejs_version: "4"
- nodejs_version: "5"
- nodejs_version: "10"
platform:
- x64
@@ -14,8 +13,7 @@ install:
# Clone submodules (mustache spec)
- cmd: git submodule update --init --recursive
# Install modules
- cmd: npm install
- cmd: npm install -g grunt-cli
- cmd: npm ci
# Post-install test scripts
@@ -24,7 +22,7 @@ test_script:
- cmd: node --version
- cmd: npm --version
# Run tests
- cmd: grunt --stack travis
- cmd: npm run test
# Don't actually build
build: off
@@ -35,4 +33,4 @@ on_failure:
# Set build version format here instead of in the admin panel
version: "{build}"
version: "{build}"
+2 -1
View File
@@ -1,4 +1,5 @@
{
"extends": "prettier",
"globals": {
"require": true
},
@@ -11,4 +12,4 @@
"handle-callback-err": 0,
"no-console": 0
}
}
}
+12 -7
View File
@@ -1,12 +1,14 @@
var async = require('async'),
fs = require('fs'),
zlib = require('zlib');
var async = require('neo-async'),
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);
@@ -32,7 +34,10 @@ 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]);
});
}
);
};
+1 -1
View File
@@ -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;
}
+9 -4
View File
@@ -1,5 +1,5 @@
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
@@ -8,12 +8,17 @@ module.exports = function(grunt, callback) {
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]);
};
+2 -1
View File
@@ -8,5 +8,6 @@ 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}}'
};
+8 -1
View File
@@ -1,5 +1,12 @@
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}}',
+8 -1
View File
@@ -1,4 +1,11 @@
module.exports = {
context: { names: [{name: 'Moe'}, {name: 'Larry'}, {name: 'Curly'}, {name: 'Shemp'}] },
context: {
names: [
{ name: 'Moe' },
{ name: 'Larry' },
{ name: 'Curly' },
{ name: 'Shemp' }
]
},
handlebars: '{{#names}}{{name}}{{/names}}'
};
+4 -4
View File
@@ -5,11 +5,11 @@ module.exports = {
header: function() {
return 'Colors';
},
hasItems: true, // To make things fairer in mustache land due to no `{{if}}` construct on arrays
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' }
]
},
+8 -1
View File
@@ -1,4 +1,11 @@
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}}{{@index}}{{name}}{{/each}}'
};
+9 -1
View File
@@ -1,5 +1,13 @@
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 %>'
+13 -3
View File
@@ -1,6 +1,16 @@
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}}',
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 %>'
eco:
'<% for item in @names: %><% for child in item.name: %><%= item.bat %><%= @foo %><% end %><% end %>'
};
+1 -1
View File
@@ -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);
+4 -1
View File
@@ -1,5 +1,8 @@
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}}' }
+10 -2
View File
@@ -1,8 +1,16 @@
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}}',
+5 -3
View File
@@ -1,7 +1,9 @@
module.exports = {
context: { person: { name: {bar: {baz: 'Larry'}}, age: 45 } },
handlebars: '{{person.name.bar.baz}}{{person.age}}{{person.foo}}{{animal.age}}',
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 %>',
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 -2
View File
@@ -1,8 +1,7 @@
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.'
};
+49 -25
View File
@@ -1,19 +1,27 @@
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');
@@ -22,21 +30,28 @@ 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;
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}));
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);
@@ -58,7 +73,9 @@ 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() {});
@@ -84,7 +101,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);
@@ -107,9 +124,16 @@ 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
);
}
}
+51 -25
View File
@@ -1,5 +1,5 @@
var _ = require('underscore'),
Benchmark = require('benchmark');
Benchmark = require('benchmark');
function BenchWarmer() {
this.benchmarks = [];
@@ -29,20 +29,25 @@ BenchWarmer.prototype = {
});
},
push: function(name, fn) {
if (this.names.indexOf(name) == -1) {
if (this.names.indexOf(name) === -1) {
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;
}
});
@@ -75,10 +80,14 @@ BenchWarmer.prototype = {
});
print('\n');
var errors = false, prop, bench;
var errors = false,
prop,
bench;
for (prop in self.errors) {
if (self.errors.hasOwnProperty(prop)
&& self.errors[prop].error.message !== 'EWOT') {
if (
Object.prototype.hasOwnProperty.call(self, prop) &&
self.errors[prop].error.message !== 'EWOT'
) {
errors = true;
break;
}
@@ -86,9 +95,8 @@ BenchWarmer.prototype = {
if (errors) {
print('\n\nErrors:\n');
for (prop in self.errors) {
if (self.errors.hasOwnProperty(prop)
&& self.errors[prop].error.message !== 'EWOT') {
Object.keys(self.errors).forEach(function(prop) {
if (self.errors[prop].error.message !== 'EWOT') {
bench = self.errors[prop];
print('\n' + bench.name + ':\n');
print(bench.error.message);
@@ -97,7 +105,7 @@ BenchWarmer.prototype = {
}
print('\n');
}
}
});
}
callback();
@@ -108,23 +116,39 @@ BenchWarmer.prototype = {
},
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;
@@ -147,7 +171,9 @@ BenchWarmer.prototype = {
},
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];
});
@@ -165,9 +191,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);
+3 -3
View File
@@ -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);
}
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
rules: {
'no-console': 0,
'no-var': 0
}
};
+159 -111
View File
@@ -1,128 +1,176 @@
#!/usr/bin/env node
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'
},
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'
}
});
'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)) {
optimist.showHelp();
printUsage(argv._spec, 120);
} 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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "handlebars",
"version": "4.0.11",
"version": "4.7.6",
"main": "handlebars.js",
"license": "MIT",
"dependencies": {}
+1 -1
View File
@@ -2,7 +2,7 @@
<package>
<metadata>
<id>handlebars.js</id>
<version>4.0.11</version>
<version>4.7.6</version>
<authors>handlebars.js Authors</authors>
<licenseUrl>https://github.com/wycats/handlebars.js/blob/master/LICENSE</licenseUrl>
<projectUrl>https://github.com/wycats/handlebars.js/</projectUrl>
+20
View File
@@ -0,0 +1,20 @@
{
"name": "handlebars",
"version": "4.7.6",
"license": "MIT",
"jspm": {
"main": "handlebars",
"shim": {
"handlebars": {
"exports": "Handlebars"
}
},
"files": [
"handlebars.js",
"handlebars.runtime.js"
],
"buildConfig": {
"minify": true
}
}
}
+28
View File
@@ -16,6 +16,34 @@ var ast = Handlebars.parse(myTemplate);
Handlebars.precompile(ast);
```
### Parsing
There are two primary APIs that are used to parse an existing template into the AST:
#### parseWithoutProcessing
`Handlebars.parseWithoutProcessing` is the primary mechanism to turn a raw template string into the Handlebars AST described in this document. No processing is done on the resulting AST which makes this ideal for codemod (for source to source transformation) tooling.
Example:
```js
let ast = Handlebars.parseWithoutProcessing(myTemplate);
```
#### parse
`Handlebars.parse` will parse the template with `parseWithoutProcessing` (see above) then it will update the AST to strip extraneous whitespace. The whitespace stripping functionality handles two distinct situations:
* Removes whitespace around dynamic statements that are on a line by themselves (aka "stand alone")
* Applies "whitespace control" characters (i.e. `~`) by truncating the `ContentStatement` `value` property appropriately (e.g. `\n\n{{~foo}}` would have a `ContentStatement` with a `value` of `''`)
`Handlebars.parse` is used internally by `Handlebars.precompile` and `Handlebars.compile`.
Example:
```js
let ast = Handlebars.parse(myTemplate);
```
### Basic
+12
View File
@@ -0,0 +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
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.
Currently, integration tests are only running on Linux, especially in travis-ci.
@@ -0,0 +1,13 @@
module.exports = {
extends: ['eslint:recommended', 'plugin:es5/no-es2015', 'prettier'],
globals: {
self: false
},
env: {
node: true
},
rules: {
'no-console': 'off',
'no-var': 'off'
}
};
@@ -0,0 +1,2 @@
target
package-lock.json
@@ -0,0 +1,16 @@
{
"name": "multi-nodejs-test",
"version": "1.0.0",
"description": "Simple integration test with all relevant NodeJS-versions.",
"keywords": [],
"author": "Nils Knappmeier",
"private": true,
"license": "MIT",
"dependencies": {
"handlebars": "file:../.."
},
"scripts": {
"test": "node run-handlebars.js",
"test-precompile": "handlebars precompile-test-template.txt.hbs"
}
}
@@ -0,0 +1 @@
Author: {{author}}
+11
View File
@@ -0,0 +1,11 @@
// This test should run successfully with node 0.10++ as long as Handlebars has been compiled before
var assert = require('assert');
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' });
assert.strictEqual(output, 'Author: Yehuda');
console.log('Success');
+29
View File
@@ -0,0 +1,29 @@
#!/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 framwork to make this part independent of the Node version.
unset npm_config_prefix
echo "Handlebars should be able to run in various versions of NodeJS"
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 "$i"
nvm exec "$i" npm install
nvm exec "$i" npm run test
nvm exec "$i" npm run test-precompile
echo Success
done
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
set -e
cd "$( dirname "$( readlink -f "$0" )" )"
for i in */test.sh ; do
(
echo "----------------------------------------"
echo "-- Running integration test: $i"
echo "----------------------------------------"
cd "$( dirname "$i" )"
./test.sh
)
done
@@ -0,0 +1,11 @@
{
"plugins": [
"@roundingwellos/babel-plugin-handlebars-inline-precompile"
// "istanbul"
],
"presets": [
[
"@babel/preset-env"
]
]
}
@@ -0,0 +1,3 @@
node_modules
dist
package-lock.json
@@ -0,0 +1,24 @@
{
"name": "webpack-babel-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.5.5",
"@babel/preset-env": "^7.5.5",
"@roundingwellos/babel-plugin-handlebars-inline-precompile": "^3.0.1",
"babel-loader": "^8.0.6",
"babel-plugin-istanbul": "^5.2.0",
"handlebars": "file:../..",
"handlebars-loader": "^1.7.1",
"nyc": "^14.1.1",
"webpack": "^4.39.3",
"webpack-cli": "^3.3.7"
},
"scripts": {
"build": "webpack --config webpack.config.js"
}
}
@@ -0,0 +1,12 @@
import * as Handlebars from 'handlebars/runtime';
import hbs from 'handlebars-inline-precompile';
import { assertEquals } from '../../webpack-test/src/lib/assert';
Handlebars.registerHelper('loud', function(text) {
return text.toUpperCase();
});
const template = hbs`{{loud name}}`;
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}"`);
}
}
+16
View File
@@ -0,0 +1,16 @@
#!/bin/bash
set -e
# Cleanup: package-lock and "npm ci" is not working with local dependencies
rm dist package-lock.json -rf
npm install
npm run build
for i in dist/*-test.js ; do
echo "----------------------"
echo "-- Running $i"
echo "----------------------"
node "$i"
echo "Success"
done
@@ -0,0 +1,32 @@
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: /\.js?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: { cacheDirectory: false }
}
}
]
},
optimization: {
minimize: false
}
};
@@ -0,0 +1,3 @@
node_modules
dist
package-lock.json
@@ -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"
}
}
@@ -0,0 +1,6 @@
import Handlebars from 'handlebars/dist/handlebars';
import { assertEquals } from './lib/assert';
const template = Handlebars.compile('Author: {{author}}');
assertEquals(template({ author: 'Yehuda' }), 'Author: Yehuda');
@@ -0,0 +1,5 @@
import Handlebars from 'handlebars';
import { assertEquals } from './lib/assert';
const template = Handlebars.compile('Author: {{author}}');
assertEquals(template({ author: 'Yehuda' }), 'Author: Yehuda');
@@ -0,0 +1,10 @@
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'
);
@@ -0,0 +1,10 @@
import * as HandlebarsViaImport from 'handlebars';
const HandlebarsViaRequire = require('handlebars');
import { assertEquals } from './lib/assert';
HandlebarsViaImport.registerHelper('loud', function(text) {
return text.toUpperCase();
});
const template = HandlebarsViaRequire.compile('Author: {{loud author}}');
assertEquals(template({ author: 'Yehuda' }), 'Author: YEHUDA');
@@ -0,0 +1,6 @@
import * as Handlebars from 'handlebars/dist/handlebars';
import { assertEquals } from './lib/assert';
const template = Handlebars.compile('Author: {{author}}');
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}"`);
}
}
@@ -0,0 +1,2 @@
Author: {{author}}
+16
View File
@@ -0,0 +1,16 @@
#!/bin/bash
set -e
# Cleanup: package-lock and "npm ci" is not working with local dependencies
rm dist package-lock.json -rf
npm install
npm run build
for i in dist/*-test.js ; do
echo "----------------------"
echo "-- Running $i"
echo "----------------------"
node "$i"
echo "Success"
done
@@ -0,0 +1,20 @@
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' }]
}
};
+6 -1
View File
@@ -2,7 +2,11 @@ import runtime from './handlebars.runtime';
// Compiler imports
import AST from './handlebars/compiler/ast';
import { parser as Parser, parse } 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';
@@ -25,6 +29,7 @@ function create() {
hb.JavaScriptCompiler = JavaScriptCompiler;
hb.Parser = Parser;
hb.parse = parse;
hb.parseWithoutProcessing = parseWithoutProcessing;
return hb;
}
+26 -10
View File
@@ -1,11 +1,13 @@
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.0.11';
export const COMPILER_REVISION = 7;
export const VERSION = '4.7.6';
export const COMPILER_REVISION = 8;
export const LAST_COMPATIBLE_COMPILER_REVISION = 7;
export const REVISION_CHANGES = {
1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
@@ -14,7 +16,8 @@ export const REVISION_CHANGES = {
4: '== 1.x.x',
5: '== 2.0.0-alpha.x',
6: '>= 2.0.0-beta.1',
7: '>= 4.0.0'
7: '>= 4.0.0 <4.3.0',
8: '>= 4.3.0'
};
const objectType = '[object Object]';
@@ -36,7 +39,9 @@ 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;
@@ -51,7 +56,9 @@ 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;
}
@@ -62,7 +69,9 @@ 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;
@@ -70,9 +79,16 @@ 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 };
+10 -6
View File
@@ -5,24 +5,28 @@ 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;
+14 -4
View File
@@ -8,9 +8,11 @@ export { parser };
let yy = {};
extend(yy, Helpers);
export function parse(input, options) {
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;
@@ -19,6 +21,14 @@ export function parse(input, options) {
return new yy.SourceLocation(options && options.srcName, locInfo);
};
let strip = new WhitespaceControl(options);
return strip.accept(parser.parse(input));
let ast = parser.parse(input);
return ast;
}
export function parse(input, options) {
let ast = parseWithoutProcessing(input, options);
let strip = new WhitespaceControl(options);
return strip.accept(ast);
}
+26 -23
View File
@@ -1,5 +1,5 @@
/* global define */
import {isArray} from '../utils';
import { isArray } from '../utils';
let SourceNode;
@@ -38,7 +38,7 @@ if (!SourceNode) {
this.src = chunks + this.src;
},
toStringWithSourceMap: function() {
return {code: this.toString()};
return { code: this.toString() };
},
toString: function() {
return this.src;
@@ -46,7 +46,6 @@ if (!SourceNode) {
};
}
function castChunk(chunk, codeGen, loc) {
if (isArray(chunk)) {
let ret = [];
@@ -62,7 +61,6 @@ function castChunk(chunk, codeGen, loc) {
return chunk;
}
function CodeGen(srcFile) {
this.srcFile = srcFile;
this.source = [];
@@ -94,17 +92,22 @@ 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) {
@@ -113,26 +116,28 @@ 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) {
let pairs = [];
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
let value = castChunk(obj[key], this);
if (value !== 'undefined') {
pairs.push([this.quotedString(key), ':', value]);
}
Object.keys(obj).forEach(key => {
let value = castChunk(obj[key], this);
if (value !== 'undefined') {
pairs.push([this.quotedString(key), ':', value]);
}
}
});
let ret = this.generateList(pairs);
ret.prepend('{');
@@ -140,7 +145,6 @@ CodeGen.prototype = {
return ret;
},
generateList: function(entries) {
let ret = this.empty();
@@ -165,4 +169,3 @@ CodeGen.prototype = {
};
export default CodeGen;
+97 -62
View File
@@ -1,7 +1,7 @@
/* eslint-disable new-cap */
import Exception from '../exception';
import {isArray, indexOf, extend} from '../utils';
import { isArray, indexOf, extend } from '../utils';
import AST from './ast';
const slice = [].slice;
@@ -24,8 +24,11 @@ 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;
}
}
@@ -54,34 +57,28 @@ Compiler.prototype = {
options.blockParams = options.blockParams || [];
// These changes will propagate to the other compiler components
let knownHelpers = options.knownHelpers;
options.knownHelpers = {
'helperMissing': true,
'blockHelperMissing': true,
'each': true,
'if': true,
'unless': true,
'with': true,
'log': true,
'lookup': true
};
if (knownHelpers) {
for (let name in knownHelpers) {
/* istanbul ignore else */
if (name in knownHelpers) {
this.options.knownHelpers[name] = knownHelpers[name];
}
}
}
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;
@@ -107,7 +104,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]);
}
@@ -124,7 +121,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);
@@ -159,7 +156,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);
@@ -175,17 +172,20 @@ 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);
}
@@ -218,7 +218,6 @@ Compiler.prototype = {
this.DecoratorBlock(decorator);
},
ContentStatement: function(content) {
if (content.value) {
this.opcode('appendContent', content.value);
@@ -241,8 +240,8 @@ 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', path.depth);
@@ -264,19 +263,27 @@ 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)
);
}
},
@@ -285,8 +292,8 @@ Compiler.prototype = {
this.opcode('getContext', path.depth);
let name = path.parts[0],
scoped = AST.helpers.scopedId(path),
blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
scoped = AST.helpers.scopedId(path),
blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
if (blockParamId) {
this.opcode('lookupBlockParam', blockParamId, path.parts);
@@ -297,7 +304,13 @@ Compiler.prototype = {
this.options.data = true;
this.opcode('lookupData', path.depth, path.parts, path.strict);
} else {
this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
this.opcode(
'lookupOnContext',
path.parts,
path.falsy,
path.strict,
scoped
);
}
},
@@ -323,8 +336,8 @@ Compiler.prototype = {
Hash: function(hash) {
let pairs = hash.pairs,
i = 0,
l = pairs.length;
i = 0,
l = pairs.length;
this.opcode('pushHash');
@@ -339,7 +352,11 @@ 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) {
@@ -368,8 +385,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) {
@@ -397,9 +413,7 @@ Compiler.prototype = {
if (this.stringParams) {
if (value.replace) {
value = value
.replace(/^(\.?\.\/)*/g, '')
.replace(/\//g, '.');
value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
}
if (val.depth) {
@@ -417,7 +431,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('.');
@@ -426,9 +440,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);
@@ -455,9 +469,13 @@ 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];
}
@@ -466,8 +484,14 @@ 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 || {};
@@ -479,13 +503,19 @@ 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);
@@ -500,8 +530,13 @@ 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);
}
+30 -23
View File
@@ -4,9 +4,12 @@ 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
);
}
}
@@ -24,7 +27,7 @@ export function SourceLocation(source, locInfo) {
export function id(token) {
if (/^\[.*\]$/.test(token)) {
return token.substr(1, token.length - 2);
return token.substring(1, token.length - 1);
} else {
return token;
}
@@ -38,31 +41,28 @@ 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,
depthString = '';
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++;
depthString += '../';
}
} else {
dig.push(part);
@@ -82,9 +82,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,21 +120,30 @@ 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) {
@@ -168,7 +177,7 @@ export function prepareBlock(openBlock, program, inverseAndProgram, close, inver
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) {
@@ -194,7 +203,6 @@ export function prepareProgram(statements, loc) {
};
}
export function preparePartialBlock(open, program, close, locInfo) {
validateClose(open, close);
@@ -209,4 +217,3 @@ export function preparePartialBlock(open, program, close, locInfo) {
loc: this.locInfo(locInfo)
};
}
+250 -100
View File
@@ -1,6 +1,6 @@
import { COMPILER_REVISION, REVISION_CHANGES } from '../base';
import Exception from '../exception';
import {isArray} from '../utils';
import { isArray } from '../utils';
import CodeGen from './code-gen';
function Literal(value) {
@@ -12,12 +12,8 @@ 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*/) {
if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
return [parent, '.', name];
} else {
return [parent, '[', JSON.stringify(name), ']'];
}
nameLookup: function(parent, name /*, type */) {
return this.internalNameLookup(parent, name);
},
depthedLookup: function(name) {
return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
@@ -25,7 +21,7 @@ JavaScriptCompiler.prototype = {
compilerInfo: function() {
const revision = COMPILER_REVISION,
versions = REVISION_CHANGES[revision];
versions = REVISION_CHANGES[revision];
return [revision, versions];
},
@@ -53,6 +49,12 @@ 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;
@@ -82,14 +84,18 @@ 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];
@@ -111,13 +117,28 @@ JavaScriptCompiler.prototype = {
if (!this.decorators.isEmpty()) {
this.useDecorators = true;
this.decorators.prepend('var decorators = container.decorators;\n');
this.decorators.prepend([
'var decorators = container.decorators, ',
this.lookupPropertyFunctionVarDeclaration(),
';\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();
}
@@ -133,11 +154,11 @@ JavaScriptCompiler.prototype = {
};
if (this.decorators) {
ret.main_d = this.decorators; // eslint-disable-line camelcase
ret.main_d = this.decorators; // eslint-disable-line camelcase
ret.useDecorators = true;
}
let {programs, decorators} = this.context;
let { programs, decorators } = this.context;
for (i = 0, l = programs.length; i < l; i++) {
if (programs[i]) {
ret[i] = programs[i];
@@ -167,11 +188,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();
@@ -209,13 +230,16 @@ JavaScriptCompiler.prototype = {
// aliases will not be used, but this case is already being run on the client and
// we aren't concern about minimizing the template size.
let aliasCount = 0;
for (let alias in this.aliases) { // eslint-disable-line guard-for-in
Object.keys(this.aliases).forEach(alias => {
let node = this.aliases[alias];
if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
varDeclarations += ', alias' + (++aliasCount) + '=' + alias;
if (node.children && node.referenceCount > 1) {
varDeclarations += ', alias' + ++aliasCount + '=' + alias;
node.children[0] = 'alias' + aliasCount;
}
});
if (this.lookupPropertyFunctionIsUsed) {
varDeclarations += ', ' + this.lookupPropertyFunctionVarDeclaration();
}
let params = ['container', 'depth0', 'helpers', 'partials', 'data'];
@@ -235,18 +259,23 @@ 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(' + ');
@@ -272,7 +301,6 @@ JavaScriptCompiler.prototype = {
}
});
if (appendOnly) {
if (bufferStart) {
bufferStart.prepend('return ');
@@ -281,7 +309,8 @@ JavaScriptCompiler.prototype = {
this.source.push('return "";');
}
} else {
varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
varDeclarations +=
', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
if (bufferStart) {
bufferStart.prepend('return buffer + ');
@@ -292,12 +321,25 @@ 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
@@ -308,8 +350,10 @@ JavaScriptCompiler.prototype = {
// replace it on the stack with the result of properly
// invoking blockHelperMissing.
blockValue: function(name) {
let blockHelperMissing = this.aliasable('helpers.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();
@@ -326,8 +370,10 @@ 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('helpers.blockHelperMissing'),
params = [this.contextName(0)];
let blockHelperMissing = this.aliasable(
'container.hooks.blockHelperMissing'
),
params = [this.contextName(0)];
this.setupHelperArgs('', 0, params, true);
this.flushInline();
@@ -336,9 +382,14 @@ 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]
@@ -368,14 +419,24 @@ 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),
' }'
]);
}
}
},
@@ -387,8 +448,14 @@ 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]
@@ -472,7 +539,7 @@ JavaScriptCompiler.prototype = {
let len = parts.length;
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.
@@ -495,7 +562,14 @@ 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]
@@ -535,7 +609,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;
@@ -599,11 +673,16 @@ 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);
this.decorators.push([
'fn = ',
this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]),
this.decorators.functionCall(foundDecorator, '', [
'fn',
'props',
'container',
options
]),
' || fn;'
]);
},
@@ -619,18 +698,43 @@ 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),
simple = isSimple ? [helper.name, ' || '] : '';
helper = this.setupHelper(paramSize, name);
let lookup = ['('].concat(simple, nonHelper);
if (!this.options.strict) {
lookup.push(' || ', this.aliasable('helpers.helperMissing'));
let possibleFunctionCalls = [];
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')
);
}
lookup.push(')');
this.push(this.source.functionCall(lookup, 'call', helper.callParams));
let functionLookupCode = [
'(',
this.itemsSeparatedBy(possibleFunctionCalls, '||'),
')'
];
let functionCall = this.source.functionCall(
functionLookupCode,
'call',
helper.callParams
);
this.push(functionCall);
},
itemsSeparatedBy: function(items, separator) {
let result = [];
result.push(items[0]);
for (let i = 1; i < items.length; i++) {
result.push(separator, items[i]);
}
return result;
},
// [invokeKnownHelper]
//
// On stack, before: hash, inverse, program, params..., ...
@@ -663,22 +767,31 @@ 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('helpers.helperMissing')
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))'
]);
},
@@ -691,7 +804,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();
@@ -728,9 +841,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();
@@ -756,8 +869,13 @@ 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') {
@@ -772,20 +890,27 @@ 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];
compiler = new this.compiler(); // eslint-disable-line new-cap
compiler = new this.compiler(); // eslint-disable-line new-cap
let existing = this.matchExistingProgram(child);
if (existing == null) {
this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
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;
@@ -813,7 +938,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');
@@ -848,7 +973,11 @@ 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;
}
@@ -859,9 +988,9 @@ JavaScriptCompiler.prototype = {
replaceStack: function(callback) {
let prefix = ['('],
stack,
createdStack,
usedLiteral;
stack,
createdStack,
usedLiteral;
/* istanbul ignore next */
if (!this.isInline()) {
@@ -898,7 +1027,9 @@ 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() {
@@ -925,9 +1056,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) {
@@ -942,8 +1073,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) {
@@ -985,9 +1116,13 @@ 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,
@@ -999,11 +1134,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 = [];
@@ -1021,7 +1156,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)`
@@ -1069,6 +1204,7 @@ JavaScriptCompiler.prototype = {
setupHelperArgs: function(helper, paramSize, params, useRegister) {
let options = this.setupParams(helper, paramSize, params);
options.loc = JSON.stringify(this.source.currentLocation);
options = this.objectLiteral(options);
if (useRegister) {
this.useRegister('options');
@@ -1083,7 +1219,6 @@ JavaScriptCompiler.prototype = {
}
};
(function() {
const reservedWords = (
'break else new var' +
@@ -1104,21 +1239,27 @@ 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, type) {
let stack = compiler.popStack(),
i = 0,
len = parts.length;
i = 0,
len = parts.length;
if (requireTerminal) {
len--;
}
@@ -1128,7 +1269,16 @@ function strictLookup(requireTerminal, compiler, parts, type) {
}
if (requireTerminal) {
return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
return [
compiler.aliasable('container.strict'),
'(',
stack,
', ',
compiler.quotedString(parts[i]),
', ',
JSON.stringify(compiler.source.currentLocation),
' )'
];
} else {
return stack;
}
+19 -12
View File
@@ -24,13 +24,14 @@ 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);
@@ -52,11 +53,14 @@ 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) {
@@ -66,12 +70,16 @@ PrintVisitor.prototype.DecoratorBlock = function(block) {
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--;
@@ -115,8 +123,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]));
@@ -134,7 +142,6 @@ PrintVisitor.prototype.PathExpression = function(id) {
return (id.data ? '@' : '') + 'PATH:' + path;
};
PrintVisitor.prototype.StringLiteral = function(string) {
return '"' + string.value + '"';
};
@@ -157,7 +164,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]));
+8 -1
View File
@@ -15,7 +15,14 @@ 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;
}
+48 -30
View File
@@ -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,9 +112,11 @@ WhitespaceControl.prototype.PartialBlockStatement = function(block) {
}
// 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);
}
@@ -125,13 +127,15 @@ WhitespaceControl.prototype.PartialBlockStatement = function(block) {
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 {
@@ -141,7 +145,6 @@ WhitespaceControl.prototype.PartialStatement =
};
};
function isPrevWhitespace(body, i, isRoot) {
if (i === undefined) {
i = body.length;
@@ -150,13 +153,15 @@ 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) {
@@ -165,13 +170,15 @@ 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
);
}
}
@@ -184,12 +191,19 @@ 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;
}
@@ -202,13 +216,17 @@ 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 preceeded by a non-content node.
// 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;
}
-1
View File
@@ -3,4 +3,3 @@ import registerInline from './decorators/inline';
export function registerDefaultDecorators(instance) {
registerInline(instance);
}
+1 -1
View File
@@ -1,4 +1,4 @@
import {extend} from '../utils';
import { extend } from '../utils';
export default function(instance) {
instance.registerDecorator('inline', function(fn, props, container, options) {
+23 -4
View File
@@ -1,13 +1,26 @@
const errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
const errorProps = [
'description',
'fileName',
'lineNumber',
'endLineNumber',
'message',
'name',
'number',
'stack'
];
function Exception(message, node) {
let loc = node && node.loc,
line,
column;
line,
endLineNumber,
column,
endColumn;
if (loc) {
line = loc.start.line;
endLineNumber = loc.end.line;
column = loc.start.column;
endColumn = loc.end.column;
message += ' - ' + line + ':' + column;
}
@@ -27,6 +40,7 @@ function Exception(message, node) {
try {
if (loc) {
this.lineNumber = line;
this.endLineNumber = endLineNumber;
// Work around issue under safari where we can't directly set the column value
/* istanbul ignore next */
@@ -35,8 +49,13 @@ function Exception(message, node) {
value: column,
enumerable: true
});
Object.defineProperty(this, 'endColumn', {
value: endColumn,
enumerable: true
});
} else {
this.column = column;
this.endColumn = endColumn;
}
}
} catch (nop) {
+9
View File
@@ -15,3 +15,12 @@ export function registerDefaultHelpers(instance) {
registerLookup(instance);
registerWith(instance);
}
export function moveHelperToHooks(instance, helperName, keepHelper) {
if (instance.helpers[helperName]) {
instance.hooks[helperName] = instance.helpers[helperName];
if (!keepHelper) {
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,8 +22,11 @@ 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);
+45 -23
View File
@@ -1,4 +1,10 @@
import {appendContextPath, blockParams, createFrame, isArray, isFunction} from '../utils';
import {
appendContextPath,
blockParams,
createFrame,
isArray,
isFunction
} from '../utils';
import Exception from '../exception';
export default function(instance) {
@@ -8,17 +14,20 @@ 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);
@@ -36,10 +45,15 @@ 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') {
@@ -49,21 +63,29 @@ export default function(instance) {
execIteration(i, i, i === context.length - 1);
}
}
} else if (global.Symbol && context[global.Symbol.iterator]) {
const newContext = [];
const iterator = context[global.Symbol.iterator]();
for (let it = iterator.next(); !it.done; it = iterator.next()) {
newContext.push(it.value);
}
context = newContext;
for (let j = context.length; i < j; i++) {
execIteration(i, i, i === context.length - 1);
}
} else {
let priorKey;
for (let key in context) {
if (context.hasOwnProperty(key)) {
// We're running the iterations one step out of sync so we can detect
// the last iteration without have to scan the object twice and create
// an itermediate keys array.
if (priorKey !== undefined) {
execIteration(priorKey, i - 1);
}
priorKey = key;
i++;
Object.keys(context).forEach(key => {
// We're running the iterations one step out of sync so we can detect
// the last iteration without have to scan the object twice and create
// an itermediate keys array.
if (priorKey !== undefined) {
execIteration(priorKey, i - 1);
}
}
priorKey = key;
i++;
});
if (priorKey !== undefined) {
execIteration(priorKey, i - 1, true);
}
+3 -1
View File
@@ -7,7 +7,9 @@ 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 + '"'
);
}
});
}
+16 -3
View File
@@ -1,8 +1,14 @@
import {isEmpty, isFunction} from '../utils';
import { isEmpty, isFunction } from '../utils';
import Exception from '../exception';
export default function(instance) {
instance.registerHelper('if', function(conditional, options) {
if (isFunction(conditional)) { conditional = conditional.call(this); }
if (arguments.length != 2) {
throw new Exception('#if requires exactly one argument');
}
if (isFunction(conditional)) {
conditional = conditional.call(this);
}
// Default behavior is to render the positive path if the value is truthy and not empty.
// The `includeZero` option may be set to treat the condtional as purely not empty based on the
@@ -15,6 +21,13 @@ export default function(instance) {
});
instance.registerHelper('unless', function(conditional, options) {
return instance.helpers['if'].call(this, conditional, {fn: options.inverse, inverse: options.fn, hash: options.hash});
if (arguments.length != 2) {
throw new Exception('#unless requires exactly one argument');
}
return instance.helpers['if'].call(this, conditional, {
fn: options.inverse,
inverse: options.fn,
hash: options.hash
});
});
}
+2 -2
View File
@@ -1,7 +1,7 @@
export default function(instance) {
instance.registerHelper('log', function(/* message, options */) {
let args = [undefined],
options = arguments[arguments.length - 1];
options = arguments[arguments.length - 1];
for (let i = 0; i < arguments.length - 1; i++) {
args.push(arguments[i]);
}
@@ -14,6 +14,6 @@ export default function(instance) {
}
args[0] = level;
instance.log(... args);
instance.log(...args);
});
}
+6 -2
View File
@@ -1,5 +1,9 @@
export default function(instance) {
instance.registerHelper('lookup', function(obj, field) {
return obj && obj[field];
instance.registerHelper('lookup', function(obj, field, options) {
if (!obj) {
// Note for 5.0: Change to "obj == null" in 5.0
return obj;
}
return options.lookupProperty(obj, field);
});
}
+18 -3
View File
@@ -1,8 +1,20 @@
import {appendContextPath, blockParams, createFrame, isEmpty, isFunction} from '../utils';
import {
appendContextPath,
blockParams,
createFrame,
isEmpty,
isFunction
} from '../utils';
import Exception from '../exception';
export default function(instance) {
instance.registerHelper('with', function(context, options) {
if (isFunction(context)) { context = context.call(this); }
if (arguments.length != 2) {
throw new Exception('#with requires exactly one argument');
}
if (isFunction(context)) {
context = context.call(this);
}
let fn = options.fn;
@@ -10,7 +22,10 @@ export default function(instance) {
let data = options.data;
if (options.data && options.ids) {
data = createFrame(options.data);
data.contextPath = appendContextPath(options.data.contextPath, options.ids[0]);
data.contextPath = appendContextPath(
options.data.contextPath,
options.ids[0]
);
}
return fn(context, {
@@ -0,0 +1,11 @@
import { extend } from '../utils';
/**
* Create a new object with "null"-prototype to avoid truthy results on prototype properties.
* The resulting object can be used with "object[property]" to check if a property exists
* @param {...object} sources a varargs parameter of source objects that will be merged
* @returns {object}
*/
export function createNewLookupObject(...sources) {
return extend(Object.create(null), ...sources);
}
+70
View File
@@ -0,0 +1,70 @@
import { createNewLookupObject } from './create-new-lookup-object';
import * as logger from '../logger';
const loggedProperties = Object.create(null);
export function createProtoAccessControl(runtimeOptions) {
let defaultMethodWhiteList = Object.create(null);
defaultMethodWhiteList['constructor'] = false;
defaultMethodWhiteList['__defineGetter__'] = false;
defaultMethodWhiteList['__defineSetter__'] = false;
defaultMethodWhiteList['__lookupGetter__'] = false;
let defaultPropertyWhiteList = Object.create(null);
// eslint-disable-next-line no-proto
defaultPropertyWhiteList['__proto__'] = false;
return {
properties: {
whitelist: createNewLookupObject(
defaultPropertyWhiteList,
runtimeOptions.allowedProtoProperties
),
defaultValue: runtimeOptions.allowProtoPropertiesByDefault
},
methods: {
whitelist: createNewLookupObject(
defaultMethodWhiteList,
runtimeOptions.allowedProtoMethods
),
defaultValue: runtimeOptions.allowProtoMethodsByDefault
}
};
}
export function resultIsAllowed(result, protoAccessControl, propertyName) {
if (typeof result === 'function') {
return checkWhiteList(protoAccessControl.methods, propertyName);
} else {
return checkWhiteList(protoAccessControl.properties, propertyName);
}
}
function checkWhiteList(protoAccessControlForType, propertyName) {
if (protoAccessControlForType.whitelist[propertyName] !== undefined) {
return protoAccessControlForType.whitelist[propertyName] === true;
}
if (protoAccessControlForType.defaultValue !== undefined) {
return protoAccessControlForType.defaultValue;
}
logUnexpecedPropertyAccessOnce(propertyName);
return false;
}
function logUnexpecedPropertyAccessOnce(propertyName) {
if (loggedProperties[propertyName] !== true) {
loggedProperties[propertyName] = true;
logger.log(
'error',
`Handlebars: Access has been denied to resolve the property "${propertyName}" because it is not an "own property" of its parent.\n` +
`You can add a runtime option to disable the check or this warning:\n` +
`See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details`
);
}
}
export function resetLoggedProperties() {
Object.keys(loggedProperties).forEach(propertyName => {
delete loggedProperties[propertyName];
});
}
+13
View File
@@ -0,0 +1,13 @@
export function wrapHelper(helper, transformOptionsFn) {
if (typeof helper !== 'function') {
// This should not happen, but apparently it does in https://github.com/wycats/handlebars.js/issues/1639
// We try to make the wrapper least-invasive by not wrapping it, if the helper is not a function.
return helper;
}
let wrapper = function(/* dynamic arguments */) {
const options = arguments[arguments.length - 1];
arguments[arguments.length - 1] = transformOptionsFn(options);
return helper.apply(this, arguments);
};
return wrapper;
}
+8 -4
View File
@@ -1,4 +1,4 @@
import {indexOf} from './utils';
import { indexOf } from './utils';
let logger = {
methodMap: ['debug', 'info', 'warn', 'error'],
@@ -22,12 +22,16 @@ let logger = {
log: function(level, ...message) {
level = logger.lookupLevel(level);
if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
if (
typeof console !== 'undefined' &&
logger.lookupLevel(logger.level) <= level
) {
let method = logger.methodMap[level];
if (!console[method]) { // eslint-disable-line no-console
// eslint-disable-next-line no-console
if (!console[method]) {
method = 'log';
}
console[method](...message); // eslint-disable-line no-console
console[method](...message); // eslint-disable-line no-console
}
}
};
+1 -2
View File
@@ -1,8 +1,7 @@
/* global window */
export default function(Handlebars) {
/* istanbul ignore next */
let root = typeof global !== 'undefined' ? global : window,
$Handlebars = root.Handlebars;
$Handlebars = root.Handlebars;
/* istanbul ignore next */
Handlebars.noConflict = function() {
if (root.Handlebars === Handlebars) {
+218 -49
View File
@@ -1,22 +1,48 @@
import * as Utils from './utils';
import Exception from './exception';
import { COMPILER_REVISION, REVISION_CHANGES, createFrame } from './base';
import {
COMPILER_REVISION,
createFrame,
LAST_COMPATIBLE_COMPILER_REVISION,
REVISION_CHANGES
} from './base';
import { moveHelperToHooks } from './helpers';
import { wrapHelper } from './internal/wrapHelper';
import {
createProtoAccessControl,
resultIsAllowed
} from './internal/proto-access';
export function checkRevision(compilerInfo) {
const compilerRevision = compilerInfo && compilerInfo[0] || 1,
currentRevision = COMPILER_REVISION;
const compilerRevision = (compilerInfo && compilerInfo[0]) || 1,
currentRevision = COMPILER_REVISION;
if (compilerRevision !== currentRevision) {
if (compilerRevision < currentRevision) {
const runtimeVersions = REVISION_CHANGES[currentRevision],
compilerVersions = REVISION_CHANGES[compilerRevision];
throw new Exception('Template was precompiled with an older version of Handlebars than the current runtime. ' +
'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').');
} else {
// Use the embedded version info since the runtime doesn't know about this revision yet
throw new Exception('Template was precompiled with a newer version of Handlebars than the current runtime. ' +
'Please update your runtime to a newer version (' + compilerInfo[1] + ').');
}
if (
compilerRevision >= LAST_COMPATIBLE_COMPILER_REVISION &&
compilerRevision <= COMPILER_REVISION
) {
return;
}
if (compilerRevision < LAST_COMPATIBLE_COMPILER_REVISION) {
const runtimeVersions = REVISION_CHANGES[currentRevision],
compilerVersions = REVISION_CHANGES[compilerRevision];
throw new Exception(
'Template was precompiled with an older version of Handlebars than the current runtime. ' +
'Please update your precompiler to a newer version (' +
runtimeVersions +
') or downgrade your runtime to an older version (' +
compilerVersions +
').'
);
} else {
// Use the embedded version info since the runtime doesn't know about this revision yet
throw new Exception(
'Template was precompiled with a newer version of Handlebars than the current runtime. ' +
'Please update your runtime to a newer version (' +
compilerInfo[1] +
').'
);
}
}
@@ -32,9 +58,13 @@ export function template(templateSpec, env) {
templateSpec.main.decorator = templateSpec.main_d;
// Note: Using env.VM references rather than local var references throughout this section to allow
// for external users to override these as psuedo-supported APIs.
// for external users to override these as pseudo-supported APIs.
env.VM.checkRevision(templateSpec.compiler);
// backwards compatibility for precompiled templates with compiler-version 7 (<4.3.0)
const templateWasPrecompiledWithCompilerV7 =
templateSpec.compiler && templateSpec.compiler[0] === 7;
function invokePartialWrapper(partial, context, options) {
if (options.hash) {
context = Utils.extend({}, context, options.hash);
@@ -42,13 +72,27 @@ export function template(templateSpec, env) {
options.ids[0] = true;
}
}
partial = env.VM.resolvePartial.call(this, partial, context, options);
let result = env.VM.invokePartial.call(this, partial, context, options);
let extendedOptions = Utils.extend({}, options, {
hooks: this.hooks,
protoAccessControl: this.protoAccessControl
});
let result = env.VM.invokePartial.call(
this,
partial,
context,
extendedOptions
);
if (result == null && env.compile) {
options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
result = options.partials[options.name](context, options);
options.partials[options.name] = env.compile(
partial,
templateSpec.compilerOptions,
env
);
result = options.partials[options.name](context, extendedOptions);
}
if (result != null) {
if (options.indent) {
@@ -64,22 +108,43 @@ export function template(templateSpec, env) {
}
return result;
} else {
throw new Exception('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
throw new Exception(
'The partial ' +
options.name +
' could not be compiled when running in runtime-only mode'
);
}
}
// Just add water
let container = {
strict: function(obj, name) {
if (!(name in obj)) {
throw new Exception('"' + name + '" not defined in ' + obj);
strict: function(obj, name, loc) {
if (!obj || !(name in obj)) {
throw new Exception('"' + name + '" not defined in ' + obj, {
loc: loc
});
}
return obj[name];
},
lookupProperty: function(parent, propertyName) {
let result = parent[propertyName];
if (result == null) {
return result;
}
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
return result;
}
if (resultIsAllowed(result, container.protoAccessControl, propertyName)) {
return result;
}
return undefined;
},
lookup: function(depths, name) {
const len = depths.length;
for (let i = 0; i < len; i++) {
if (depths[i] && depths[i][name] != null) {
let result = depths[i] && container.lookupProperty(depths[i], name);
if (result != null) {
return depths[i][name];
}
}
@@ -100,9 +165,17 @@ export function template(templateSpec, env) {
programs: [],
program: function(i, data, declaredBlockParams, blockParams, depths) {
let programWrapper = this.programs[i],
fn = this.fn(i);
fn = this.fn(i);
if (data || depths || blockParams || declaredBlockParams) {
programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
programWrapper = wrapProgram(
this,
i,
fn,
data,
declaredBlockParams,
blockParams,
depths
);
} else if (!programWrapper) {
programWrapper = this.programs[i] = wrapProgram(this, i, fn);
}
@@ -115,10 +188,10 @@ export function template(templateSpec, env) {
}
return value;
},
merge: function(param, common) {
mergeIfNeeded: function(param, common) {
let obj = param || common;
if (param && common && (param !== common)) {
if (param && common && param !== common) {
obj = Utils.extend({}, common, param);
}
@@ -139,37 +212,81 @@ export function template(templateSpec, env) {
data = initData(context, data);
}
let depths,
blockParams = templateSpec.useBlockParams ? [] : undefined;
blockParams = templateSpec.useBlockParams ? [] : undefined;
if (templateSpec.useDepths) {
if (options.depths) {
depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
depths =
context != options.depths[0]
? [context].concat(options.depths)
: options.depths;
} else {
depths = [context];
}
}
function main(context/*, options*/) {
return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
function main(context /*, options*/) {
return (
'' +
templateSpec.main(
container,
context,
container.helpers,
container.partials,
data,
blockParams,
depths
)
);
}
main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
main = executeDecorators(
templateSpec.main,
main,
container,
options.depths || [],
data,
blockParams
);
return main(context, options);
}
ret.isTop = true;
ret._setup = function(options) {
if (!options.partial) {
container.helpers = container.merge(options.helpers, env.helpers);
let mergedHelpers = Utils.extend({}, env.helpers, options.helpers);
wrapHelpersToPassLookupProperty(mergedHelpers, container);
container.helpers = mergedHelpers;
if (templateSpec.usePartial) {
container.partials = container.merge(options.partials, env.partials);
// Use mergeIfNeeded here to prevent compiling global partials multiple times
container.partials = container.mergeIfNeeded(
options.partials,
env.partials
);
}
if (templateSpec.usePartial || templateSpec.useDecorators) {
container.decorators = container.merge(options.decorators, env.decorators);
container.decorators = Utils.extend(
{},
env.decorators,
options.decorators
);
}
container.hooks = {};
container.protoAccessControl = createProtoAccessControl(options);
let keepHelperInHelpers =
options.allowCallsToHelperMissing ||
templateWasPrecompiledWithCompilerV7;
moveHelperToHooks(container, 'helperMissing', keepHelperInHelpers);
moveHelperToHooks(container, 'blockHelperMissing', keepHelperInHelpers);
} else {
container.protoAccessControl = options.protoAccessControl; // internal option
container.helpers = options.helpers;
container.partials = options.partials;
container.decorators = options.decorators;
container.hooks = options.hooks;
}
};
@@ -181,24 +298,47 @@ export function template(templateSpec, env) {
throw new Exception('must pass parent depths');
}
return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
return wrapProgram(
container,
i,
templateSpec[i],
data,
0,
blockParams,
depths
);
};
return ret;
}
export function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
export function wrapProgram(
container,
i,
fn,
data,
declaredBlockParams,
blockParams,
depths
) {
function prog(context, options = {}) {
let currentDepths = depths;
if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
if (
depths &&
context != depths[0] &&
!(context === container.nullContext && depths[0] === null)
) {
currentDepths = [context].concat(depths);
}
return fn(container,
context,
container.helpers, container.partials,
options.data || data,
blockParams && [options.blockParams].concat(blockParams),
currentDepths);
return fn(
container,
context,
container.helpers,
container.partials,
options.data || data,
blockParams && [options.blockParams].concat(blockParams),
currentDepths
);
}
prog = executeDecorators(fn, prog, container, depths, data, blockParams);
@@ -209,6 +349,9 @@ export function wrapProgram(container, i, fn, data, declaredBlockParams, blockPa
return prog;
}
/**
* This is currently part of the official API, therefore implementation details should not be changed.
*/
export function resolvePartial(partial, context, options) {
if (!partial) {
if (options.name === '@partial-block') {
@@ -237,8 +380,10 @@ export function invokePartial(partial, context, options) {
options.data = createFrame(options.data);
// Wrapper function to get access to currentPartialBlock from the closure
let fn = options.fn;
partialBlock = options.data['partial-block'] = function partialBlockWrapper(context, options = {}) {
partialBlock = options.data['partial-block'] = function partialBlockWrapper(
context,
options = {}
) {
// Restore the partial-block from the closure for the execution of the block
// i.e. the part inside the block of the partial call.
options.data = createFrame(options.data);
@@ -261,7 +406,9 @@ export function invokePartial(partial, context, options) {
}
}
export function noop() { return ''; }
export function noop() {
return '';
}
function initData(context, data) {
if (!data || !('root' in data)) {
@@ -274,8 +421,30 @@ function initData(context, data) {
function executeDecorators(fn, prog, container, depths, data, blockParams) {
if (fn.decorator) {
let props = {};
prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
prog = fn.decorator(
prog,
props,
container,
depths && depths[0],
data,
blockParams,
depths
);
Utils.extend(prog, props);
}
return prog;
}
function wrapHelpersToPassLookupProperty(mergedHelpers, container) {
Object.keys(mergedHelpers).forEach(helperName => {
let helper = mergedHelpers[helperName];
mergedHelpers[helperName] = passLookupPropertyOption(helper, container);
});
}
function passLookupPropertyOption(helper, container) {
const lookupProperty = container.lookupProperty;
return wrapHelper(helper, options => {
return Utils.extend({ lookupProperty }, options);
});
}
+17 -9
View File
@@ -9,13 +9,13 @@ const escape = {
};
const badChars = /[&<>"'`=]/g,
possible = /[&<>"'`=]/;
possible = /[&<>"'`=]/;
function escapeChar(chr) {
return escape[chr];
}
export function extend(obj/* , ...source */) {
export function extend(obj /* , ...source */) {
for (let i = 1; i < arguments.length; i++) {
for (let key in arguments[i]) {
if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
@@ -39,16 +39,23 @@ let isFunction = function(value) {
/* istanbul ignore next */
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value === 'function' && toString.call(value) === '[object Function]';
return (
typeof value === 'function' &&
toString.call(value) === '[object Function]'
);
};
}
export {isFunction};
export { isFunction };
/* eslint-enable func-style */
/* istanbul ignore next */
export const isArray = Array.isArray || function(value) {
return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false;
};
export const isArray =
Array.isArray ||
function(value) {
return value && typeof value === 'object'
? toString.call(value) === '[object Array]'
: false;
};
// Older IE versions do not directly support indexOf so we must implement our own, sadly.
export function indexOf(array, value) {
@@ -60,7 +67,6 @@ export function indexOf(array, value) {
return -1;
}
export function escapeExpression(string) {
if (typeof string !== 'string') {
// don't escape SafeStrings, since they're already safe
@@ -78,7 +84,9 @@ export function escapeExpression(string) {
string = '' + string;
}
if (!possible.test(string)) { return string; }
if (!possible.test(string)) {
return string;
}
return string.replace(badChars, escapeChar);
}
+122 -79
View File
@@ -1,10 +1,9 @@
/* eslint-disable no-console */
import Async from 'async';
import Async from 'neo-async';
import fs from 'fs';
import * as Handlebars from './handlebars';
import {basename} from 'path';
import {SourceMapConsumer, SourceNode} from 'source-map';
import { basename } from 'path';
import { SourceMapConsumer, SourceNode } from 'source-map';
module.exports.loadTemplates = function(opts, callback) {
loadStrings(opts, function(err, strings) {
@@ -25,14 +24,19 @@ module.exports.loadTemplates = function(opts, callback) {
function loadStrings(opts, callback) {
let strings = arrayCast(opts.string),
names = arrayCast(opts.name);
names = arrayCast(opts.name);
if (names.length !== strings.length
&& strings.length > 1) {
return callback(new Handlebars.Exception('Number of names did not match the number of string inputs'));
if (names.length !== strings.length && strings.length > 1) {
return callback(
new Handlebars.Exception(
'Number of names did not match the number of string inputs'
)
);
}
Async.map(strings, function(string, callback) {
Async.map(
strings,
function(string, callback) {
if (string !== '-') {
callback(undefined, string);
} else {
@@ -55,80 +59,94 @@ function loadStrings(opts, callback) {
source: string
}));
callback(err, strings);
});
}
);
}
function loadFiles(opts, callback) {
// Build file extension pattern
let extension = (opts.extension || 'handlebars').replace(/[\\^$*+?.():=!|{}\-\[\]]/g, function(arg) { return '\\' + arg; });
let extension = (opts.extension || 'handlebars').replace(
/[\\^$*+?.():=!|{}\-[\]]/g,
function(arg) {
return '\\' + arg;
}
);
extension = new RegExp('\\.' + extension + '$');
let ret = [],
queue = (opts.files || []).map((template) => ({template, root: opts.root}));
Async.whilst(() => queue.length, function(callback) {
let {template: path, root} = queue.shift();
queue = (opts.files || []).map(template => ({ template, root: opts.root }));
Async.whilst(
() => queue.length,
function(callback) {
let { template: path, root } = queue.shift();
fs.stat(path, function(err, stat) {
if (err) {
return callback(new Handlebars.Exception(`Unable to open template file "${path}"`));
}
fs.stat(path, function(err, stat) {
if (err) {
return callback(
new Handlebars.Exception(`Unable to open template file "${path}"`)
);
}
if (stat.isDirectory()) {
opts.hasDirectory = true;
if (stat.isDirectory()) {
opts.hasDirectory = true;
fs.readdir(path, function(err, children) {
/* istanbul ignore next : Race condition that being too lazy to test */
if (err) {
return callback(err);
}
children.forEach(function(file) {
let childPath = path + '/' + file;
if (extension.test(childPath) || fs.statSync(childPath).isDirectory()) {
queue.push({template: childPath, root: root || path});
fs.readdir(path, function(err, children) {
/* istanbul ignore next : Race condition that being too lazy to test */
if (err) {
return callback(err);
}
});
children.forEach(function(file) {
let childPath = path + '/' + file;
callback();
});
if (
extension.test(childPath) ||
fs.statSync(childPath).isDirectory()
) {
queue.push({ template: childPath, root: root || path });
}
});
callback();
});
} else {
fs.readFile(path, 'utf8', function(err, data) {
/* istanbul ignore next : Race condition that being too lazy to test */
if (err) {
return callback(err);
}
if (opts.bom && data.indexOf('\uFEFF') === 0) {
data = data.substring(1);
}
// Clean the template name
let name = path;
if (!root) {
name = basename(name);
} else if (name.indexOf(root) === 0) {
name = name.substring(root.length + 1);
}
name = name.replace(extension, '');
ret.push({
path: path,
name: name,
source: data
});
callback();
});
}
});
},
function(err) {
if (err) {
callback(err);
} else {
fs.readFile(path, 'utf8', function(err, data) {
/* istanbul ignore next : Race condition that being too lazy to test */
if (err) {
return callback(err);
}
if (opts.bom && data.indexOf('\uFEFF') === 0) {
data = data.substring(1);
}
// Clean the template name
let name = path;
if (!root) {
name = basename(name);
} else if (name.indexOf(root) === 0) {
name = name.substring(root.length + 1);
}
name = name.replace(extension, '');
ret.push({
path: path,
name: name,
source: data
});
callback();
});
callback(undefined, ret);
}
});
},
function(err) {
if (err) {
callback(err);
} else {
callback(undefined, ret);
}
});
);
}
module.exports.cli = function(opts) {
@@ -138,7 +156,9 @@ module.exports.cli = function(opts) {
}
if (!opts.templates.length && !opts.hasDirectory) {
throw new Handlebars.Exception('Must define at least one template or directory.');
throw new Handlebars.Exception(
'Must define at least one template or directory.'
);
}
if (opts.simple && opts.min) {
@@ -147,12 +167,18 @@ module.exports.cli = function(opts) {
const multiple = opts.templates.length !== 1 || opts.hasDirectory;
if (opts.simple && multiple) {
throw new Handlebars.Exception('Unable to output multiple templates in simple mode');
throw new Handlebars.Exception(
'Unable to output multiple templates in simple mode'
);
}
// Force simple mode if we have only one template and it's unnamed.
if (!opts.amd && !opts.commonjs && opts.templates.length === 1
&& !opts.templates[0].name) {
if (
!opts.amd &&
!opts.commonjs &&
opts.templates.length === 1 &&
!opts.templates[0].name
) {
opts.simple = true;
}
@@ -172,7 +198,11 @@ module.exports.cli = function(opts) {
let output = new SourceNode();
if (!opts.simple) {
if (opts.amd) {
output.add('define([\'' + opts.handlebarPath + 'handlebars.runtime\'], function(Handlebars) {\n Handlebars = Handlebars["default"];');
output.add(
"define(['" +
opts.handlebarPath +
'handlebars.runtime\'], function(Handlebars) {\n Handlebars = Handlebars["default"];'
);
} else if (opts.commonjs) {
output.add('var Handlebars = require("' + opts.commonjs + '");');
} else {
@@ -206,7 +236,10 @@ module.exports.cli = function(opts) {
// If we are generating a source map, we have to reconstruct the SourceNode object
if (opts.map) {
let consumer = new SourceMapConsumer(precompiled.map);
precompiled = SourceNode.fromStringWithSourceMap(precompiled.code, consumer);
precompiled = SourceNode.fromStringWithSourceMap(
precompiled.code,
consumer
);
}
if (opts.simple) {
@@ -219,7 +252,14 @@ module.exports.cli = function(opts) {
if (opts.amd && !multiple) {
output.add('return ');
}
output.add([objectName, '[\'', template.name, '\'] = template(', precompiled, ');\n']);
output.add([
objectName,
"['",
template.name,
"'] = template(",
precompiled,
');\n'
]);
}
});
@@ -286,12 +326,15 @@ function minify(output, sourceMapFile) {
throw e;
}
// it does not exist!
console.error('Code minimization is disabled due to missing uglify-js dependency');
console.error(
'Code minimization is disabled due to missing uglify-js dependency'
);
return output;
}
return require('uglify-js').minify(output.code, {
fromString: true,
outSourceMap: sourceMapFile,
inSourceMap: JSON.parse(output.map)
sourceMap: {
content: output.map,
url: sourceMapFile
}
});
}
+9
View File
@@ -0,0 +1,9 @@
module.exports = {
'check-coverage': true,
branches: 100,
lines: 100,
functions: 100,
statements: 100,
exclude: ['**/spec/**', '**/handlebars/compiler/parser.js'],
reporter: 'html'
};
+11486
View File
File diff suppressed because it is too large Load Diff
+75 -19
View File
@@ -1,7 +1,7 @@
{
"name": "handlebars",
"barename": "handlebars",
"version": "4.0.11",
"version": "4.7.6",
"description": "Handlebars provides the power necessary to let you build semantic templates effectively with no frustration",
"homepage": "http://www.handlebarsjs.com/",
"keywords": [
@@ -21,49 +21,78 @@
"node": ">=0.4.7"
},
"dependencies": {
"async": "^1.4.0",
"optimist": "^0.6.1",
"source-map": "^0.4.4"
"minimist": "^1.2.5",
"neo-async": "^2.6.0",
"source-map": "^0.6.1",
"wordwrap": "^1.0.0"
},
"optionalDependencies": {
"uglify-js": "^2.6"
"uglify-js": "^3.1.4"
},
"devDependencies": {
"@knappi/grunt-saucelabs": "^9.0.2",
"aws-sdk": "^2.1.49",
"babel-loader": "^5.0.0",
"babel-runtime": "^5.1.10",
"benchmark": "~1.0",
"chai": "^4.2.0",
"chai-diff": "^1.0.1",
"concurrently": "^5.0.0",
"dirty-chai": "^2.0.1",
"dtslint": "^0.5.5",
"dustjs-linkedin": "^2.0.2",
"eco": "~1.1.0-rc-3",
"grunt": "~0.4.1",
"eslint": "^6.7.2",
"eslint-config-prettier": "^6.7.0",
"eslint-plugin-compat": "^3.3.0",
"eslint-plugin-es5": "^1.4.1",
"fs-extra": "^8.1.0",
"grunt": "^1.0.4",
"grunt-babel": "^5.0.0",
"grunt-cli": "~0.1.10",
"grunt-contrib-clean": "0.x",
"grunt-contrib-concat": "0.x",
"grunt-contrib-connect": "0.x",
"grunt-contrib-copy": "0.x",
"grunt-contrib-requirejs": "0.x",
"grunt-contrib-uglify": "0.x",
"grunt-contrib-watch": "0.x",
"grunt-eslint": "^17.1.0",
"grunt-saucelabs": "8.x",
"grunt-bg-shell": "^2.3.3",
"grunt-cli": "^1",
"grunt-contrib-clean": "^1",
"grunt-contrib-concat": "^1",
"grunt-contrib-connect": "^1",
"grunt-contrib-copy": "^1",
"grunt-contrib-requirejs": "^1",
"grunt-contrib-uglify": "^1",
"grunt-contrib-watch": "^1.1.0",
"grunt-webpack": "^1.0.8",
"istanbul": "^0.3.0",
"husky": "^3.1.0",
"jison": "~0.3.0",
"mocha": "~1.20.0",
"lint-staged": "^9.5.0",
"mocha": "^5",
"mock-stdin": "^0.3.0",
"mustache": "^2.1.3",
"nyc": "^14.1.1",
"prettier": "^1.19.1",
"semver": "^5.0.1",
"sinon": "^7.5.0",
"typescript": "^3.4.3",
"underscore": "^1.5.1",
"webpack": "^1.12.6",
"webpack-dev-server": "^1.12.1"
},
"main": "lib/index.js",
"types": "types/index.d.ts",
"browser": {
".": "./dist/cjs/handlebars.js",
"./runtime": "./dist/cjs/handlebars.runtime.js"
},
"bin": {
"handlebars": "bin/handlebars"
},
"scripts": {
"test": "grunt"
"format": "prettier --write '**/*.js' && eslint --fix .",
"check-format": "prettier --check '**/*.js'",
"lint": "eslint --max-warnings 0 .",
"dtslint": "dtslint types",
"test": "grunt",
"extensive-tests-and-publish-to-aws": "npx mocha tasks/task-tests/ && grunt --stack extensive-tests-and-publish-to-aws",
"integration-test": "grunt integration-tests",
"--- combined tasks ---": "",
"check-before-pull-request": "concurrently --kill-others-on-fail npm:lint npm:dtslint npm:check-format npm:test"
},
"jspm": {
"main": "handlebars",
@@ -73,5 +102,32 @@
"buildConfig": {
"minify": true
}
},
"files": [
"bin",
"dist/*.js",
"dist/amd/**/*.js",
"dist/cjs/**/*.js",
"lib",
"print-script",
"release-notes.md",
"runtime.js",
"types/*.d.ts",
"runtime.d.ts"
],
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,css,json,md}": [
"prettier --write",
"git add"
],
"*.js": [
"eslint --fix",
"git add"
]
}
}
+5
View File
@@ -0,0 +1,5 @@
module.exports = {
tabWidth: 2,
semi: true,
singleQuote: true
};
+682 -147
View File
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More