mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-13 03:10:40 -07:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8d5487a43 | ||
|
|
6f8224d286 | ||
|
|
7274c8bd0a | ||
|
|
047b110939 | ||
|
|
bba5c43c09 | ||
|
|
85321c6d64 | ||
|
|
d32da49925 | ||
|
|
071c4a3619 | ||
|
|
5d0d884938 | ||
|
|
33e455282d | ||
|
|
78915d1a2e | ||
|
|
6e8af35dd5 | ||
|
|
12fa904ebd | ||
|
|
bc207a66b7 | ||
|
|
90ab891c29 | ||
|
|
812af67022 | ||
|
|
aa58a45021 | ||
|
|
cbc317508b | ||
|
|
e01d30f33b | ||
|
|
04354ce36f | ||
|
|
072f63c2c0 | ||
|
|
3c385f74ec | ||
|
|
1be994194d | ||
|
|
6bdf65a6a1 | ||
|
|
61ed163821 | ||
|
|
f0b6cd375c | ||
|
|
9481008f2b | ||
|
|
cc4a9ce0a7 | ||
|
|
5e3928654b | ||
|
|
962e5b6433 | ||
|
|
7ab49f999a | ||
|
|
552819a84b | ||
|
|
8bfb6428ae | ||
|
|
568bd5f9cb | ||
|
|
ed489865b6 | ||
|
|
afec88b04c | ||
|
|
3a0d80d1f4 | ||
|
|
956b51ea95 | ||
|
|
5c3522f339 | ||
|
|
6d00257e15 | ||
|
|
03a30e6dc4 | ||
|
|
4775227358 |
@@ -838,6 +838,15 @@
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "spokodev",
|
||||
"name": "spokodev",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/239690017?v=4",
|
||||
"profile": "https://github.com/spokodev",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
}
|
||||
],
|
||||
"contributorsPerLine": 7,
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
description: Architecture overview for liquidjs internals
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
## Async/sync duality via generators
|
||||
|
||||
All core logic is written once as a `Generator` function (`function *`). Use `yield` where you'd normally `await` a potentially async value.
|
||||
|
||||
- `toPromise(generator)` drives it **asynchronously** — awaits yielded promises.
|
||||
- `toValueSync(generator)` drives it **synchronously** — passes yielded values through as-is.
|
||||
|
||||
Never duplicate logic into separate async and sync methods. A single generator serves both paths.
|
||||
|
||||
When wrapping an async+sync function pair (e.g. `contains`/`containsSync`, `exists`/`existsSync`, `readFile`/`readFileSync`), use `toLiquidAsync(asyncFn, syncFn?)` which returns a `LiquidAsync<F>` — one function that picks the sync or async implementation based on a leading `sync: boolean` arg. Then `yield` the result inside a generator to let the driver handle it in both modes.
|
||||
|
||||
See `src/util/async.ts`.
|
||||
@@ -1,6 +0,0 @@
|
||||
---
|
||||
description: Project conventions for liquidjs
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
- Keep edits minimal: change only what the task requires, match existing style.
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
description: Testing conventions — e2e uses built dist, integration uses src
|
||||
globs: test/**/*.ts
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Testing
|
||||
|
||||
## End-to-end tests (`test/e2e`)
|
||||
|
||||
- **Use the built package**, not TypeScript sources under `src/`.
|
||||
- Import the public API from the package root (for example `import { Liquid } from '../..'`), which resolves through `package.json` to **`dist/`** (`main`, `module`, etc.).
|
||||
- **Avoid** `import … from '../../src/liquid'` (or other `src/` paths) in `test/e2e/**` so e2e matches what consumers get from npm and you do not depend on an unbuilt tree.
|
||||
|
||||
## Integration and unit tests
|
||||
|
||||
- Tests under `test/integration/`, `src/**/*.spec.ts`, and similar may import from **`src/`** when the suite is meant to run against the current TypeScript sources (typical for this repo’s Jest setup).
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: 'latest'
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Build
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version: 'latest'
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Test
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: 'latest'
|
||||
- name: Build
|
||||
run: |
|
||||
npm ci
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: 'latest'
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Lint
|
||||
|
||||
@@ -17,7 +17,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: 'latest'
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
|
||||
@@ -24,12 +24,7 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ ${{ github.ref == 'refs/heads/master' }} ]; then
|
||||
npx semantic-release
|
||||
else
|
||||
npx semantic-release --dry-run
|
||||
fi
|
||||
run: npx semantic-release
|
||||
- name: Archive npm failure logs
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
|
||||
@@ -7,20 +7,10 @@ jobs:
|
||||
matrix:
|
||||
os: [ubuntu-latest]
|
||||
timezone: [Etc/GMT, Asia/Shanghai, America/New_York]
|
||||
node-version: [22]
|
||||
node-version: [latest]
|
||||
include:
|
||||
- os: macos-latest
|
||||
timezone: America/New_York
|
||||
node-versoin: 22
|
||||
- os: ubuntu-latest
|
||||
timezone: Etc/GMT
|
||||
node-version: 20
|
||||
- os: ubuntu-latest
|
||||
timezone: Asia/Shanghai
|
||||
node-version: 18
|
||||
- os: ubuntu-latest
|
||||
timezone: Asia/Shanghai
|
||||
node-version: 16
|
||||
node-version: lts/*
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -39,7 +29,7 @@ jobs:
|
||||
name: dist-${{ matrix.os }}
|
||||
path: dist
|
||||
- name: Run Test
|
||||
run: TZ=${{ matrix.timezone }} npm test
|
||||
run: TZ=${{ matrix.timezone || 'Etc/GMT' }} npm test
|
||||
- name: Archive npm failure logs
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
@@ -57,7 +47,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: latest
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
|
||||
@@ -11,9 +11,11 @@ coverage/
|
||||
node_modules/
|
||||
|
||||
# tmp
|
||||
.local/
|
||||
docs/themes/navy/source/js/liquid.browser.min.js
|
||||
docs/themes/navy/layout/partial/all-contributors.swig
|
||||
docs/themes/navy/layout/partial/financial-contributors.swig
|
||||
docs/themes/navy/layout/partial/used-by.swig
|
||||
dist/
|
||||
demo/*/yarn.json
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
const gitPlugin = [
|
||||
'@semantic-release/git',
|
||||
{
|
||||
assets: ['package.json', 'package-lock.json', 'CHANGELOG.md'],
|
||||
message: 'chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}'
|
||||
}
|
||||
]
|
||||
|
||||
const githubPlugin = [
|
||||
'@semantic-release/github',
|
||||
{
|
||||
assets: [
|
||||
{ path: 'dist/*.umd.js', label: 'liquid.js' },
|
||||
{ path: 'dist/*.min.js', label: 'liquid.min.js' },
|
||||
{ path: 'dist/*.min.js.map', label: 'liquid.min.js.map' }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
// next is branch-protected (PR-only); skip @semantic-release/git there and publish to npm only.
|
||||
const onMaster = process.env.GITHUB_REF === 'refs/heads/master'
|
||||
const onNext = process.env.GITHUB_REF === 'refs/heads/next'
|
||||
|
||||
// On next, breaking changes are v11 WIP — bump alpha prerelease only, not major.
|
||||
const commitAnalyzer = onNext
|
||||
? ['@semantic-release/commit-analyzer', {
|
||||
releaseRules: [
|
||||
{ breaking: true, release: 'patch' }
|
||||
]
|
||||
}]
|
||||
: '@semantic-release/commit-analyzer'
|
||||
|
||||
const basePlugins = [
|
||||
commitAnalyzer,
|
||||
'@semantic-release/release-notes-generator',
|
||||
'@semantic-release/changelog',
|
||||
'@semantic-release/npm'
|
||||
]
|
||||
|
||||
module.exports = {
|
||||
branches: [
|
||||
'master',
|
||||
{ name: 'next', prerelease: 'alpha' }
|
||||
],
|
||||
plugins: [
|
||||
...basePlugins,
|
||||
...(onMaster ? [gitPlugin] : []),
|
||||
githubPlugin
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
# LiquidJS
|
||||
|
||||
A simple, expressive, extensible Liquid template engine for JavaScript — Shopify, Jekyll and GitHub Pages compatible, for Node.js, browsers, and the CLI, with TypeScript support. TypeScript in `src/`, bundles in `dist/`. Docs site in `docs/` (Hexo, `navy` theme).
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | Contents |
|
||||
| --- | --- |
|
||||
| `src/parser`, `src/render`, `src/tags`, `src/filters` | Template parse and render |
|
||||
| `src/context`, `src/template`, `src/tokens` | Scope, templates, token stream |
|
||||
| `src/util/async.ts` | `toPromise`, `toValueSync`, `toLiquidAsync` |
|
||||
| `test/` | Jest |
|
||||
| `docs/source/` | Doc markdown; sidebar in `docs/source/_data/sidebar.yml` |
|
||||
| `docs/themes/navy/` | Layout, CSS, JS |
|
||||
| `.local/` | Scratch, repro, PoC (gitignored) |
|
||||
|
||||
## Commands
|
||||
|
||||
```
|
||||
npm run build # after src/ changes, before npm test
|
||||
npm test
|
||||
npm run lint
|
||||
npm run check # build + build:docs + test + lint + perf:diff (manual)
|
||||
npm run build:docs
|
||||
cd docs && npm start # http://localhost:4000
|
||||
npm run perf:diff
|
||||
```
|
||||
|
||||
PR CI (`pull_request`): build, lint, test, coverage, performance. Docs build runs on push to `master` only.
|
||||
|
||||
PR titles: conventional format (`feat:`, `fix:`, `docs:`, …) — checked by CI. Releases on `master` use semantic-release from merged commits.
|
||||
|
||||
Backward-compatible API changes expected unless doing an intentional major break.
|
||||
|
||||
## Architecture
|
||||
|
||||
All core logic is one `function *` per feature. Use `yield` where you'd normally `await` a potentially async value.
|
||||
|
||||
- `toPromise(generator)` — async driver; awaits yielded promises
|
||||
- `toValueSync(generator)` — sync driver; passes yielded values through as-is
|
||||
|
||||
Never duplicate logic into separate async and sync methods. One generator serves both paths.
|
||||
|
||||
When wrapping an async+sync pair (e.g. `contains`/`containsSync`, `readFile`/`readFileSync`), use `toLiquidAsync(asyncFn, syncFn?)` — returns a `LiquidAsync<F>` that picks sync or async via a leading `sync: boolean` arg. `yield` the result inside a generator. See `src/util/async.ts`.
|
||||
|
||||
## Style
|
||||
|
||||
Make minimal changes only. Avoid sweeping edits. Always check after you made changes.
|
||||
|
||||
- Change only what the task requires. No drive-by refactors, test harnesses, or extra files unless asked.
|
||||
- Match existing patterns in the file you edit.
|
||||
- Repro, PoC, and scratch files go in `.local/` — not tracked `poc/` folders or one-off scripts under `docs/`.
|
||||
|
||||
### Comments
|
||||
|
||||
- Do not add narrative comments. Code should be clear from structure and naming; if it needs explanation, refactor instead.
|
||||
- Comments follow existing repo usage only: non-obvious invariants, `@deprecated`, JSDoc on public API where TypeDoc needs it. Not for explaining changes to the author, migration history, or restating what the code already says.
|
||||
- Comments document the code; they do not fix unclear code.
|
||||
|
||||
### Tests
|
||||
|
||||
- Assert observable behavior, not internal implementation details.
|
||||
- Avoid duplicate coverage; keep test diffs minimal.
|
||||
- **E2E** (`test/e2e/`): import from the package root (resolves to `dist/` via `package.json`). Do not import from `src/` — e2e must match what npm consumers get.
|
||||
- **Integration/unit** (`test/integration/`, etc.): may import from `src/` against current TypeScript sources.
|
||||
|
||||
### Docs site
|
||||
|
||||
- Reuse existing asset paths under `docs/source/` and `docs/themes/navy/` — no new asset directories unless asked.
|
||||
- Front matter `title:` is plain text (no backticks).
|
||||
- `docs/source/llms.txt` — deployed to https://liquidjs.com/llms.txt for web agents (llms.txt spec).
|
||||
- After theme/markdown changes: build or serve locally, check in a browser (light and dark), not only curl or editor preview.
|
||||
|
||||
### README
|
||||
|
||||
- Research original sources before reordering contributors, logos, or lists.
|
||||
|
||||
## Verify
|
||||
|
||||
- Do not commit, push, amend, or open a PR unless asked.
|
||||
- After changes: verify yourself via CLI or UI (tests, `cd docs && npm start`, browser) before reporting done. Do not tell the user to check instead.
|
||||
- Before push on sweeping changes: run `npm run check`.
|
||||
- Confirm facts from `.github/workflows`, `package.json`, and library docs — not stale human docs or assumptions.
|
||||
- When replacing or integrating a library: read its docs and understand what the previous setup did before changing behavior.
|
||||
|
||||
### Security fixes
|
||||
|
||||
- Reproduce on current `master` first. Smallest fix that addresses the reported issue.
|
||||
- If Shopify/Ruby Liquid behaves the same, document unsafe usage in filter/docs instead of changing behavior.
|
||||
|
||||
## Docs
|
||||
|
||||
- Published: https://liquidjs.com
|
||||
- Repo agent instructions: this file (`AGENTS.md`)
|
||||
@@ -1,3 +1,17 @@
|
||||
## [10.27.1](https://github.com/harttle/liquidjs/compare/v10.27.0...v10.27.1) (2026-06-23)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* improve round function; improvement to [#873](https://github.com/harttle/liquidjs/issues/873) ([#901](https://github.com/harttle/liquidjs/issues/901)) ([956b51e](https://github.com/harttle/liquidjs/commit/956b51ea953eb52d9eba7409b7f51e379023fec4))
|
||||
* **security:** charge pop filter allocation to memoryLimit ([#907](https://github.com/harttle/liquidjs/issues/907)) ([8a0c74a](https://github.com/harttle/liquidjs/commit/8a0c74a7fcb1671aa1dcb71ec82ba0602dc90d04))
|
||||
* **strip_html:** infinite loop for strip_html ([5c3522f](https://github.com/harttle/liquidjs/commit/5c3522f33928aae66f0fe85c36e1d9015c768fe2))
|
||||
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* **parser:** memoize createTrie to avoid rebuilding tries per Tokenizer ([#911](https://github.com/harttle/liquidjs/issues/911)) ([3a0d80d](https://github.com/harttle/liquidjs/commit/3a0d80d1f4526af0fbca2bb2e0a9c51669d2fd3e))
|
||||
|
||||
# [10.27.0](https://github.com/harttle/liquidjs/compare/v10.26.0...v10.27.0) (2026-05-15)
|
||||
|
||||
|
||||
|
||||
@@ -1,72 +1,86 @@
|
||||
# liquidjs
|
||||
# LiquidJS
|
||||
|
||||
A simple, expressive, extensible Liquid template engine for JavaScript — Shopify, Jekyll and GitHub Pages compatible, for Node.js, browsers, and the CLI, with TypeScript support.
|
||||
|
||||
[](https://www.npmjs.org/package/liquidjs)
|
||||
[](https://www.npmjs.org/package/liquidjs)
|
||||
[](https://coveralls.io/github/harttle/liquidjs?branch=master)
|
||||
[](https://github.com/harttle/liquidjs/actions/workflows/ci-build.yml?query=branch%3Amaster)
|
||||
[](https://github.com/harttle/liquidjs/blob/master/LICENSE)
|
||||
[](https://github.com/harttle/liquidjs)
|
||||
[](https://coveralls.io/github/harttle/liquidjs?branch=master)
|
||||
[](https://github.com/harttle/liquidjs/blob/master/LICENSE)
|
||||
|
||||
A simple, expressive and safe [Shopify][shopify/liquid] / GitHub Pages compatible template engine in pure JavaScript.
|
||||
**The purpose of this repo** is to provide a standard Liquid implementation for the JavaScript community so that [Jekyll sites](https://jekyllrb.com), [GitHub Pages](https://pages.github.com/) and [Shopify templates](https://themes.shopify.com/) can be ported to Node.js without pain.
|
||||
[Documentation][doc] · [Playground](https://liquidjs.com/playground.html) · [Setup guide][setup] · [Contributing][contribution]
|
||||
|
||||
* [Documentation][doc]
|
||||
* Please star [LiquidJS on GitHub][github]!
|
||||
* Financial support via [GitHub Sponsors](https://github.com/sponsors/harttle).
|
||||
<a href="https://liquidjs.com/playground.html">
|
||||
<img src="docs/source/playground-demo.gif" alt="LiquidJS playground: edit a template and context, see live HTML output" width="980" style="display: block; margin: 0 auto;" />
|
||||
</a>
|
||||
|
||||
<p align="center"><a href="https://liquidjs.com"><img height="155px" width="155px" src="https://liquidjs.com/icon/mstile-310x310.png" alt="logo"></a></p>
|
||||
<p align="center"><sub>Try the <a href="https://liquidjs.com/playground.html">online playground</a>.</sub></p>
|
||||
|
||||
## What's it like?
|
||||
## Quick start
|
||||
|
||||
Basically there're two types of Liquid syntax: tags enclosed by `{% %}` and outputs enclosed by `{{ }}`. A Liquid template looks like:
|
||||
```js
|
||||
import { Liquid } from 'liquidjs'
|
||||
|
||||
```liquid
|
||||
{% if username %}
|
||||
{{ username | append: ", welcome to LiquidJS!" | capitalize }}
|
||||
{% endif %}
|
||||
const engine = new Liquid()
|
||||
const html = await engine.parseAndRender(
|
||||
'Hello, {{ name | capitalize }}!',
|
||||
{ name: 'liquid' }
|
||||
)
|
||||
//=> 'Hello, Liquid!'
|
||||
```
|
||||
|
||||
[A live demo](https://liquidjs.com/playground.html) is also available and here's a [quick tutorial](https://liquidjs.com/tutorials/intro-to-liquid.html) for Liquid syntax.
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
Install from npm in Node.js:
|
||||
**Node.js**
|
||||
|
||||
```bash
|
||||
npm install liquidjs
|
||||
```
|
||||
|
||||
Or use the UMD bundle from jsDelivr:
|
||||
**Browser** (jsDelivr UMD bundle)
|
||||
|
||||
```html
|
||||
<script src="https://cdn.jsdelivr.net/npm/liquidjs/dist/liquid.browser.min.js"></script>
|
||||
```
|
||||
|
||||
Or render directly from CLI using npx:
|
||||
**CLI**
|
||||
|
||||
```bash
|
||||
npx liquidjs --template 'Hello, {{ name }}!' --context '{"name": "Snake"}'
|
||||
npx liquidjs --template 'Hello, {{ name }}!' --context '{"name": "Liquid"}'
|
||||
```
|
||||
|
||||
For more details, refer to the [Setup Guide][setup].
|
||||
See the [setup guide][setup] for partials, layouts, caching, and other options.
|
||||
|
||||
## Who's Using LiquidJS?
|
||||
## Used by
|
||||
|
||||
- [Eleventy](https://www.11ty.dev/): Eleventy, a simpler static site generator.
|
||||
- [Github Docs](https://github.com/github/docs): The open-source repo for docs.github.com.
|
||||
- [Kibana](https://github.com/elastic/kibana): Elastic's analytics and visualization platform for Elasticsearch; workflow features use LiquidJS for Liquid templates.
|
||||
- [Opensense](https://www.opensense.com/): The smarter way to send email.
|
||||
- [Directus](https://docs.directus.io/): an instant REST+GraphQL API and intuitive no-code data collaboration app for any SQL database.
|
||||
- [Rock](https://www.rockrms.com/): An open source CMS, Relationship Management System (RMS) and Church Management System (ChMS) all rolled into one.
|
||||
- [Mitosis](https://github.com/BuilderIO/mitosis): Write components once, run everywhere. Compiles to React, Vue, Qwik, Solid, Angular, Svelte, and more.
|
||||
- [Pattern Lab](https://patternlab.io/): a frontend workshop environment that helps you build, view, test, and showcase your design system's UI components.
|
||||
- [Builder.io](https://www.builder.io/m/developers): the first and only headless CMS with a visual editor that lets you drag and drop with your components, directly within your current site or app. Completely API-driven, for cleaner code and simpler workflows.
|
||||
- [Microsoft Power Pages](https://learn.microsoft.com/en-us/power-pages/introduction): a secure, enterprise-grade, low-code software as a service (SaaS) platform for creating, hosting, and administering modern external-facing business websites.
|
||||
- [Azure API Management developer portal](https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-developer-portal): an automatically generated, fully customizable website with the documentation of your APIs.
|
||||
- [WISMOlabs](https://wismolabs.com/): Post Purchase Experience platform for eCommerce retailers enhancing customer satisfaction by using LiquidJS to provide customizable post-purchase experiences through programmable email, SMS, order tracking pages, and webhooks.
|
||||
- [Freshet](https://chromewebstore.google.com/detail/freshet/mpclplhdencffbilobpcapccnihpelcg): *JSON in, page out* — a Chrome extension that uses LiquidJS templates per URL pattern, so the JSON becomes a rendered, useful page.
|
||||
<!-- USED-BY-BEGIN -->
|
||||
<p align="center" style="line-height: 2.5;">
|
||||
<a href="https://www.11ty.dev/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/35147177?v=4&s=100" height="80" style="vertical-align: middle;" alt="Eleventy" title="Eleventy"/></a>
|
||||
<a href="https://www.opensense.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/opensense-inc/bf840ae/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="Opensense" title="Opensense"/></a>
|
||||
<a href="https://www.microsoft.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/6154722?v=4&s=100" height="80" style="vertical-align: middle;" alt="Power Pages, Azure API Management developer portal" title="Power Pages, Azure API Management developer portal"/></a>
|
||||
<a href="https://docs.github.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/9919?v=4&s=100" height="80" style="vertical-align: middle;" alt="GitHub Docs" title="GitHub Docs"/></a>
|
||||
<a href="https://github.com/elastic/kibana" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/6764390?v=4&s=100" height="80" style="vertical-align: middle;" alt="Kibana" title="Kibana"/></a>
|
||||
<a href="https://www.shopify.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/8085?v=4&s=100" height="80" style="vertical-align: middle;" alt="Shopify CLI, Checkout Blocks" title="Shopify CLI, Checkout Blocks"/></a>
|
||||
<a href="https://customer.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/1152079?v=4&s=100" height="80" style="vertical-align: middle;" alt="Customer IO" title="Customer IO"/></a>
|
||||
<br/>
|
||||
<a href="https://syntax.fm/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/130389858?v=4&s=100" height="80" style="vertical-align: middle;" alt="Syntax Podcast" title="Syntax Podcast"/></a>
|
||||
<a href="https://www.testmuai.com/?utm_medium=sponsor&utm_source=liquidjs" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/27130435?s=200&v=4" width="80" style="vertical-align: middle;" alt="TestMu AI" title="TestMu AI"/></a>
|
||||
<a href="https://chudovo.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/Chudovo/avatar/256.png?height=100" width="160" style="vertical-align: middle;background: white;padding: 8px 16px;" alt="Chudovo" title="Chudovo"/></a>
|
||||
<a href="https://www.pakstyle.pk/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/pakstyle/2b81605/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="PakStyle.pk" title="PakStyle.pk"/></a>
|
||||
<a href="https://www.escorta.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/escortacom/avatar/256.png?height=100" height="45" style="vertical-align: middle;" alt="EscortA.com" title="EscortA.com"/></a>
|
||||
<a href="https://opencollective.com/touchless" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/touchless/273bc74/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="Touchless" title="Touchless"/></a>
|
||||
<br/>
|
||||
<a href="https://www.dropkiq.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/1bertlol/43a8ea8/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="Dropkiq" title="Dropkiq"/></a>
|
||||
<a href="https://directus.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/15967950?v=4&s=100" height="80" style="vertical-align: middle;" alt="Directus" title="Directus"/></a>
|
||||
<a href="https://www.builder.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://cdn.builder.io/api/v1/image/assets%2FYJIGb4i01jvw0SRdL5Bt%2F51a002f4a17f4fc4a829b8891a1c25ee" height="80" style="vertical-align: middle;" alt="Builder.io, Mitosis" title="Builder.io, Mitosis"/></a>
|
||||
<a href="https://patternlab.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/4733935?v=4&s=100" height="80" style="vertical-align: middle;" alt="Pattern Lab" title="Pattern Lab"/></a>
|
||||
<a href="https://www.rockrms.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://www.rockrms.com/GetImage.ashx?id=72533" height="80" style="vertical-align: middle;" alt="Rock RMS" title="Rock RMS"/></a>
|
||||
<a href="https://wismolabs.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://cdn-ldlap.nitrocdn.com/DsLJMZpUUekfsitqBnNmsRAnzbwPoIzE/assets/images/optimized/rev-5df8687/wismolabs.com/wp-content/uploads/2023/03/favicon-300x300.png" height="80" style="vertical-align: middle;" alt="WISMOlabs" title="WISMOlabs"/></a>
|
||||
<a href="https://chromewebstore.google.com/detail/freshet/mpclplhdencffbilobpcapccnihpelcg" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://raw.githubusercontent.com/MattAltermatt/freshet/main/public/icon-128.png" height="80" style="vertical-align: middle;" alt="Freshet" title="Freshet"/></a>
|
||||
</p>
|
||||
<!-- USED-BY-END -->
|
||||
|
||||
Feel free to create a PR or contact me to add your use case into this list!
|
||||
Products and projects running on LiquidJS. [Open a PR](https://github.com/harttle/liquidjs/edit/master/README.md) to add yours.
|
||||
|
||||
## Financial Support
|
||||
|
||||
@@ -78,7 +92,7 @@ If you personally love LiquidJS or it's benefiting your business, please conside
|
||||
<a href="https://www.opensense.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/opensense-inc/bf840ae/logo/256.png?height=100" height="80" style="vertical-align: middle;" alt="Opensense Inc." title="Opensense"/></a>
|
||||
<a href="https://github.com/microsoft" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/6154722?v=4&s=100" height="80" style="vertical-align: middle;" alt="Microsoft" title="Microsoft"/></a>
|
||||
<a href="https://sentry.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/1396951?v=4&s=100" height="80" style="vertical-align: middle;" alt="Sentry" title="Sentry"/></a>
|
||||
<a href="https://www.checkoutblocks.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/114603307?v=4&s=100" height="80" style="vertical-align: middle;" alt="Checkout Blocks" title="Checkout Blocks"/></a>
|
||||
<a href="https://github.com/Checkout-Blocks" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/114603307?v=4&s=100" height="80" style="vertical-align: middle;" alt="Checkout Blocks" title="Checkout Blocks"/></a>
|
||||
<a href="https://customer.io/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/1152079?v=4&s=100" height="80" style="vertical-align: middle;" alt="Customer IO" title="Customer IO"/></a>
|
||||
<a href="https://syntax.fm/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/130389858?v=4&s=100" height="80" style="vertical-align: middle;" alt="Syntax Podcast" title="Syntax Podcast"/></a>
|
||||
<br/>
|
||||
@@ -226,6 +240,9 @@ Want to contribute? see [Contribution Guidelines][contribution]. Thanks goes to
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/talboren"><img src="https://avatars.githubusercontent.com/u/68807791?v=4?s=100" width="100px;" alt="Tal"/><br /><sub><b>Tal</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=talboren" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://filonov.dev"><img src="https://avatars.githubusercontent.com/u/813224?v=4?s=100" width="100px;" alt="Vladimir Filonov"/><br /><sub><b>Vladimir Filonov</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=VladimirFilonov" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/spokodev"><img src="https://avatars.githubusercontent.com/u/239690017?v=4?s=100" width="100px;" alt="spokodev"/><br /><sub><b>spokodev</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=spokodev" title="Code">💻</a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -234,8 +251,10 @@ Want to contribute? see [Contribution Guidelines][contribution]. Thanks goes to
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
||||
|
||||
[shopify/liquid]: https://shopify.github.io/liquid/
|
||||
[plugins]: https://liquidjs.com/tutorials/plugins.html#Plugin-List
|
||||
## License
|
||||
|
||||
[MIT](LICENSE) © [Jun Yang](https://github.com/harttle)
|
||||
|
||||
[setup]: https://liquidjs.com/tutorials/setup.html
|
||||
[doc]: https://liquidjs.com
|
||||
[github]: https://github.com/harttle/liquidjs
|
||||
|
||||
+5
-3
@@ -6,8 +6,10 @@ Only the latest major version is supported with security updates. It can be chan
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please contact harttleharttle@gmail.com to report a vulnerability or change request.
|
||||
**Please do not report security vulnerabilities through public GitHub issues.**
|
||||
|
||||
- If the vulnerability in question affects common use cases, it will be treated as a bug and fixed very soon (typically within 1 week).
|
||||
Report them via [GitHub Security Advisories — Report a vulnerability](https://github.com/harttle/liquidjs/security/advisories/new).
|
||||
|
||||
- If the vulnerability in question affects common use cases, it will be treated as a bug and fixed very soon (typically within a month).
|
||||
- Otherwise, it'll be scheduled in the same priority of feature request (which is lower than bugs).
|
||||
- If the request is declined, you'll receive a reply email anyway (most likely there will be a discussion).
|
||||
- If the request is declined, you'll receive a reply anyway (most likely there will be a discussion).
|
||||
|
||||
@@ -33,7 +33,9 @@ function transformFinancial (html) {
|
||||
|
||||
const allContributors = transformContributors(extractSection(readme, 'ALL-CONTRIBUTORS-LIST:START', 'ALL-CONTRIBUTORS-LIST:END'))
|
||||
const financialContributors = transformFinancial(extractSection(readme, 'FINANCIAL-CONTRIBUTORS-BEGIN', 'FINANCIAL-CONTRIBUTORS-END'))
|
||||
const usedBy = transformFinancial(extractSection(readme, 'USED-BY-BEGIN', 'USED-BY-END'))
|
||||
|
||||
const outDir = path.join(root, 'docs/themes/navy/layout/partial')
|
||||
fs.writeFileSync(path.join(outDir, 'all-contributors.swig'), allContributors)
|
||||
fs.writeFileSync(path.join(outDir, 'financial-contributors.swig'), financialContributors)
|
||||
fs.writeFileSync(path.join(outDir, 'used-by.swig'), usedBy)
|
||||
|
||||
@@ -7,13 +7,13 @@ while ! grep -q "Express running" "$LOG_FILE"; do
|
||||
if ! kill -0 $SERVER_PID; then
|
||||
echo "Server exited unexpectedly."
|
||||
cat $LOG_FILE
|
||||
return 1
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
curl http://127.0.0.1:3000 | grep -q 'Welcome to LiquidJS'
|
||||
RESULT=$?
|
||||
killall node
|
||||
killall node || true
|
||||
rm $LOG_FILE
|
||||
if [ $RESULT != 0 ]; then
|
||||
exit 1
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
title: LiquidJS
|
||||
subtitle: "A simple, expressive, and safe template engine for JavaScript."
|
||||
description: "LiquidJS is a simple, expressive, and safe template engine for JavaScript, compatible with Shopify and GitHub Pages."
|
||||
subtitle: "A simple, expressive, extensible Liquid template engine for JavaScript"
|
||||
description: "A simple, expressive, extensible Liquid template engine for JavaScript — Shopify, Jekyll and GitHub Pages compatible, for Node.js, browsers, and the CLI, with TypeScript support."
|
||||
author: Harttle
|
||||
language: en
|
||||
timezone: UTC
|
||||
|
||||
@@ -6,6 +6,10 @@ title: strip_html
|
||||
|
||||
Removes any HTML tags from a string.
|
||||
|
||||
{% note warn Not safe for HTML output %}
|
||||
This filter removes tags by string scanning; it does not parse HTML5 the way a browser does, and it is not a sanitizer. The result may still be unsafe when inserted into HTML. Use [escape][escape], [escape_once][escape_once], or [`outputEscape: "escape"`][outputEscape] for untrusted output.
|
||||
{% endnote %}
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{{ "Have <em>you</em> read <strong>Ulysses</strong>?" | strip_html }}
|
||||
@@ -15,3 +19,7 @@ Output
|
||||
```text
|
||||
Have you read Ulysses?
|
||||
```
|
||||
|
||||
[escape]: ./escape.html
|
||||
[escape_once]: ./escape.html
|
||||
[outputEscape]: ../tutorials/options.html#outputEscape
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
layout: index
|
||||
description: LiquidJS is a simple, expressive and safe Shopify / GitHub Pages compatible template engine in pure JavaScript.
|
||||
subtitle: A simple, expressive and safe template engine.
|
||||
---
|
||||
ul#intro-feature-list
|
||||
li.intro-feature-wrap
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# LiquidJS
|
||||
|
||||
> A simple, expressive, extensible Liquid template engine for JavaScript
|
||||
|
||||
## Tutorials
|
||||
|
||||
- [Introduction to Liquid](https://liquidjs.com/tutorials/intro-to-liquid.html)
|
||||
- [Setup](https://liquidjs.com/tutorials/setup.html)
|
||||
- [Options](https://liquidjs.com/tutorials/options.html)
|
||||
- [Render files](https://liquidjs.com/tutorials/render-file.html)
|
||||
- [Partials and layouts](https://liquidjs.com/tutorials/partials-and-layouts.html)
|
||||
- [Express.js](https://liquidjs.com/tutorials/use-in-expressjs.html)
|
||||
- [Register filters and tags](https://liquidjs.com/tutorials/register-filters-tags.html)
|
||||
- [Plugins](https://liquidjs.com/tutorials/plugins.html)
|
||||
- [Sync and async](https://liquidjs.com/tutorials/sync-and-async.html)
|
||||
- [Operators](https://liquidjs.com/tutorials/operators.html)
|
||||
- [Truthy and falsy](https://liquidjs.com/tutorials/truthy-and-falsy.html)
|
||||
- [Security model](https://liquidjs.com/tutorials/security-model.html)
|
||||
- [Differences from Shopify Liquid](https://liquidjs.com/tutorials/differences.html)
|
||||
- [Migrate to v9](https://liquidjs.com/tutorials/migrate-to-9.html)
|
||||
- [Changelog](https://liquidjs.com/tutorials/changelog.html)
|
||||
|
||||
## Reference
|
||||
|
||||
- [Tags](https://liquidjs.com/tags/overview.html)
|
||||
- [Filters](https://liquidjs.com/filters/overview.html)
|
||||
- [API (TypeDoc)](https://liquidjs.com/api/)
|
||||
- [Playground](https://liquidjs.com/playground.html)
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"short_name": "LiquidJS",
|
||||
"name": "LiquidJS",
|
||||
"description": "A simple, expressive and safe Shopify / GitHub Pages compatible template engine in pure JavaScript.",
|
||||
"description": "A simple, expressive, extensible Liquid template engine for JavaScript",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon/apple-touch-icon-57x57.png",
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 38 KiB |
@@ -3,9 +3,9 @@ title: The Liquid Template Language
|
||||
describe: A short introduction to the Liquid template language and some simple demos.
|
||||
---
|
||||
|
||||
LiquidJS is a simple, expressive and safe [Shopify][shopify/liquid] / GitHub Pages compatible template engine in pure JavaScript. The purpose of this repo is to provide a standard Liquid implementation for the JavaScript community. Liquid is originally implemented in Ruby and used by GitHub Pages, Jekyll and Shopify, see [Differences with Shopify/liquid][diff].
|
||||
Liquid is a template language originally implemented in Ruby and used by Shopify, Jekyll, and GitHub Pages. LiquidJS implements it in JavaScript; see [Differences with Shopify/liquid][diff] for compatibility notes.
|
||||
|
||||
LiquidJS syntax is relatively simple. There are 2 types of markups in LiquidJS:
|
||||
There are 2 types of markups in LiquidJS:
|
||||
|
||||
- **Tags**. A tag consists of a tag name and optional arguments wrapped between `{%raw%}{%{%endraw%}` and `%}`.
|
||||
- **Outputs**. An output consists of a value and a list of filters, which is optional, wrapped between `{%raw%}{{{%endraw%}` and `}}`.
|
||||
@@ -56,5 +56,4 @@ Typically tags appear in pairs with a start tag and a corresponding end tag. For
|
||||
|
||||
A complete list of tags supported by LiquidJS can be found [here](../tags/overview.html).
|
||||
|
||||
[shopify/liquid]: https://github.com/Shopify/liquid
|
||||
[diff]: ./differences.html
|
||||
|
||||
@@ -138,7 +138,7 @@ It defaults to `false`. For example, when set to `true`, a blank string would ev
|
||||
|
||||
**lenientIf** modifies the behavior of `strictVariables` to allow handling optional variables. If set to `true`, an undefined variable will *not* cause an exception in the following two situations: a) it is the condition to an `if`, `elsif`, or `unless` tag; b) it occurs right before a `default` filter. Irrelevant if `strictVariables` is not set. Defaults to `false`.
|
||||
|
||||
**ownPropertyOnly** hides scope variables from prototypes, useful when you're passing a not sanitized object into LiquidJS or need to hide prototypes from templates. Defaults to `true`.
|
||||
**ownPropertyOnly** limits template property reads on plain scope objects to own properties. Defaults to `true`. See [Security Model](./security-model.html).
|
||||
|
||||
{% note info Nonexistent Tags %}
|
||||
Nonexistent tags always throw errors during parsing and this behavior cannot be customized.
|
||||
|
||||
@@ -22,7 +22,7 @@ Expected output:
|
||||
</div>
|
||||
```
|
||||
|
||||
Firstly, [register][register-tags] a tag named `wrap` and parse the content into `this.tpls`. Here in `parse(tagToken, remainTokens)`:
|
||||
Firstly, [register][register-tags] a tag named `wrap` and parse the content into `this.tpls`. In the tag `constructor(tagToken, remainTokens, liquid)`:
|
||||
|
||||
- `tagToken` is current token `{%raw%}{% wrap %}{%endraw%}`, and
|
||||
- `remainTokens` is an array of all tokens following `{%raw%}{% wrap %}{%endraw%}` until the end of this template file.
|
||||
@@ -30,11 +30,14 @@ Firstly, [register][register-tags] a tag named `wrap` and parse the content into
|
||||
Basically, what we need to do is take/`.shift()` enough tags from `remainTokens` until we get an `endwrap` token (the name can be arbitrary, but by convention it should be `endwrap`). And if there's no `endwrap` until the end of the template file, we need to throw a tag-not-closed `Error`.
|
||||
|
||||
```javascript
|
||||
engine.registerTag('wrap', {
|
||||
parse(tagToken, remainTokens) {
|
||||
this.tpls = []
|
||||
const { Tag } = require('liquidjs')
|
||||
|
||||
engine.registerTag('wrap', class WrapTag extends Tag {
|
||||
tpls = []
|
||||
constructor(tagToken, remainTokens, liquid) {
|
||||
super(tagToken, remainTokens, liquid)
|
||||
let closed = false
|
||||
while(remainTokens.length) {
|
||||
while (remainTokens.length) {
|
||||
let token = remainTokens.shift()
|
||||
// we got the end tag! stop taking tokens
|
||||
if (token.name === 'endwrap') {
|
||||
@@ -44,11 +47,11 @@ engine.registerTag('wrap', {
|
||||
// parse token into template
|
||||
// parseToken() may consume more than 1 tokens
|
||||
// e.g. {% if %}...{% endif %}
|
||||
let tpl = this.liquid.parser.parseToken(token, remainTokens)
|
||||
let tpl = liquid.parser.parseToken(token, remainTokens)
|
||||
this.tpls.push(tpl)
|
||||
}
|
||||
if (!closed) throw new Error(`tag ${tagToken.getText()} not closed`)
|
||||
},
|
||||
}
|
||||
* render(context, emitter) {
|
||||
emitter.write("<div class='wrapper'>")
|
||||
yield this.liquid.renderer.renderTemplates(this.tpls, context, emitter)
|
||||
@@ -57,16 +60,17 @@ engine.registerTag('wrap', {
|
||||
})
|
||||
```
|
||||
|
||||
`.renderTemplates()` can be async; we need `yield` to wait for it to complete. For more details on async in LiquidJS, see [Sync and Async][async]. Other parts of the `render()` method are quite straightforward. Here's a JSFiddle version: <https://jsfiddle.net/por0zcn1/3/>
|
||||
`.renderTemplates()` can be async; we need `yield` to wait for it to complete. For more details on async in LiquidJS, see [Sync and Async][async]. Here's a JSFiddle version: <https://jsfiddle.net/por0zcn1/3/>
|
||||
|
||||
## Using ParseStream
|
||||
|
||||
When it comes to complex tags like [for][for] and [if][if], the `parse()` can be very complicated. There's a [ParseStream][ParseStream] utility to organize the `parse()` in event-based style. Following is a re-written `parse()` using `ParseStream` that does exactly the same as the example above.
|
||||
For more complex tags such as [for][for] and [if][if], constructor parsing can get unwieldy. [ParseStream][ParseStream] offers an event-based API for this. The constructor below is equivalent to the example above:
|
||||
|
||||
```javascript
|
||||
parse(tagToken, remainTokens) {
|
||||
this.tpls = []
|
||||
this.liquid.parser.parseStream(remainTokens)
|
||||
tpls = []
|
||||
constructor(tagToken, remainTokens, liquid) {
|
||||
super(tagToken, remainTokens, liquid)
|
||||
liquid.parser.parseStream(remainTokens)
|
||||
.on('template', tpl => this.tpls.push(tpl))
|
||||
// note that we cannot use arrow function because we need `this`
|
||||
.on('tag:endwrap', function () { this.stop() })
|
||||
@@ -103,15 +107,18 @@ As you've noticed, there's an additional `repeat.i` in the context of `repeat`.
|
||||
Each time we enter a new *Context*, we need to push a new *Scope*. And when we finish rendering and exit the *Context*, we pop the *Scope* from the *Context*. As you can see in the following implementation:
|
||||
|
||||
```javascript
|
||||
engine.registerTag('repeat', {
|
||||
parse(tagToken, remainTokens) {
|
||||
this.tpls = []
|
||||
this.liquid.parser.parseStream(remainTokens)
|
||||
const { Tag } = require('liquidjs')
|
||||
|
||||
engine.registerTag('repeat', class RepeatTag extends Tag {
|
||||
tpls = []
|
||||
constructor(tagToken, remainTokens, liquid) {
|
||||
super(tagToken, remainTokens, liquid)
|
||||
liquid.parser.parseStream(remainTokens)
|
||||
.on('template', tpl => this.tpls.push(tpl))
|
||||
.on('tag:endrepeat', function () { this.stop() })
|
||||
.on('end', () => { throw new Error(`tag ${tagToken.getText()} not closed`) })
|
||||
.start()
|
||||
},
|
||||
}
|
||||
* render(context, emitter) {
|
||||
const repeat = { i: 1 }
|
||||
context.push({ repeat })
|
||||
@@ -123,7 +130,7 @@ engine.registerTag('repeat', {
|
||||
})
|
||||
```
|
||||
|
||||
The `parse()` is exactly the same as `wrap` tag, we repeat the content simply by calling `.renderTemplates(this.tpls)` twice during `render()`. Here's the JSFiddle: <https://jsfiddle.net/por0zcn1/2/>
|
||||
The constructor is the same as in the `wrap` tag; we repeat the content by calling `.renderTemplates(this.tpls)` twice during `render()`. Here's the JSFiddle: <https://jsfiddle.net/por0zcn1/2/>
|
||||
|
||||
{% note warn Use Push & Pop in Pairs %}
|
||||
`context.push()` and `context.pop()` have to be used in pairs. Failing to `pop()` the *Scope* you pushed will leak the *Scope* to latter templates and may corrupt the *Context* stack.
|
||||
|
||||
@@ -2,21 +2,19 @@
|
||||
title: Security Model
|
||||
---
|
||||
|
||||
LiquidJS provides DoS-oriented limits (`parseLimit`, `renderLimit`, `memoryLimit`) to reduce risk. This page summarizes those limits, [`ownPropertyOnly`][ownPropertyOnly], custom [`Drop`][drop] usage, and the security boundary to assume in production.
|
||||
LiquidJS provides DoS-oriented limits (`parseLimit`, `templateLimit`, `outputLengthLimit`, `maxDepth`) to reduce risk. This page summarizes those limits, [`ownPropertyOnly`][ownPropertyOnly], custom [`Drop`][drop] usage, and the security boundary to assume in production.
|
||||
|
||||
## Security boundary
|
||||
## At a glance
|
||||
|
||||
The built-in limits are cooperative safeguards, not strict runtime isolation.
|
||||
|
||||
- They do **not** equal process RSS/heap usage.
|
||||
- They do **not** sandbox JavaScript execution.
|
||||
- They should be combined with process/container limits and request timeouts for defense in depth.
|
||||
|
||||
## Limits at a glance
|
||||
LiquidJS ships a thin cooperative DoS layer:
|
||||
|
||||
- [parseLimit][parseLimit]: limit total template size per `parse()` call.
|
||||
- [renderLimit][renderLimit]: limit total render time per `render()` call.
|
||||
- [memoryLimit][memoryLimit]: cooperatively limit memory-sensitive allocations counted by LiquidJS.
|
||||
- [templateLimit][templateLimit]: limit total tag/HTML/output nodes rendered per `render()` call.
|
||||
- [outputLengthLimit][outputLengthLimit]: limit total output length per `render()` call.
|
||||
- [maxDepth][maxDepth]: limit nesting depth of `{% render %}`, `{% include %}`, and `{% layout %}`.
|
||||
- Strftime numeric pad widths in the `date` filter are capped at `1_000_000` (1M) per conversion.
|
||||
|
||||
These are cooperative safeguards, not runtime isolation—see [Production guidance](#production-guidance) below for host-level limits and online-service hardening.
|
||||
|
||||
## Limit details
|
||||
|
||||
@@ -26,9 +24,9 @@ The built-in limits are cooperative safeguards, not strict runtime isolation.
|
||||
|
||||
A typical PC handles `1e8` (100M) characters without issues.
|
||||
|
||||
### renderLimit
|
||||
### templateLimit
|
||||
|
||||
Restricting template size alone is insufficient because dynamic loops with large counts can occur during rendering. [renderLimit][renderLimit] mitigates this by limiting the time consumed by each `render()` call.
|
||||
Restricting template size alone is insufficient because dynamic loops with large counts can occur during rendering. [templateLimit][templateLimit] mitigates this by limiting the number of tag, HTML literal, and output nodes rendered in each `render()` call.
|
||||
|
||||
```liquid
|
||||
{%- for i in (1..10000000) -%}
|
||||
@@ -36,52 +34,47 @@ Restricting template size alone is insufficient because dynamic loops with large
|
||||
{%- endfor -%}
|
||||
```
|
||||
|
||||
Render time is checked on a per-template basis (before rendering each template). In the above example, there are 2 templates in the loop: `order: ` and `{{i}}`, render time will be checked 10000000x2 times.
|
||||
Each template node (the `for` tag, literal `order: `, output `{{i}}`, and so on) counts toward the limit. In the above example, a limit of `30000000` would be exceeded before the loop finishes.
|
||||
|
||||
`renderLimit` is not a hard CPU limiter. It is checked between template renders, so compute-intensive filters/tags/user-defined functions or deeply nested template execution between checks can still cause DoS.
|
||||
`templateLimit` is checked before each node render, so compute-intensive filters/tags/user-defined functions between checks can still cause DoS.
|
||||
|
||||
### memoryLimit
|
||||
### outputLengthLimit
|
||||
|
||||
`memoryLimit` only limits operations that LiquidJS explicitly counts.
|
||||
[outputLengthLimit][outputLengthLimit] caps the cumulative length of output written during a `render()` call, including output from partials rendered via `{% render %}`.
|
||||
|
||||
- Counted: memory-sensitive LiquidJS operations that call internal memory accounting.
|
||||
- Not guaranteed counted: arbitrary user object behavior such as custom `toValue()`/`toString()` chains, or other host-side code that allocates outside LiquidJS accounting points.
|
||||
### maxDepth
|
||||
|
||||
In other words, `memoryLimit` limits what LiquidJS counts, not every byte your process may allocate.
|
||||
[maxDepth][maxDepth] limits how deeply `{% render %}`, `{% include %}`, and `{% layout %}` can nest. Defaults to `128`. In sync rendering (`renderSync`), nested tags are driven by `toValueSync`, which recursively resumes each yielded generator on the call stack—deep nesting can overflow it, and `maxDepth` caps that depth. Async `render()` resumes the same tag generators via `toPromise`/`yield` without a deep synchronous call chain, so stack overflow is not a concern there (the limit still applies as a DoS guard).
|
||||
|
||||
Even with a small number of templates and iterations, memory usage can grow exponentially. In the following example, memory doubles with each iteration:
|
||||
|
||||
```liquid
|
||||
{% assign array = "1,2,3" | split: "," %}
|
||||
{% for i in (1..32) %}
|
||||
{% assign array = array | concat: array %}
|
||||
{% endfor %}
|
||||
```
|
||||
|
||||
As [JavaScript uses GC to manage memory](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_management), `memoryLimit` may not reflect the actual memory footprint.
|
||||
The `memoryLimit` option was removed in v11; enforce memory limits at the host or process level instead.
|
||||
|
||||
## `ownPropertyOnly` and scope data
|
||||
|
||||
With [`ownPropertyOnly`][ownPropertyOnly] `true`, plain scope objects only expose **own** properties (no inherited / `Object.prototype` keys). Default `false` follows normal JS property access. Use `true` for untrusted or polluted objects; add [`strictVariables`][strictVariables] if missing paths should error. Override per render via [`RenderOptions`][renderOwnPropertyOnly]. This is a read policy for scope data—not a sandbox for filters, tags, or your code.
|
||||
With [`ownPropertyOnly`][ownPropertyOnly] `true` (default), plain scope objects only expose **own** properties (no inherited / `Object.prototype` keys), and reads of `__proto__`, `constructor`, and `prototype` are blocked (own and inherited) as a prototype-pollution defense. With `false`, inherited properties and those keys are allowed—sanitize untrusted scope data (e.g. with [bourne](https://www.npmjs.com/package/bourne)) before passing it as scope. LiquidJS also uses null-prototype objects for managed scope frames (e.g. `{% capture %}`, `{% assign %}`) so internal frames do not inherit from `Object.prototype`.
|
||||
|
||||
Not restricted: [`Drop`][drop] values, iteration via `Symbol.iterator`, `.size`/`.first`/`.last`, filters, and custom tags.
|
||||
|
||||
Use `true` for untrusted objects; add [`strictVariables`][strictVariables] if missing paths should error. Override per render via [`RenderOptions`][renderOwnPropertyOnly]. This is a read policy for scope data—not a sandbox for filters, tags, or your code.
|
||||
|
||||
## Custom `Drop` classes
|
||||
|
||||
[`Drop`][drop] values are not restricted the same way: LiquidJS still reads the prototype chain and may call [`liquidMethodMissing`][liquidMethodMissing]. **You** control what a drop exposes; narrow APIs and never feed unsafe data into drops unless the class is built for template access. `ownPropertyOnly` alone does not harden custom drops—audit them like any privileged code.
|
||||
|
||||
## Online service guidance
|
||||
## Production guidance
|
||||
|
||||
If you run an online service, avoid rendering fully user-defined templates whenever possible.
|
||||
LiquidJS does not sandbox template code—custom filters, tags, and scope helpers run as ordinary JavaScript with your process privileges. Built-in DoS limits are one layer; production deployments, especially online services that accept template input, need additional hardening:
|
||||
|
||||
- Prefer curated templates or a restricted template subset.
|
||||
- If user-defined templates are required, isolate rendering (worker/process/container), enforce OS/container memory and CPU limits, and apply request rate limits.
|
||||
- Treat `parseLimit`/`renderLimit`/`memoryLimit` as one layer in a broader DoS defense strategy.
|
||||
|
||||
For heavy single-template operations, process-level isolation is still recommended (for example with [paralleljs][paralleljs]).
|
||||
- **Prefer curated templates** over fully user-defined Liquid when possible; if users need customization, offer a restricted subset rather than open template editing.
|
||||
- Run each render in a **worker thread or child process** with a wall-clock timeout; **kill** the worker on expiry. Libraries such as [paralleljs][paralleljs] can help for heavy single-template work.
|
||||
- Enforce **container/Kubernetes cgroup limits**, `ulimit`, or equivalent on the renderer process for memory and CPU.
|
||||
- Apply **request rate limits** at the API or gateway layer.
|
||||
- **`node:vm`, `isolated-vm`, and Jinja/Twig-style sandbox modes are not a security boundary**—template logic runs in the same JS runtime as your app, with your privileges.
|
||||
|
||||
[paralleljs]: https://www.npmjs.com/package/paralleljs
|
||||
[parseLimit]: /api/interfaces/LiquidOptions.html#parseLimit
|
||||
[renderLimit]: /api/interfaces/LiquidOptions.html#renderLimit
|
||||
[memoryLimit]: /api/interfaces/LiquidOptions.html#memoryLimit
|
||||
[templateLimit]: /api/interfaces/LiquidOptions.html#templateLimit
|
||||
[outputLengthLimit]: /api/interfaces/LiquidOptions.html#outputLengthLimit
|
||||
[maxDepth]: /api/interfaces/LiquidOptions.html#maxDepth
|
||||
[ownPropertyOnly]: /api/interfaces/LiquidOptions.html#ownPropertyOnly
|
||||
[renderOwnPropertyOnly]: /api/interfaces/RenderOptions.html#ownPropertyOnly
|
||||
[strictVariables]: /api/interfaces/LiquidOptions.html#strictVariables
|
||||
|
||||
Vendored
+5
-1
@@ -13,10 +13,14 @@ index:
|
||||
description: 'Thanks to these wonderful people! See <a href="tutorials/contribution-guidelines.html">contribution guidelines</a> if you'd like to help.'
|
||||
sponsors:
|
||||
title: Sponsors
|
||||
description: 'If you personally love LiquidJS or it's benefiting your business, please <a href="https://github.com/sponsors/harttle">sponsor us</a>!'
|
||||
description: 'Organizations and individuals who <a href="https://github.com/sponsors/harttle">sponsor LiquidJS</a>. Thank you!'
|
||||
used_by:
|
||||
title: Used by
|
||||
description: 'Products and projects running on LiquidJS. <a href="https://github.com/harttle/liquidjs/edit/master/README.md">Open a PR</a> to add yours.'
|
||||
|
||||
playground:
|
||||
title: Playground
|
||||
lead: Edit a template and context JSON — rendered HTML updates as you type.
|
||||
loading: Loading...
|
||||
|
||||
page:
|
||||
|
||||
Vendored
+18
-5
@@ -1,6 +1,6 @@
|
||||
<header id="banner" class="wrapper">
|
||||
<div class="inner inner-content">
|
||||
<h2 id="banner-title">{{ page.subtitle }}</h2>
|
||||
<h2 id="banner-title">{{ page.subtitle | default(config.subtitle) }}</h2>
|
||||
<div id="banner-share">{{ partial('partial/share') }}</div>
|
||||
<div id="banner-start">
|
||||
<code id="banner-start-command">npm install liquidjs</code><a id="banner-start-link" href="./tutorials/setup.html"><i class="icon-arrow-right"></i></a>
|
||||
@@ -14,15 +14,15 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="contributors-wrap">
|
||||
<div id="used-by-wrap">
|
||||
<div class="wrapper">
|
||||
<div class="inner inner-content">
|
||||
<div class="section-header">
|
||||
<h3>{{__('index.contributors.title')}}</h3>
|
||||
<p class="description">{{__('index.contributors.description')}}</p>
|
||||
<h3>{{__('index.used_by.title')}}</h3>
|
||||
<p class="description">{{__('index.used_by.description')}}</p>
|
||||
</div>
|
||||
<div class="contributors">
|
||||
{{ partial('partial/all-contributors') }}
|
||||
{{ partial('partial/used-by') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -40,3 +40,16 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="contributors-wrap">
|
||||
<div class="wrapper">
|
||||
<div class="inner inner-content">
|
||||
<div class="section-header">
|
||||
<h3>{{__('index.contributors.title')}}</h3>
|
||||
<p class="description">{{__('index.contributors.description')}}</p>
|
||||
</div>
|
||||
<div class="contributors">
|
||||
{{ partial('partial/all-contributors') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+6
-3
@@ -1,6 +1,11 @@
|
||||
{% if page.layout === 'playground' %}
|
||||
{{ js('js/liquid.browser.min.js') }}
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src-min/ace.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src-min/mode-liquid.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src-min/mode-json.js"></script>
|
||||
<script>ace.config.set('basePath', 'https://cdn.jsdelivr.net/npm/[email protected]/src-min/');</script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/prism.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/components/prism-markup.min.js"></script>
|
||||
{% endif %}
|
||||
|
||||
{{ js('js/main') }}
|
||||
@@ -17,12 +22,10 @@ debug: false
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Google tag (gtag.js) -->
|
||||
<script async src="https://www.googletagmanager.com/gtag/js?id=G-GM713991QQ"></script>
|
||||
<script>
|
||||
<script type="text/plain" data-category="analytics">
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
|
||||
gtag('config', 'G-GM713991QQ');
|
||||
</script>
|
||||
+1
-5
@@ -1,7 +1,3 @@
|
||||
{
|
||||
"people": [
|
||||
"alice",
|
||||
"bob",
|
||||
"carol"
|
||||
]
|
||||
"name": "liquid"
|
||||
}
|
||||
|
||||
+1
-9
@@ -1,9 +1 @@
|
||||
<ul>
|
||||
{%- for person in people %}
|
||||
<li>
|
||||
<a href="{{person | prepend: "https://example.com/"}}">
|
||||
{{ person | capitalize }}
|
||||
</a>
|
||||
</li>
|
||||
{%- endfor%}
|
||||
</ul>
|
||||
<p>Hello, {{ name | capitalize }}!</p>
|
||||
|
||||
+1
@@ -5,6 +5,7 @@
|
||||
{{__('footer.license')}}
|
||||
</div>
|
||||
<div id="footer-links">
|
||||
<button type="button" class="footer-link cookie-preferences" data-cc="show-consentModal" title="Manage cookie preferences"><i class="icon-shield"></i></button>
|
||||
<a href="https://twitter.com/{{ config.twitter }}" class="footer-link" target="_blank"><i class="icon-twitter"></i></a>
|
||||
<a href="https://opencollective.com/{{ config.oc }}" class="footer-link" target="_blank"><i class="icon-opencollective"></i></a>
|
||||
<a href="https://github.com/{{ config.github }}" class="footer-link" target="_blank"><i class="icon-github"></i></a>
|
||||
|
||||
+3
-8
@@ -32,12 +32,7 @@
|
||||
<meta name="msapplication-TileImage" content="{{ url_for('icon/mstile-144x144.png') }}">
|
||||
{{ css('css/navy') }}
|
||||
{{ feed_tag('atom.xml') }}
|
||||
<script src="https://cdn.cookiehub.eu/c2/e8e44c93.js"></script>
|
||||
<script type="text/javascript">
|
||||
document.addEventListener("DOMContentLoaded", function(event) {
|
||||
if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') return;
|
||||
var cpm = {};
|
||||
window.cookiehub.load(cpm);
|
||||
});
|
||||
</script>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orestbida/[email protected]/dist/cookieconsent.css">
|
||||
<script src="https://cdn.jsdelivr.net/gh/orestbida/[email protected]/dist/cookieconsent.umd.js"></script>
|
||||
{{ js('js/cookieconsent-config') }}
|
||||
</head>
|
||||
|
||||
+37
-13
@@ -1,21 +1,45 @@
|
||||
<div id="playground" role="main">
|
||||
<div class="wrapper">
|
||||
<h1 class="inner">{{__('playground.title')}}</h1>
|
||||
<header class="playground-hero inner">
|
||||
<div class="playground-hero-text">
|
||||
<h1>{{__('playground.title')}}</h1>
|
||||
<p class="playground-lead">{{__('playground.lead')}}</p>
|
||||
</div>
|
||||
<p class="playground-version version"></p>
|
||||
</header>
|
||||
<div class="loader" role=status aria-busy=true></div>
|
||||
<div id="editors" class="inner hide" aria-hide=true>
|
||||
<div class="area-tpl editor-wrapper">
|
||||
<h2>Template</h2>
|
||||
<div class="editor" id="editorEl">{{ raw('partial/demo.liquid') }}</div>
|
||||
</div>
|
||||
<div class="area-data editor-wrapper">
|
||||
<h2>Context</h2>
|
||||
<div class="editor" id="dataEl">{{ raw('partial/demo.json') }}</div>
|
||||
</div>
|
||||
<div class="area-output editor-wrapper">
|
||||
<h2>Output</h2>
|
||||
<div class="editor" id="previewEl">{{__('playground.loading')}}</div>
|
||||
<div class="playground-workspace">
|
||||
<div class="playground-pane area-tpl">
|
||||
<div class="pane-head">
|
||||
<span class="pane-indicator" data-state="idle" aria-hidden="true"></span>
|
||||
<h2>Template</h2>
|
||||
</div>
|
||||
<div class="pane-body">
|
||||
<div class="editor" id="editorEl">{{ raw('partial/demo.liquid') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="playground-pane area-data">
|
||||
<div class="pane-head">
|
||||
<span class="pane-indicator" data-state="idle" aria-hidden="true"></span>
|
||||
<h2>Context</h2>
|
||||
</div>
|
||||
<div class="pane-body">
|
||||
<div class="editor" id="dataEl">{{ raw('partial/demo.json') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="playground-pane area-output">
|
||||
<div class="pane-head">
|
||||
<span class="pane-indicator" data-state="idle" aria-hidden="true"></span>
|
||||
<h2>Output</h2>
|
||||
</div>
|
||||
<div class="pane-body">
|
||||
<div class="output-preview" id="previewEl">
|
||||
<pre class="highlight"><code class="language-markup" id="previewCode">{{__('playground.loading')}}</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="inner version"></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#cc-main
|
||||
--cc-btn-primary-bg: var(--color-link)
|
||||
--cc-btn-primary-color: #fff
|
||||
--cc-btn-primary-border-color: var(--color-link)
|
||||
--cc-btn-primary-hover-bg: var(--color-link-hover)
|
||||
--cc-btn-primary-hover-border-color: var(--color-link-hover)
|
||||
--cc-btn-secondary-bg: #eaeff2
|
||||
--cc-btn-secondary-color: var(--color-default)
|
||||
--cc-btn-secondary-border-color: #eaeff2
|
||||
--cc-toggle-on-bg: var(--color-link)
|
||||
|
||||
.cc--darkmode #cc-main
|
||||
--cc-btn-secondary-bg: #3a4248
|
||||
--cc-btn-secondary-color: var(--color-default)
|
||||
--cc-btn-secondary-border-color: #3a4248
|
||||
@@ -42,6 +42,13 @@
|
||||
@media mq-normal
|
||||
font-size: 30px
|
||||
|
||||
.cookie-preferences
|
||||
background: none
|
||||
border: 0
|
||||
padding: 0
|
||||
cursor: pointer
|
||||
color: inherit
|
||||
|
||||
.icon-oc
|
||||
height: 36px
|
||||
width: 30px
|
||||
|
||||
+2
-2
@@ -126,7 +126,7 @@
|
||||
background: var(--color-link-hover)
|
||||
color: #fff
|
||||
|
||||
#sponsors-wrap, #contributors-wrap
|
||||
#used-by-wrap, #sponsors-wrap, #contributors-wrap
|
||||
background: var(--color-navy-lighter)
|
||||
border-top: 1px solid #161d24
|
||||
border-bottom: 1px solid #161d24
|
||||
@@ -181,7 +181,7 @@
|
||||
|
||||
#contributors-wrap
|
||||
border: none
|
||||
overflow: hidden;
|
||||
overflow: hidden
|
||||
|
||||
.contributors
|
||||
tr
|
||||
|
||||
+260
-55
@@ -1,107 +1,312 @@
|
||||
#playground
|
||||
--playground-gap: 12px
|
||||
--playground-radius: 10px
|
||||
--playground-inset: 16px
|
||||
background: var(--color-content-bg)
|
||||
overflow: hidden
|
||||
box-shadow: var(--panel-shadow)
|
||||
|
||||
.wrapper
|
||||
margin-bottom: 40px
|
||||
margin-bottom: 32px
|
||||
@media mq-mobile
|
||||
margin-bottom: 20px
|
||||
|
||||
.playground-hero
|
||||
display: flex
|
||||
flex-wrap: wrap
|
||||
align-items: flex-end
|
||||
justify-content: space-between
|
||||
gap: 16px 24px
|
||||
padding-top: 32px
|
||||
padding-bottom: 20px
|
||||
@media mq-mobile
|
||||
padding-top: 16px
|
||||
padding-bottom: 12px
|
||||
gap: 10px
|
||||
align-items: flex-start
|
||||
|
||||
.playground-hero-text
|
||||
flex: 1 1 280px
|
||||
min-width: 0
|
||||
|
||||
h1
|
||||
font-size: 36px
|
||||
font-weight: 300
|
||||
margin-top: 40px
|
||||
margin-bottom: 24px
|
||||
color: var(--color-default)
|
||||
|
||||
h2
|
||||
font-size: 0.8125rem
|
||||
font-size: 28px
|
||||
font-weight: 600
|
||||
text-transform: uppercase
|
||||
letter-spacing: 0.04em
|
||||
color: var(--color-gray)
|
||||
letter-spacing: -0.02em
|
||||
margin: 0 0 8px
|
||||
color: var(--color-default)
|
||||
@media mq-mobile
|
||||
font-size: 22px
|
||||
margin-bottom: 4px
|
||||
|
||||
.playground-lead
|
||||
margin: 0
|
||||
font-size: 15px
|
||||
line-height: 1.5
|
||||
color: var(--color-gray)
|
||||
@media mq-mobile
|
||||
font-size: 14px
|
||||
line-height: 1.45
|
||||
|
||||
.playground-version
|
||||
flex: 0 0 auto
|
||||
margin: 0
|
||||
font-size: 12px
|
||||
line-height: 1.4
|
||||
font-family: font-mono
|
||||
padding: 6px 12px
|
||||
border-radius: 999px
|
||||
background: var(--playground-surface)
|
||||
border: 1px solid var(--color-border)
|
||||
color: var(--color-gray)
|
||||
a
|
||||
color: var(--color-default)
|
||||
text-decoration: none
|
||||
font-weight: 500
|
||||
&:hover
|
||||
color: var(--color-link)
|
||||
text-decoration: none
|
||||
|
||||
#editors
|
||||
display: grid
|
||||
overflow: hidden
|
||||
margin-bottom: 0
|
||||
height: 75vh
|
||||
min-height: 480px
|
||||
|
||||
.playground-workspace
|
||||
display: grid
|
||||
gap: var(--playground-gap)
|
||||
grid-template-columns: 1fr 1fr
|
||||
grid-template-rows: 3fr 2fr
|
||||
grid-gap: 16px
|
||||
align-items: stretch
|
||||
@media mq-normal
|
||||
overflow: hidden
|
||||
height: 75vh
|
||||
max-height: unquote('calc(100vh - 200px)')
|
||||
min-height: 520px
|
||||
@media mq-mobile
|
||||
height: auto
|
||||
min-height: 0
|
||||
grid-template-columns: 1fr
|
||||
grid-template-rows: auto
|
||||
grid-gap: 20px
|
||||
gap: 12px
|
||||
|
||||
.area-tpl
|
||||
grid-row: 1
|
||||
grid-column: 1
|
||||
min-height: 0
|
||||
--pane-dot: var(--color-link)
|
||||
.area-data
|
||||
grid-row: 2
|
||||
grid-column: 1
|
||||
min-height: 0
|
||||
--pane-dot: var(--highlight-orange)
|
||||
.area-output
|
||||
grid-column: 2
|
||||
grid-row: 1 / -1
|
||||
min-height: 0
|
||||
min-width: 0
|
||||
--pane-dot: var(--highlight-green)
|
||||
@media mq-mobile
|
||||
grid-row: auto
|
||||
grid-column: 1
|
||||
|
||||
.editor-wrapper
|
||||
.playground-pane
|
||||
display: flex
|
||||
gap: 8px
|
||||
flex-direction: column
|
||||
min-height: 0
|
||||
overflow: hidden
|
||||
.editor
|
||||
flex: 1 1 auto
|
||||
min-height: 0
|
||||
position: relative
|
||||
code-block-chrome()
|
||||
overflow: hidden
|
||||
@media mq-mobile
|
||||
min-height: 240px
|
||||
.ace_editor
|
||||
font-family: font-mono
|
||||
font-size: 14px
|
||||
line-height: 1.5
|
||||
border-radius: 6px
|
||||
.ace_scrollbar
|
||||
z-index: 2
|
||||
background: var(--playground-pane-head)
|
||||
border: 1px solid var(--code-border)
|
||||
border-radius: var(--playground-radius)
|
||||
box-shadow: var(--code-shadow)
|
||||
|
||||
.version
|
||||
font-size: 0.8125rem
|
||||
line-height: 1.5
|
||||
.pane-head
|
||||
display: flex
|
||||
align-items: center
|
||||
gap: 10px
|
||||
flex-shrink: 0
|
||||
height: 36px
|
||||
padding: 0 var(--playground-inset)
|
||||
border-bottom: 1px solid var(--code-border)
|
||||
@media mq-mobile
|
||||
height: 32px
|
||||
padding: 0 10px
|
||||
h2
|
||||
font-size: 13px
|
||||
font-weight: 600
|
||||
letter-spacing: 0.01em
|
||||
text-transform: none
|
||||
color: var(--color-default)
|
||||
margin: 0
|
||||
@media mq-mobile
|
||||
font-size: 12px
|
||||
|
||||
.pane-indicator
|
||||
width: 8px
|
||||
height: 8px
|
||||
border-radius: 50%
|
||||
flex-shrink: 0
|
||||
background: unquote('color-mix(in srgb, var(--pane-dot) 38%, var(--color-border))')
|
||||
transition: background 0.25s ease, box-shadow 0.25s ease, transform 0.25s ease
|
||||
|
||||
&[data-state="active"]
|
||||
background: var(--pane-dot)
|
||||
animation: playground-dot-typing 0.85s ease-in-out infinite
|
||||
|
||||
&[data-state="pending"]
|
||||
background: var(--highlight-yellow)
|
||||
|
||||
&[data-state="ok"]
|
||||
background: var(--highlight-green)
|
||||
animation: playground-dot-ok 0.45s ease-out
|
||||
|
||||
&[data-state="error"]
|
||||
background: var(--highlight-red)
|
||||
animation: playground-dot-error 0.35s ease-out
|
||||
|
||||
.area-output .pane-indicator
|
||||
&[data-state="pending"]
|
||||
animation: playground-dot-pending 0.55s ease-in-out infinite
|
||||
|
||||
@keyframes playground-dot-typing
|
||||
0%, 100%
|
||||
transform: scale(1)
|
||||
box-shadow: 0 0 0 0 unquote('color-mix(in srgb, var(--pane-dot) 0%, transparent)')
|
||||
50%
|
||||
transform: scale(1.2)
|
||||
box-shadow: 0 0 0 4px unquote('color-mix(in srgb, var(--pane-dot) 28%, transparent)')
|
||||
|
||||
@keyframes playground-dot-pending
|
||||
0%, 100%
|
||||
transform: scale(1)
|
||||
opacity: 0.75
|
||||
50%
|
||||
transform: scale(1.12)
|
||||
opacity: 1
|
||||
|
||||
@keyframes playground-dot-ok
|
||||
0%
|
||||
transform: scale(0.85)
|
||||
box-shadow: 0 0 0 0 unquote('color-mix(in srgb, var(--highlight-green) 50%, transparent)')
|
||||
70%
|
||||
transform: scale(1.15)
|
||||
box-shadow: 0 0 0 5px unquote('color-mix(in srgb, var(--highlight-green) 0%, transparent)')
|
||||
100%
|
||||
transform: scale(1)
|
||||
box-shadow: none
|
||||
|
||||
@keyframes playground-dot-error
|
||||
0%, 100%
|
||||
transform: translateX(0)
|
||||
20%
|
||||
transform: translateX(-2px)
|
||||
40%
|
||||
transform: translateX(2px)
|
||||
60%
|
||||
transform: translateX(-1px)
|
||||
80%
|
||||
transform: translateX(1px)
|
||||
|
||||
.pane-body
|
||||
flex: 1 1 auto
|
||||
min-height: 0
|
||||
min-width: 0
|
||||
display: flex
|
||||
flex-direction: column
|
||||
overflow: hidden
|
||||
background: var(--highlight-background)
|
||||
|
||||
.area-tpl .pane-body,
|
||||
.area-data .pane-body
|
||||
padding: var(--playground-inset)
|
||||
box-sizing: border-box
|
||||
@media mq-mobile
|
||||
padding: 12px
|
||||
|
||||
.area-tpl .ace_gutter,
|
||||
.area-data .ace_gutter
|
||||
display: none
|
||||
width: 0
|
||||
min-width: 0
|
||||
|
||||
.area-tpl .ace_editor,
|
||||
.area-data .ace_editor,
|
||||
.area-tpl .ace_scroller,
|
||||
.area-data .ace_scroller,
|
||||
.area-tpl .ace_content,
|
||||
.area-data .ace_content,
|
||||
.area-tpl .ace_text-layer,
|
||||
.area-data .ace_text-layer
|
||||
background: transparent
|
||||
|
||||
.editor
|
||||
flex: 1 1 auto
|
||||
min-height: 0
|
||||
position: relative
|
||||
overflow: hidden
|
||||
@media mq-mobile
|
||||
min-height: 180px
|
||||
|
||||
.output-preview
|
||||
flex: 1 1 auto
|
||||
min-height: 0
|
||||
min-width: 0
|
||||
width: 100%
|
||||
overflow: auto
|
||||
@media mq-mobile
|
||||
min-height: 120px
|
||||
pre.highlight
|
||||
margin: 0
|
||||
min-height: 100%
|
||||
width: 100%
|
||||
box-sizing: border-box
|
||||
padding: var(--playground-inset)
|
||||
border: none
|
||||
box-shadow: none
|
||||
border-radius: 0
|
||||
background: transparent
|
||||
color: var(--highlight-foreground)
|
||||
overflow-x: hidden
|
||||
overflow-y: auto
|
||||
white-space: pre-wrap
|
||||
overflow-wrap: break-word
|
||||
@media mq-mobile
|
||||
padding: 12px
|
||||
code
|
||||
display: block
|
||||
width: 100%
|
||||
box-sizing: border-box
|
||||
font-family: font-mono
|
||||
font-size: 14px
|
||||
line-height: 1.55
|
||||
color: var(--highlight-foreground)
|
||||
background: transparent
|
||||
padding: 0
|
||||
white-space: inherit
|
||||
overflow-wrap: inherit
|
||||
@media mq-mobile
|
||||
font-size: 13px
|
||||
|
||||
.ace_editor
|
||||
font-family: font-mono
|
||||
color: var(--color-gray)
|
||||
margin-top: 20px
|
||||
margin-bottom: 32px
|
||||
a
|
||||
color: inherit
|
||||
text-decoration: none
|
||||
&:hover
|
||||
color: var(--color-link)
|
||||
text-decoration: underline
|
||||
font-size: 14px
|
||||
line-height: 1.55
|
||||
border-radius: 0
|
||||
@media mq-mobile
|
||||
font-size: 13px
|
||||
.ace_scrollbar
|
||||
z-index: 2
|
||||
|
||||
.hide
|
||||
display: none
|
||||
|
||||
.loader
|
||||
width: 48px
|
||||
height: 48px
|
||||
margin: 150px auto 200px
|
||||
border: 3px solid var(--color-border)
|
||||
width: 40px
|
||||
height: 40px
|
||||
margin: 120px auto 160px
|
||||
border: 2px solid var(--color-border)
|
||||
border-top-color: var(--color-link)
|
||||
border-radius: 50%
|
||||
animation: spin 0.8s infinite linear
|
||||
animation: playground-spin 0.7s infinite linear
|
||||
@media mq-mobile
|
||||
margin: 60px auto 80px
|
||||
|
||||
@keyframes spin
|
||||
@keyframes playground-spin
|
||||
100%
|
||||
transform: rotate(360deg)
|
||||
|
||||
+4
@@ -37,6 +37,8 @@ vendor-prefixes = webkit moz ms official
|
||||
--highlight-aqua: #0550ae
|
||||
--highlight-blue: #0550ae
|
||||
--highlight-purple: #8250df
|
||||
--playground-surface: #f3f4f6
|
||||
--playground-pane-head: #fff
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
@@ -75,6 +77,8 @@ vendor-prefixes = webkit moz ms official
|
||||
--highlight-aqua: #79c0ff
|
||||
--highlight-blue: #79c0ff
|
||||
--highlight-purple: #d2a8ff
|
||||
--playground-surface: hsl(218, 26%, 10%)
|
||||
--playground-pane-head: hsl(218, 22%, 16%)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -9,6 +9,7 @@
|
||||
@import "_partial/page"
|
||||
@import "_partial/mobile_nav"
|
||||
@import "_partial/footer"
|
||||
@import "_partial/cookieconsent"
|
||||
@import "_partial/highlight"
|
||||
@import "_partial/icomoon.css"
|
||||
@import "_partial/docsearch.min.css"
|
||||
@@ -0,0 +1,49 @@
|
||||
(function () {
|
||||
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
|
||||
document.documentElement.classList.add('cc--darkmode');
|
||||
}
|
||||
|
||||
var config = {
|
||||
guiOptions: {
|
||||
consentModal: {
|
||||
equalWeightButtons: false
|
||||
}
|
||||
},
|
||||
categories: {
|
||||
necessary: {
|
||||
enabled: true,
|
||||
readOnly: true
|
||||
},
|
||||
analytics: {
|
||||
enabled: false
|
||||
}
|
||||
},
|
||||
language: {
|
||||
default: 'en',
|
||||
translations: {
|
||||
en: {
|
||||
consentModal: {
|
||||
title: 'We use cookies',
|
||||
description: 'This site uses cookies for analytics and to improve your experience.',
|
||||
acceptAllBtn: 'Accept',
|
||||
acceptNecessaryBtn: 'Reject'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (/^localhost$|^127\.0\.0\.1$/i.test(location.hostname)) {
|
||||
config.cookie = { secure: false };
|
||||
}
|
||||
|
||||
function run() {
|
||||
CookieConsent.run(config);
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', run);
|
||||
} else {
|
||||
run();
|
||||
}
|
||||
}());
|
||||
Vendored
+120
-18
@@ -38,24 +38,28 @@
|
||||
|
||||
(function() {
|
||||
// playground
|
||||
/* global liquidjs, ace */
|
||||
if (!location.pathname.match(/playground.html$/)) return;
|
||||
/* global liquidjs, ace, Prism */
|
||||
if (!/\/playground(?:\.html)?$/.test(location.pathname)) return;
|
||||
updateVersion(liquidjs.version);
|
||||
const engine = new liquidjs.Liquid({
|
||||
memoryLimit: 1e5,
|
||||
renderLimit: 1e5
|
||||
templateLimit: 1e5
|
||||
});
|
||||
const colorScheme = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const editor = createEditor('editorEl', 'liquid');
|
||||
const dataEditor = createEditor('dataEl', 'json');
|
||||
const preview = createEditor('previewEl', 'html');
|
||||
preview.setReadOnly(true);
|
||||
preview.renderer.setShowGutter(false);
|
||||
preview.renderer.setPadding(16);
|
||||
const previewCode = document.getElementById('previewCode');
|
||||
const indicatorTpl = document.querySelector('.area-tpl .pane-indicator');
|
||||
const indicatorData = document.querySelector('.area-data .pane-indicator');
|
||||
const indicatorOutput = document.querySelector('.area-output .pane-indicator');
|
||||
|
||||
const editors = [editor, dataEditor, preview];
|
||||
const editors = [editor, dataEditor];
|
||||
let previewValue = '';
|
||||
let hadPreview = false;
|
||||
let renderTimer = null;
|
||||
const RENDER_DELAY = 180;
|
||||
colorScheme.addEventListener('change', function() {
|
||||
editors.forEach(applyEditorTheme);
|
||||
if (previewValue) setPreview(previewValue);
|
||||
});
|
||||
|
||||
const init = parseArgs(location.hash.slice(1));
|
||||
@@ -63,9 +67,11 @@
|
||||
editor.setValue(init.tpl, 1);
|
||||
dataEditor.setValue(init.data, 1);
|
||||
}
|
||||
editor.on('change', update);
|
||||
dataEditor.on('change', update);
|
||||
update();
|
||||
editor.on('change', onTemplateChange);
|
||||
dataEditor.on('change', onContextChange);
|
||||
editor.on('focus', function () { setIndicator(indicatorTpl, 'active'); });
|
||||
dataEditor.on('focus', function () { setIndicator(indicatorData, 'active'); });
|
||||
scheduleUpdate();
|
||||
ready();
|
||||
|
||||
function ready() {
|
||||
@@ -87,6 +93,8 @@
|
||||
|
||||
function applyEditorTheme(editor) {
|
||||
editor.setTheme(getEditorTheme());
|
||||
editor.renderer.setPadding(0);
|
||||
editor.container.style.background = 'transparent';
|
||||
}
|
||||
|
||||
function createEditor(id, lang) {
|
||||
@@ -96,15 +104,61 @@
|
||||
fontFamily: '"Source Code Pro", ui-monospace, Monaco, Menlo, Consolas, monospace',
|
||||
fontSize: '14px',
|
||||
showPrintMargin: false,
|
||||
showGutter: false,
|
||||
highlightActiveLine: false,
|
||||
tabSize: 2,
|
||||
useSoftTabs: true,
|
||||
scrollPastEnd: 0.25
|
||||
scrollPastEnd: 0
|
||||
});
|
||||
editor.getSession().setMode('ace/mode/' + lang);
|
||||
editor.renderer.setScrollMargin(8, 8, 0, 0);
|
||||
editor.renderer.setShowGutter(false);
|
||||
if (editor.renderer.$gutter) {
|
||||
editor.renderer.$gutter.style.display = 'none';
|
||||
}
|
||||
editor.renderer.setScrollMargin(0, 0, 0, 0);
|
||||
bindClipboard(editor);
|
||||
return editor;
|
||||
}
|
||||
|
||||
function bindClipboard(editor) {
|
||||
editor.commands.addCommand({
|
||||
name: 'copy',
|
||||
bindKey: {win: 'Ctrl-C', mac: 'Command-C'},
|
||||
exec: function (ed) {
|
||||
const text = ed.getCopyText();
|
||||
if (!text) return;
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
navigator.clipboard.writeText(text);
|
||||
}
|
||||
},
|
||||
readOnly: true
|
||||
});
|
||||
editor.commands.addCommand({
|
||||
name: 'cut',
|
||||
bindKey: {win: 'Ctrl-X', mac: 'Command-X'},
|
||||
exec: function (ed) {
|
||||
const text = ed.getCopyText();
|
||||
if (!text) return;
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
navigator.clipboard.writeText(text).then(function () {
|
||||
ed.insert('');
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
editor.commands.addCommand({
|
||||
name: 'paste',
|
||||
bindKey: {win: 'Ctrl-V', mac: 'Command-V'},
|
||||
exec: function (ed) {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
navigator.clipboard.readText().then(function (text) {
|
||||
ed.insert(text);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function parseArgs(hash) {
|
||||
if (!hash) return;
|
||||
try {
|
||||
@@ -118,16 +172,64 @@
|
||||
return utoa(obj.tpl) + ',' + utoa(obj.data);
|
||||
}
|
||||
|
||||
function setPreview(value) {
|
||||
previewValue = value;
|
||||
previewCode.textContent = value;
|
||||
if (window.Prism) {
|
||||
delete previewCode.dataset.highlighted;
|
||||
window.Prism.highlightElement(previewCode);
|
||||
}
|
||||
}
|
||||
|
||||
function setIndicator(indicator, state) {
|
||||
if (indicator) indicator.dataset.state = state;
|
||||
}
|
||||
|
||||
function onTemplateChange() {
|
||||
setIndicator(indicatorTpl, 'active');
|
||||
if (indicatorData.dataset.state !== 'error') setIndicator(indicatorData, 'idle');
|
||||
setIndicator(indicatorOutput, 'pending');
|
||||
scheduleUpdate();
|
||||
}
|
||||
|
||||
function onContextChange() {
|
||||
setIndicator(indicatorData, 'active');
|
||||
if (indicatorTpl.dataset.state !== 'error') setIndicator(indicatorTpl, 'idle');
|
||||
setIndicator(indicatorOutput, 'pending');
|
||||
scheduleUpdate();
|
||||
}
|
||||
|
||||
function scheduleUpdate() {
|
||||
clearTimeout(renderTimer);
|
||||
renderTimer = setTimeout(update, RENDER_DELAY);
|
||||
}
|
||||
|
||||
async function update() {
|
||||
const tpl = editor.getValue();
|
||||
const data = dataEditor.getValue();
|
||||
history.replaceState({}, '', '#' + serializeArgs({tpl, data}));
|
||||
let parsed;
|
||||
try {
|
||||
const html = await engine.parseAndRender(tpl, JSON.parse(data));
|
||||
preview.setValue(html, 1);
|
||||
parsed = JSON.parse(data);
|
||||
} catch (err) {
|
||||
preview.setValue(err.stack, 1);
|
||||
throw err;
|
||||
setIndicator(indicatorData, 'error');
|
||||
setIndicator(indicatorTpl, 'idle');
|
||||
setIndicator(indicatorOutput, 'error');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const html = await engine.parseAndRender(tpl, parsed);
|
||||
if (html !== '' || !hadPreview) {
|
||||
setPreview(html);
|
||||
if (html !== '') hadPreview = true;
|
||||
}
|
||||
setIndicator(indicatorTpl, 'idle');
|
||||
setIndicator(indicatorData, 'idle');
|
||||
setIndicator(indicatorOutput, 'ok');
|
||||
} catch (err) {
|
||||
setIndicator(indicatorTpl, 'error');
|
||||
setIndicator(indicatorData, 'idle');
|
||||
setIndicator(indicatorOutput, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Generated
+3
-3
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "liquidjs",
|
||||
"version": "10.27.0",
|
||||
"version": "10.27.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "liquidjs",
|
||||
"version": "10.27.0",
|
||||
"version": "10.27.1",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"commander": "^10.0.0"
|
||||
@@ -64,7 +64,7 @@
|
||||
"typescript": "^4.5.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
"node": ">=20"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
|
||||
+8
-44
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "liquidjs",
|
||||
"version": "10.27.0",
|
||||
"version": "10.27.1",
|
||||
"sideEffects": false,
|
||||
"description": "A simple, expressive and safe Shopify / Github Pages compatible template engine in pure JavaScript.",
|
||||
"description": "A simple, expressive, extensible Liquid template engine for JavaScript — Shopify, Jekyll and GitHub Pages compatible, for Node.js, browsers, and the CLI, with TypeScript support.",
|
||||
"main": "dist/liquid.node.js",
|
||||
"module": "dist/liquid.node.mjs",
|
||||
"es2015": "dist/liquid.browser.mjs",
|
||||
@@ -12,7 +12,7 @@
|
||||
},
|
||||
"types": "dist/index.d.ts",
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
"node": ">=20"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint \"**/*.mjs\" \"**/*.ts\" .",
|
||||
@@ -29,12 +29,15 @@
|
||||
"build:min": "BUNDLES=min rollup -c rollup.config.mjs",
|
||||
"build:umd": "BUNDLES=umd rollup -c rollup.config.mjs",
|
||||
"build:charmap": "./bin/character-gen.js > src/util/character.ts",
|
||||
"build:docs": "run-s build:docs-liquid build:contributors build:apidoc build:changelog build:docs-hexo",
|
||||
"prepare:docs": "run-s build:docs-liquid build:contributors build:apidoc build:changelog",
|
||||
"build:docs": "run-s prepare:docs build:docs-hexo",
|
||||
"build:docs-liquid": "cross-env BUNDLES=min rollup -c rollup.config.mjs && shx cp dist/liquid.browser.min.js docs/themes/navy/source/js/",
|
||||
"build:contributors": "node bin/build-contributors.js",
|
||||
"build:apidoc": "shx rm -rf docs/source/api && typedoc --plugin typedoc-plugin-missing-exports ./src --gitRevision master --out docs/source/api",
|
||||
"build:changelog": "node bin/build-changelog.js",
|
||||
"build:docs-hexo": "cd docs && npm ci && npm run build && shx cp CNAME public/"
|
||||
"build:docs-hexo": "cd docs && npm ci && npm run build && shx cp CNAME public/",
|
||||
"serve:docs": "cd docs && npm run start",
|
||||
"dev:docs": "run-s prepare:docs serve:docs"
|
||||
},
|
||||
"bin": {
|
||||
"liquidjs": "./bin/liquid.js",
|
||||
@@ -118,45 +121,6 @@
|
||||
"dependencies": {
|
||||
"commander": "^10.0.0"
|
||||
},
|
||||
"release": {
|
||||
"branch": "master",
|
||||
"plugins": [
|
||||
"@semantic-release/commit-analyzer",
|
||||
"@semantic-release/release-notes-generator",
|
||||
"@semantic-release/changelog",
|
||||
"@semantic-release/npm",
|
||||
[
|
||||
"@semantic-release/git",
|
||||
{
|
||||
"assets": [
|
||||
"package.json",
|
||||
"package-lock.json",
|
||||
"CHANGELOG.md"
|
||||
],
|
||||
"message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
|
||||
}
|
||||
],
|
||||
[
|
||||
"@semantic-release/github",
|
||||
{
|
||||
"assets": [
|
||||
{
|
||||
"path": "dist/*.umd.js",
|
||||
"label": "liquid.js"
|
||||
},
|
||||
{
|
||||
"path": "dist/*.min.js",
|
||||
"label": "liquid.min.js"
|
||||
},
|
||||
{
|
||||
"path": "dist/*.min.js.map",
|
||||
"label": "liquid.min.js.map"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
]
|
||||
},
|
||||
"publishConfig": {
|
||||
"provenance": true
|
||||
},
|
||||
|
||||
+5
-6
@@ -23,8 +23,7 @@ const tsconfig = (target) => ({
|
||||
compilerOptions: {
|
||||
target,
|
||||
module: 'ES2015',
|
||||
rootDir: 'src',
|
||||
downlevelIteration: true
|
||||
rootDir: 'src'
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -89,7 +88,7 @@ const nodeEsm = {
|
||||
plugins: [
|
||||
versionInjection,
|
||||
replace(esmRequire),
|
||||
typescript(tsconfig('es6'))
|
||||
typescript(tsconfig('ES2020'))
|
||||
],
|
||||
treeshake,
|
||||
input
|
||||
@@ -108,7 +107,7 @@ const browserEsm = {
|
||||
replace(browserBase64),
|
||||
replace(browserCrypto),
|
||||
replace(browserStream),
|
||||
typescript(tsconfig('es6'))
|
||||
typescript(tsconfig('ES2020'))
|
||||
],
|
||||
treeshake,
|
||||
input
|
||||
@@ -128,7 +127,7 @@ const browserUmd = {
|
||||
replace(browserBase64),
|
||||
replace(browserCrypto),
|
||||
replace(browserStream),
|
||||
typescript(tsconfig('es5'))
|
||||
typescript(tsconfig('ES2020'))
|
||||
],
|
||||
treeshake,
|
||||
input
|
||||
@@ -148,7 +147,7 @@ const browserMin = {
|
||||
replace(browserBase64),
|
||||
replace(browserCrypto),
|
||||
replace(browserStream),
|
||||
typescript(tsconfig('es5')),
|
||||
typescript(tsconfig('ES2020')),
|
||||
uglify()
|
||||
],
|
||||
treeshake,
|
||||
|
||||
@@ -2,11 +2,6 @@ import * as base64 from './base64-impl-browser'
|
||||
import { JSDOM } from 'jsdom'
|
||||
|
||||
describe('base64-impl/browser', function () {
|
||||
if (+(process.version.match(/^v(\d+)/) as RegExpMatchArray)[1] < 8) {
|
||||
console.info('jsdom not supported, skipping base64-impl-browser...')
|
||||
return
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
const dom = new JSDOM(``, {
|
||||
url: 'https://example.com/',
|
||||
|
||||
@@ -3,10 +3,6 @@ import * as sinon from 'sinon'
|
||||
import { JSDOM } from 'jsdom'
|
||||
|
||||
describe('fs/browser', function () {
|
||||
if (+(process.version.match(/^v(\d+)/) as RegExpMatchArray)[1] < 8) {
|
||||
console.info('jsdom not supported, skipping template-browser...')
|
||||
return
|
||||
}
|
||||
beforeEach(function () {
|
||||
const dom = new JSDOM(``, {
|
||||
url: 'https://example.com/foo/bar/',
|
||||
|
||||
@@ -58,6 +58,9 @@ describe('Context', function () {
|
||||
it('should return map size as size', async function () {
|
||||
expect(ctx.get(['map', 'size'])).toEqual(1)
|
||||
})
|
||||
it('should return own size property', async function () {
|
||||
expect(ctx.get(['zoo', 'size'])).toEqual(4)
|
||||
})
|
||||
it('should return undefined if not have a size', async function () {
|
||||
expect(ctx.get(['one', 'size'])).toBeUndefined()
|
||||
expect(ctx.get(['non-exist', 'size'])).toBeUndefined()
|
||||
@@ -130,6 +133,10 @@ describe('Context', function () {
|
||||
ctx = new Context({ foo: Object.create({ bar: 'BAR' }) }, { ownPropertyOnly: false } as any)
|
||||
return expect(ctx.getSync(['foo', 'bar'])).toEqual('BAR')
|
||||
})
|
||||
it('should read inherited size when ownPropertyOnly=false', function () {
|
||||
ctx = new Context({ foo: Object.create({ size: 99 }) }, { ownPropertyOnly: false } as any)
|
||||
return expect(ctx.getSync(['foo', 'size'])).toEqual(99)
|
||||
})
|
||||
it('renderOptions.ownPropertyOnly should override options.ownPropertyOnly', function () {
|
||||
ctx = new Context({ foo: Object.create({ bar: 'BAR' }) }, { ownPropertyOnly: false } as any, { ownPropertyOnly: true })
|
||||
return expect(ctx.getSync(['foo', 'bar'])).toEqual(undefined)
|
||||
@@ -183,6 +190,51 @@ describe('Context', function () {
|
||||
ctx.push({ foo: Object.create({ bar: 'BAR' }) })
|
||||
return expect(() => ctx.getSync(['foo', 'bar'])).toThrow(/undefined variable: foo.bar/)
|
||||
})
|
||||
it('should return undefined for inherited array indices', function () {
|
||||
// eslint-disable-next-line no-extend-native
|
||||
Array.prototype[0] = 'POLLUTED'
|
||||
try {
|
||||
const a: number[] = []
|
||||
a.length = 1
|
||||
ctx.push({ foo: a })
|
||||
expect(ctx.getSync(['foo', 0])).toEqual(undefined)
|
||||
expect(ctx.getSync(['foo', -1])).toEqual(undefined)
|
||||
expect(ctx.getSync(['foo', 'first'])).toEqual(undefined)
|
||||
expect(ctx.getSync(['foo', 'last'])).toEqual(undefined)
|
||||
} finally {
|
||||
delete (Array.prototype as any)[0]
|
||||
}
|
||||
})
|
||||
it('should allow own blocked keys when ownPropertyOnly=false', function () {
|
||||
ctx = new Context({
|
||||
foo: {
|
||||
...JSON.parse('{"__proto__": {"bar": "BAR"}}'),
|
||||
constructor: { name: 'Custom' },
|
||||
prototype: { x: 1 }
|
||||
}
|
||||
}, { ownPropertyOnly: false } as any)
|
||||
expect(ctx.getSync(['foo', '__proto__', 'bar'])).toEqual('BAR')
|
||||
expect(ctx.getSync(['foo', 'constructor', 'name'])).toEqual('Custom')
|
||||
expect(ctx.getSync(['foo', 'prototype', 'x'])).toEqual(1)
|
||||
})
|
||||
it('should allow inherited properties when ownPropertyOnly=false', function () {
|
||||
ctx = new Context({ foo: Object.create({ __proto__: { bar: 'BAR' }, constructor: { name: 'Evil' } }) }, { ownPropertyOnly: false } as any)
|
||||
expect(ctx.getSync(['foo', '__proto__', '__proto__', 'bar'])).toEqual('BAR')
|
||||
expect(ctx.getSync(['foo', 'constructor', 'name'])).toEqual('Evil')
|
||||
})
|
||||
it('should block own constructor when ownPropertyOnly=true', function () {
|
||||
ctx.push({ foo: { constructor: { name: 'Evil' } } })
|
||||
expect(ctx.getSync(['foo', 'constructor'])).toEqual(undefined)
|
||||
})
|
||||
it('should block own prototype when ownPropertyOnly=true', function () {
|
||||
ctx.push({ foo: { prototype: { bar: 'BAR' } } })
|
||||
expect(ctx.getSync(['foo', 'prototype'])).toEqual(undefined)
|
||||
})
|
||||
it('should block own top-level __proto__ variable when ownPropertyOnly=true', function () {
|
||||
ctx = new Context(JSON.parse('{"__proto__": {"bar": "BAR"}, "bar": "BAR"}'))
|
||||
expect(ctx.getSync(['__proto__'])).toEqual(undefined)
|
||||
expect(ctx.getSync(['bar'])).toEqual('BAR')
|
||||
})
|
||||
})
|
||||
|
||||
describe('.getAll()', function () {
|
||||
@@ -206,6 +258,11 @@ describe('Context', function () {
|
||||
expect(ctx.getSync(['bar', 'foo'])).toEqual('foo')
|
||||
expect(ctx.getSync(['bar', 'bar'])).toEqual(undefined)
|
||||
})
|
||||
it('should return pushed scope for in-place mutation', function () {
|
||||
const scope = ctx.push({})
|
||||
scope.item = 'ITEM'
|
||||
expect(ctx.getSync(['item'])).toEqual('ITEM')
|
||||
})
|
||||
})
|
||||
describe('.pop()', function () {
|
||||
it('should pop scope', async function () {
|
||||
|
||||
+39
-33
@@ -1,12 +1,13 @@
|
||||
import { getPerformance } from '../util/performance'
|
||||
import { Drop } from '../drop/drop'
|
||||
import { __assign } from 'tslib'
|
||||
import { NormalizedFullOptions, defaultOptions, RenderOptions } from '../liquid-options'
|
||||
import { createScope, Scope } from './scope'
|
||||
import { hasOwnProperty, isArray, isNil, isUndefined, isString, isFunction, toLiquid, InternalUndefinedVariableError, toValueSync, isObject, Limiter, toValue } from '../util'
|
||||
import { hasOwnProperty, isArray, isNil, isUndefined, isString, isFunction, isNumber, toLiquid, InternalUndefinedVariableError, toValueSync, isObject, Limiter, toValue, readArrayElement } from '../util'
|
||||
|
||||
type PropertyKey = string | number;
|
||||
|
||||
const BLOCKED_SCOPE_KEYS: ReadonlySet<PropertyKey> = new Set(['__proto__', 'constructor', 'prototype'])
|
||||
|
||||
export class Context {
|
||||
/**
|
||||
* insert a Context-level empty scope,
|
||||
@@ -36,17 +37,19 @@ export class Context {
|
||||
*/
|
||||
public strictVariables: boolean;
|
||||
public ownPropertyOnly: boolean;
|
||||
public memoryLimit: Limiter;
|
||||
public renderLimit: Limiter;
|
||||
public constructor (env: object = {}, opts: NormalizedFullOptions = defaultOptions, renderOptions: RenderOptions = {}, { memoryLimit, renderLimit }: { [key: string]: Limiter } = {}) {
|
||||
public templateLimit: Limiter;
|
||||
public outputLengthLimit: Limiter;
|
||||
public depthLimit: Limiter;
|
||||
public constructor (env: object = {}, opts: NormalizedFullOptions = defaultOptions, renderOptions: RenderOptions = {}, { templateLimit, outputLengthLimit, depthLimit }: { templateLimit?: Limiter, outputLengthLimit?: Limiter, depthLimit?: Limiter } = {}) {
|
||||
this.sync = !!renderOptions.sync
|
||||
this.opts = opts
|
||||
this.globals = renderOptions.globals ?? opts.globals
|
||||
this.environments = isObject(env) ? env : Object(env)
|
||||
this.strictVariables = renderOptions.strictVariables ?? this.opts.strictVariables
|
||||
this.ownPropertyOnly = renderOptions.ownPropertyOnly ?? opts.ownPropertyOnly
|
||||
this.memoryLimit = memoryLimit ?? new Limiter('memory alloc', renderOptions.memoryLimit ?? opts.memoryLimit)
|
||||
this.renderLimit = renderLimit ?? new Limiter('template render', getPerformance().now() + (renderOptions.renderLimit ?? opts.renderLimit))
|
||||
this.templateLimit = templateLimit ?? new Limiter('template', renderOptions.templateLimit ?? opts.templateLimit)
|
||||
this.outputLengthLimit = outputLengthLimit ?? new Limiter('output length', renderOptions.outputLengthLimit ?? opts.outputLengthLimit)
|
||||
this.depthLimit = depthLimit ?? new Limiter('template depth', opts.maxDepth)
|
||||
}
|
||||
public getRegister<T> (key: string, defaultValue: T = undefined as T): T {
|
||||
return (this.registers[key] = this.registers[key] || defaultValue)
|
||||
@@ -93,8 +96,10 @@ export class Context {
|
||||
}
|
||||
return scope
|
||||
}
|
||||
public push (ctx: object) {
|
||||
return this.scopes.push(ctx)
|
||||
public push (ctx: Scope): Scope {
|
||||
const scope = createScope(ctx)
|
||||
this.scopes.push(scope)
|
||||
return scope
|
||||
}
|
||||
public pop () {
|
||||
return this.scopes.pop()
|
||||
@@ -109,50 +114,51 @@ export class Context {
|
||||
strictVariables: this.strictVariables,
|
||||
ownPropertyOnly: this.ownPropertyOnly
|
||||
}, {
|
||||
renderLimit: this.renderLimit,
|
||||
memoryLimit: this.memoryLimit
|
||||
templateLimit: this.templateLimit,
|
||||
outputLengthLimit: this.outputLengthLimit,
|
||||
depthLimit: this.depthLimit
|
||||
})
|
||||
}
|
||||
private findScope (key: string | number) {
|
||||
for (let i = this.scopes.length - 1; i >= 0; i--) {
|
||||
const candidate = this.scopes[i]
|
||||
if (key in candidate) return candidate
|
||||
if (this.ownPropertyOnly ? hasOwnProperty.call(candidate, key) : key in candidate) return candidate
|
||||
}
|
||||
if (key in this.environments) return this.environments
|
||||
if (this.ownPropertyOnly ? hasOwnProperty.call(this.environments, key) : key in this.environments) return this.environments
|
||||
return this.globals
|
||||
}
|
||||
readProperty (obj: Scope, key: (PropertyKey | Drop)) {
|
||||
obj = toLiquid(obj)
|
||||
key = toValue(key) as PropertyKey
|
||||
if (isNil(obj)) return obj
|
||||
if (isArray(obj) && (key as number) < 0) return obj[obj.length + +key]
|
||||
if (isArray(obj) && isNumber(key)) return readArrayElement(obj, key, this.ownPropertyOnly)
|
||||
const value = readJSProperty(obj, key, this.ownPropertyOnly)
|
||||
if (value === undefined && obj instanceof Drop) return obj.liquidMethodMissing(key, this)
|
||||
if (isFunction(value)) return value.call(obj)
|
||||
if (key === 'size') return readSize(obj)
|
||||
else if (key === 'first') return readFirst(obj)
|
||||
else if (key === 'last') return readLast(obj)
|
||||
if (key === 'size') return this.readSize(obj)
|
||||
else if (key === 'first') return this.readFirst(obj)
|
||||
else if (key === 'last') return this.readLast(obj)
|
||||
return value
|
||||
}
|
||||
private readFirst (obj: Scope) {
|
||||
if (isArray(obj)) return readArrayElement(obj, 0, this.ownPropertyOnly)
|
||||
return readJSProperty(obj, 'first', this.ownPropertyOnly)
|
||||
}
|
||||
private readLast (obj: Scope) {
|
||||
if (isArray(obj)) return readArrayElement(obj, -1, this.ownPropertyOnly)
|
||||
return readJSProperty(obj, 'last', this.ownPropertyOnly)
|
||||
}
|
||||
private readSize (obj: Scope) {
|
||||
if (hasOwnProperty.call(obj, 'size')) return obj['size']
|
||||
if (!this.ownPropertyOnly && obj['size'] !== undefined) return obj['size']
|
||||
if (isArray(obj) || isString(obj)) return obj.length
|
||||
if (obj instanceof Map || obj instanceof Set) return obj.size
|
||||
if (typeof obj === 'object') return Object.keys(obj).length
|
||||
}
|
||||
}
|
||||
|
||||
export function readJSProperty (obj: Scope, key: PropertyKey, ownPropertyOnly: boolean) {
|
||||
if (BLOCKED_SCOPE_KEYS.has(key) && ownPropertyOnly) return undefined
|
||||
if (ownPropertyOnly && !hasOwnProperty.call(obj, key) && !(obj instanceof Drop)) return undefined
|
||||
return obj[key]
|
||||
}
|
||||
|
||||
function readFirst (obj: Scope) {
|
||||
if (isArray(obj)) return obj[0]
|
||||
return obj['first']
|
||||
}
|
||||
|
||||
function readLast (obj: Scope) {
|
||||
if (isArray(obj)) return obj[obj.length - 1]
|
||||
return obj['last']
|
||||
}
|
||||
|
||||
function readSize (obj: Scope) {
|
||||
if (hasOwnProperty.call(obj, 'size') || obj['size'] !== undefined) return obj['size']
|
||||
if (isArray(obj) || isString(obj)) return obj.length
|
||||
if (typeof obj === 'object') return Object.keys(obj).length
|
||||
}
|
||||
|
||||
@@ -6,8 +6,7 @@ export interface ScopeObject extends Record<string | number | symbol, any> {
|
||||
|
||||
export type Scope = ScopeObject | Drop
|
||||
|
||||
export function createScope (from?: ScopeObject): ScopeObject {
|
||||
const scope = Object.create(null)
|
||||
if (from) Object.assign(scope, from)
|
||||
return scope
|
||||
export function createScope (from?: Scope): Scope {
|
||||
if (from instanceof Drop) return from
|
||||
return Object.assign(Object.create(null), from)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
export * from './emitter'
|
||||
export * from './simple-emitter'
|
||||
export * from './streamed-emitter'
|
||||
export * from './keeping-type-emitter'
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import { stringify, toValue } from '../util'
|
||||
import { Emitter } from './emitter'
|
||||
|
||||
export class KeepingTypeEmitter implements Emitter {
|
||||
public buffer: any = '';
|
||||
|
||||
public write (html: any) {
|
||||
html = toValue(html)
|
||||
// This will only preserve the type if the value is isolated.
|
||||
// I.E:
|
||||
// {{ my-port }} -> 42
|
||||
// {{ my-host }}:{{ my-port }} -> 'host:42'
|
||||
if (typeof html !== 'string' && this.buffer === '') {
|
||||
this.buffer = html
|
||||
} else {
|
||||
this.buffer = stringify(this.buffer) + stringify(html)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,17 @@
|
||||
import { stringify } from '../util'
|
||||
import { stringify, Limiter } from '../util'
|
||||
import { Emitter } from './emitter'
|
||||
|
||||
export class SimpleEmitter implements Emitter {
|
||||
public buffer = '';
|
||||
private outputLengthLimit?: Limiter
|
||||
|
||||
constructor (outputLengthLimit?: Limiter) {
|
||||
this.outputLengthLimit = outputLengthLimit
|
||||
}
|
||||
|
||||
public write (html: any) {
|
||||
this.buffer += stringify(html)
|
||||
const str = stringify(html)
|
||||
this.outputLengthLimit?.use(str.length)
|
||||
this.buffer += str
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { stringify } from '../util'
|
||||
import { stringify, Limiter } from '../util'
|
||||
import { Emitter } from './emitter'
|
||||
import { PassThrough } from 'stream'
|
||||
|
||||
export class StreamedEmitter implements Emitter {
|
||||
public buffer = '';
|
||||
public stream: NodeJS.ReadWriteStream = new PassThrough()
|
||||
private outputLengthLimit?: Limiter
|
||||
|
||||
constructor (outputLengthLimit?: Limiter) {
|
||||
this.outputLengthLimit = outputLengthLimit
|
||||
}
|
||||
|
||||
public write (html: any) {
|
||||
this.stream.write(stringify(html))
|
||||
const str = stringify(html)
|
||||
this.outputLengthLimit?.use(str.length)
|
||||
this.stream.write(str)
|
||||
}
|
||||
public error (err: Error) {
|
||||
this.stream.emit('error', err)
|
||||
|
||||
+15
-26
@@ -1,4 +1,4 @@
|
||||
import { toArray, argumentsToValue, toValue, stringify, caseInsensitiveCompare, orderedCompare, isArray, isNil, last as arrayLast, isArrayLike, toEnumerable } from '../util'
|
||||
import { toArray, argumentsToValue, toValue, stringify, caseInsensitiveCompare, orderedCompare, isArray, isNil, isArrayLike, readArrayElement, toEnumerable } from '../util'
|
||||
import { arrayIncludes, equals, evalToken, isTruthy } from '../render'
|
||||
import { Value, FilterImpl } from '../template'
|
||||
import { Tokenizer } from '../parser'
|
||||
@@ -8,22 +8,22 @@ import { EmptyDrop } from '../drop'
|
||||
export const join = argumentsToValue(function (this: FilterImpl, v: any[], arg: string) {
|
||||
const array = toArray(v)
|
||||
const sep = isNil(arg) ? ' ' : stringify(arg)
|
||||
const complexity = array.length * (1 + sep.length)
|
||||
this.context.memoryLimit.use(complexity)
|
||||
return array.join(sep)
|
||||
return Array.prototype.join.call(array, sep)
|
||||
})
|
||||
export const last = argumentsToValue(function (this: FilterImpl, v: any) {
|
||||
return isArrayLike(v) ? readArrayElement(v, -1, this.context.ownPropertyOnly) : ''
|
||||
})
|
||||
export const first = argumentsToValue(function (this: FilterImpl, v: any) {
|
||||
return isArrayLike(v) ? readArrayElement(v, 0, this.context.ownPropertyOnly) : ''
|
||||
})
|
||||
export const last = argumentsToValue((v: any) => isArrayLike(v) ? arrayLast(v) : '')
|
||||
export const first = argumentsToValue((v: any) => isArrayLike(v) ? v[0] : '')
|
||||
export const reverse = argumentsToValue(function (this: FilterImpl, v: any[]) {
|
||||
const array = toArray(v)
|
||||
this.context.memoryLimit.use(array.length)
|
||||
return [...array].reverse()
|
||||
})
|
||||
|
||||
function * sortBy<T> (this: FilterImpl, arr: T[], property: string | undefined, comparator: (a: unknown, b: unknown) => number): IterableIterator<unknown> {
|
||||
const values: [T, unknown][] = []
|
||||
const array = toArray(arr)
|
||||
this.context.memoryLimit.use(array.length)
|
||||
for (const item of array) {
|
||||
values.push([
|
||||
item,
|
||||
@@ -41,12 +41,11 @@ export function * sort_natural<T> (this: FilterImpl, arr: T[], property?: string
|
||||
return yield * sortBy.call(this, arr, property, caseInsensitiveCompare)
|
||||
}
|
||||
|
||||
export const size = (v: string | any[]) => (v && v.length) || 0
|
||||
export const size = (v: string | any[]) => v?.length || 0
|
||||
|
||||
export function * map (this: FilterImpl, arr: Scope[], property: string): IterableIterator<unknown> {
|
||||
const results = []
|
||||
const array = toArray(arr)
|
||||
this.context.memoryLimit.use(array.length)
|
||||
for (const item of array) {
|
||||
results.push(yield this.context._getFromScope(item, stringify(property), false))
|
||||
}
|
||||
@@ -65,15 +64,13 @@ export function * sum (this: FilterImpl, arr: Scope[], property?: string): Itera
|
||||
|
||||
export function compact<T> (this: FilterImpl, arr: T[]) {
|
||||
const array = toArray(arr)
|
||||
this.context.memoryLimit.use(array.length)
|
||||
return array.filter(x => !isNil(toValue(x)))
|
||||
return Array.prototype.filter.call(array, x => !isNil(toValue(x)))
|
||||
}
|
||||
|
||||
export function concat<T1, T2> (this: FilterImpl, v: T1[], arg: T2[] = []): (T1 | T2)[] {
|
||||
const lhs = toArray(v)
|
||||
const rhs = toArray(arg)
|
||||
this.context.memoryLimit.use(lhs.length + rhs.length)
|
||||
return lhs.concat(rhs)
|
||||
return Array.prototype.concat.call(lhs, rhs)
|
||||
}
|
||||
|
||||
export function push<T> (this: FilterImpl, v: T[], arg: T): T[] {
|
||||
@@ -82,7 +79,6 @@ export function push<T> (this: FilterImpl, v: T[], arg: T): T[] {
|
||||
|
||||
export function unshift<T> (this: FilterImpl, v: T[], arg: T): T[] {
|
||||
const array = toArray(v)
|
||||
this.context.memoryLimit.use(array.length)
|
||||
const clone = [...array]
|
||||
clone.unshift(arg)
|
||||
return clone
|
||||
@@ -90,7 +86,6 @@ export function unshift<T> (this: FilterImpl, v: T[], arg: T): T[] {
|
||||
|
||||
export function pop<T> (this: FilterImpl, v: T[]): T[] {
|
||||
const array = toArray(v)
|
||||
this.context.memoryLimit.use(array.length)
|
||||
const clone = [...array]
|
||||
clone.pop()
|
||||
return clone
|
||||
@@ -98,7 +93,6 @@ export function pop<T> (this: FilterImpl, v: T[]): T[] {
|
||||
|
||||
export function shift<T> (this: FilterImpl, v: T[]): T[] {
|
||||
const array = toArray(v)
|
||||
this.context.memoryLimit.use(array.length)
|
||||
const clone = [...array]
|
||||
clone.shift()
|
||||
return clone
|
||||
@@ -109,8 +103,9 @@ export function slice<T> (this: FilterImpl, v: T[] | string, begin: number, leng
|
||||
if (isNil(v)) return []
|
||||
if (!isArray(v)) v = stringify(v)
|
||||
begin = begin < 0 ? v.length + begin : begin
|
||||
this.context.memoryLimit.use(length)
|
||||
return v.slice(begin, begin + length)
|
||||
return isArray(v)
|
||||
? Array.prototype.slice.call(v, begin, begin + length)
|
||||
: String.prototype.slice.call(v, begin, begin + length)
|
||||
}
|
||||
|
||||
function expectedMatcher (this: FilterImpl, expected: any): (v: any) => boolean {
|
||||
@@ -126,20 +121,18 @@ function expectedMatcher (this: FilterImpl, expected: any): (v: any) => boolean
|
||||
function * filter<T extends object> (this: FilterImpl, include: boolean, arr: T[], property: string, expected: any): IterableIterator<unknown> {
|
||||
const values: unknown[] = []
|
||||
arr = toArray(arr)
|
||||
this.context.memoryLimit.use(arr.length)
|
||||
const token = new Tokenizer(stringify(property)).readScopeValue()
|
||||
for (const item of arr) {
|
||||
values.push(yield evalToken(token, this.context.spawn(item)))
|
||||
}
|
||||
const matcher = expectedMatcher.call(this, expected)
|
||||
return arr.filter((_, i) => matcher(values[i]) === include)
|
||||
return Array.prototype.filter.call(arr, (_, i) => matcher(values[i]) === include)
|
||||
}
|
||||
|
||||
function * filter_exp<T extends object> (this: FilterImpl, include: boolean, arr: T[], itemName: string, exp: string): IterableIterator<unknown> {
|
||||
const filtered: unknown[] = []
|
||||
const keyTemplate = new Value(stringify(exp), this.liquid)
|
||||
const array = toArray(arr)
|
||||
this.context.memoryLimit.use(array.length)
|
||||
for (const item of array) {
|
||||
this.context.push({ [itemName]: item })
|
||||
const value = yield keyTemplate.value(this.context)
|
||||
@@ -169,7 +162,6 @@ export function * group_by<T extends object> (this: FilterImpl, arr: T[], proper
|
||||
const map = new Map()
|
||||
arr = toEnumerable(arr)
|
||||
const token = new Tokenizer(stringify(property)).readScopeValue()
|
||||
this.context.memoryLimit.use(arr.length)
|
||||
for (const item of arr) {
|
||||
const key = yield evalToken(token, this.context.spawn(item))
|
||||
if (!map.has(key)) map.set(key, [])
|
||||
@@ -182,7 +174,6 @@ export function * group_by_exp<T extends object> (this: FilterImpl, arr: T[], it
|
||||
const map = new Map()
|
||||
const keyTemplate = new Value(stringify(exp), this.liquid)
|
||||
arr = toEnumerable(arr)
|
||||
this.context.memoryLimit.use(arr.length)
|
||||
for (const item of arr) {
|
||||
this.context.push({ [itemName]: item })
|
||||
const key = yield keyTemplate.value(this.context)
|
||||
@@ -246,7 +237,6 @@ export function * find_exp<T extends object> (this: FilterImpl, arr: T[], itemNa
|
||||
|
||||
export function uniq<T> (this: FilterImpl, arr: T[]): T[] {
|
||||
arr = toArray(arr)
|
||||
this.context.memoryLimit.use(arr.length)
|
||||
return [...new Set(arr)]
|
||||
}
|
||||
|
||||
@@ -254,7 +244,6 @@ export function sample<T> (this: FilterImpl, v: T[] | string, count = 1): T | st
|
||||
v = toValue(v)
|
||||
if (isNil(v)) return []
|
||||
if (!isArray(v)) v = stringify(v)
|
||||
this.context.memoryLimit.use(v.length)
|
||||
const shuffled = [...v].sort(() => Math.random() - 0.5)
|
||||
if (count === 1) return shuffled[0]
|
||||
return shuffled.slice(0, count)
|
||||
|
||||
@@ -10,16 +10,13 @@ import { base64Encode, base64Decode } from './base64-impl'
|
||||
|
||||
export function base64_encode (this: FilterImpl, value: string | Buffer): string {
|
||||
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
|
||||
this.context.memoryLimit.use(value.byteLength)
|
||||
return value.toString('base64')
|
||||
}
|
||||
const str = stringify(value)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return base64Encode(str)
|
||||
}
|
||||
|
||||
export function base64_decode (this: FilterImpl, value: string): string {
|
||||
const str = stringify(value)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return base64Decode(str)
|
||||
}
|
||||
|
||||
@@ -10,13 +10,11 @@ import { sha256 as sha256Impl, hmacSha256 as hmacSha256Impl } from './crypto-imp
|
||||
|
||||
export function sha256 (this: FilterImpl, value: unknown): string | Promise<string> {
|
||||
const str = stringify(value)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return sha256Impl(str)
|
||||
}
|
||||
|
||||
export function hmac_sha256 (this: FilterImpl, value: unknown, key: unknown): string | Promise<string> {
|
||||
const str = stringify(value)
|
||||
const keyStr = stringify(key)
|
||||
this.context.memoryLimit.use(str.length + keyStr.length)
|
||||
return hmacSha256Impl(str, keyStr)
|
||||
}
|
||||
|
||||
+4
-8
@@ -3,14 +3,11 @@ import { FilterImpl } from '../template'
|
||||
import { NormalizedFullOptions } from '../liquid-options'
|
||||
|
||||
export function date (this: FilterImpl, v: string | Date, format?: string, timezoneOffset?: number | string) {
|
||||
const size = ((v as string)?.length ?? 0) + ((timezoneOffset as string)?.length ?? 0)
|
||||
this.context.memoryLimit.use(size)
|
||||
const date = parseDate(v, this.context.opts, timezoneOffset)
|
||||
if (!date) return v
|
||||
format = toValue(format)
|
||||
format = isNil(format) ? this.context.opts.dateFormat : stringify(format)
|
||||
this.context.memoryLimit.use(format.length)
|
||||
return strftime(date, format, this.context.memoryLimit)
|
||||
return strftime(date, format)
|
||||
}
|
||||
|
||||
export function date_to_xmlschema (this: FilterImpl, v: string | Date) {
|
||||
@@ -32,14 +29,13 @@ export function date_to_long_string (this: FilterImpl, v: string | Date, type?:
|
||||
function stringify_date (this: FilterImpl, v: string | Date, month_type: string, type?: string, style?: string) {
|
||||
const date = parseDate(v, this.context.opts)
|
||||
if (!date) return v
|
||||
const ml = this.context.memoryLimit
|
||||
if (type === 'ordinal') {
|
||||
const d = date.getDate()
|
||||
return style === 'US'
|
||||
? strftime(date, `${month_type} ${d}%q, %Y`, ml)
|
||||
: strftime(date, `${d}%q ${month_type} %Y`, ml)
|
||||
? strftime(date, `${month_type} ${d}%q, %Y`)
|
||||
: strftime(date, `${d}%q ${month_type} %Y`)
|
||||
}
|
||||
return strftime(date, `%d ${month_type} %Y`, ml)
|
||||
return strftime(date, `%d ${month_type} %Y`)
|
||||
}
|
||||
|
||||
function parseDate (v: string | Date, opts: NormalizedFullOptions, timezoneOffset?: number | string): LiquidDate | undefined {
|
||||
|
||||
+1
-5
@@ -18,7 +18,6 @@ const unescapeMap: Record<string, string> = {
|
||||
|
||||
export function escape (this: FilterImpl, str: string) {
|
||||
str = stringify(str)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.replace(/&|<|>|"|'/g, m => escapeMap[m])
|
||||
}
|
||||
|
||||
@@ -28,7 +27,6 @@ export function xml_escape (this: FilterImpl, str: string) {
|
||||
|
||||
function unescape (this: FilterImpl, str: string) {
|
||||
str = stringify(str)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m])
|
||||
}
|
||||
|
||||
@@ -38,7 +36,6 @@ export function escape_once (this: FilterImpl, str: string) {
|
||||
|
||||
export function newline_to_br (this: FilterImpl, v: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.replace(/\r?\n/gm, '<br />\n')
|
||||
}
|
||||
|
||||
@@ -46,7 +43,6 @@ export function newline_to_br (this: FilterImpl, v: string) {
|
||||
// equivalent is O(n^2) in V8 on unclosed openers.
|
||||
export function strip_html (this: FilterImpl, v: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
const blocks = new Map([['<script', '</script>'], ['<style', '</style>'], ['<!--', '-->'], ['<', '>']])
|
||||
let out = ''
|
||||
let i = 0
|
||||
@@ -60,7 +56,7 @@ export function strip_html (this: FilterImpl, v: string) {
|
||||
if (e >= 0) { i = e + closer.length; break }
|
||||
blocks.delete(opener)
|
||||
}
|
||||
if (i === lt) return out + str.slice(lt)
|
||||
if (i <= lt) return out + str.slice(lt)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
+3
-4
@@ -8,14 +8,13 @@ export const divided_by = argumentsToNumber((dividend: number, divisor: number,
|
||||
export const floor = argumentsToNumber(Math.floor)
|
||||
export const minus = argumentsToNumber((v: number, arg: number) => v - arg)
|
||||
export const plus = argumentsToNumber((lhs: number, rhs: number) => lhs + rhs)
|
||||
export const modulo = argumentsToNumber((v: number, arg: number) => v % arg)
|
||||
export const modulo = argumentsToNumber((v: number, arg: number) => ((v % arg) + arg) % arg)
|
||||
export const times = argumentsToNumber((v: number, arg: number) => v * arg)
|
||||
|
||||
export function round (v: number, arg = 0) {
|
||||
v = toNumber(v)
|
||||
arg = toNumber(arg)
|
||||
const amp = Math.pow(10, arg)
|
||||
const scaled = v * amp
|
||||
// Round half away from zero
|
||||
return Math.sign(v) * Math.round(Math.abs(scaled)) / amp
|
||||
const scaled = (v * amp) * (1 + Number.EPSILON)
|
||||
return Math.round(scaled) / amp
|
||||
}
|
||||
|
||||
+9
-5
@@ -9,17 +9,21 @@ function defaultFilter<T1 extends boolean, T2> (this: FilterImpl, value: T1, def
|
||||
return isFalsy(value, this.context) ? defaultValue : value
|
||||
}
|
||||
|
||||
function json (value: any, space = 0) {
|
||||
return JSON.stringify(value, null, space)
|
||||
function json (this: FilterImpl, value: any, space = 0) {
|
||||
return JSON.stringify(value, undefined, space)
|
||||
}
|
||||
|
||||
function inspect (value: any, space = 0) {
|
||||
function inspect (this: FilterImpl, value: any, space = 0) {
|
||||
const ancestors: object[] = []
|
||||
return JSON.stringify(value, function (this: unknown, _key: unknown, value: any) {
|
||||
if (typeof value !== 'object' || value === null) return value
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return value
|
||||
}
|
||||
// `this` is the object that value is contained in, i.e., its direct parent.
|
||||
while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) ancestors.pop()
|
||||
if (ancestors.includes(value)) return '[Circular]'
|
||||
if (ancestors.includes(value)) {
|
||||
return '[Circular]'
|
||||
}
|
||||
ancestors.push(value)
|
||||
return value
|
||||
}, space)
|
||||
|
||||
@@ -22,7 +22,6 @@ export function append (this: FilterImpl, v: string, arg: string) {
|
||||
assert(arguments.length === 2, 'append expect 2 arguments')
|
||||
const lhs = stringify(v)
|
||||
const rhs = stringify(arg)
|
||||
this.context.memoryLimit.use(lhs.length + rhs.length)
|
||||
return lhs + rhs
|
||||
}
|
||||
|
||||
@@ -30,16 +29,13 @@ export function prepend (this: FilterImpl, v: string, arg: string) {
|
||||
assert(arguments.length === 2, 'prepend expect 2 arguments')
|
||||
const lhs = stringify(v)
|
||||
const rhs = stringify(arg)
|
||||
this.context.memoryLimit.use(lhs.length + rhs.length)
|
||||
return rhs + lhs
|
||||
}
|
||||
|
||||
export function lstrip (this: FilterImpl, v: string, chars?: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
if (chars) {
|
||||
chars = stringify(chars)
|
||||
this.context.memoryLimit.use(chars.length)
|
||||
for (let i = 0, set = new Set(chars); i < str.length; i++) {
|
||||
if (!set.has(str[i])) return str.slice(i)
|
||||
}
|
||||
@@ -50,34 +46,29 @@ export function lstrip (this: FilterImpl, v: string, chars?: string) {
|
||||
|
||||
export function downcase (this: FilterImpl, v: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.toLowerCase()
|
||||
}
|
||||
|
||||
export function upcase (this: FilterImpl, v: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return stringify(str).toUpperCase()
|
||||
}
|
||||
|
||||
export function remove (this: FilterImpl, v: string, arg: string) {
|
||||
const str = stringify(v)
|
||||
arg = stringify(arg)
|
||||
this.context.memoryLimit.use(str.length + arg.length)
|
||||
return str.split(arg).join('')
|
||||
}
|
||||
|
||||
export function remove_first (this: FilterImpl, v: string, l: string) {
|
||||
const str = stringify(v)
|
||||
l = stringify(l)
|
||||
this.context.memoryLimit.use(str.length + l.length)
|
||||
return str.replace(l, '')
|
||||
}
|
||||
|
||||
export function remove_last (this: FilterImpl, v: string, l: string) {
|
||||
const str = stringify(v)
|
||||
const pattern = stringify(l)
|
||||
this.context.memoryLimit.use(str.length + pattern.length)
|
||||
const index = str.lastIndexOf(pattern)
|
||||
if (index === -1) return str
|
||||
return str.substring(0, index) + str.substring(index + pattern.length)
|
||||
@@ -85,10 +76,8 @@ export function remove_last (this: FilterImpl, v: string, l: string) {
|
||||
|
||||
export function rstrip (this: FilterImpl, str: string, chars?: string) {
|
||||
str = stringify(str)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
if (chars) {
|
||||
chars = stringify(chars)
|
||||
this.context.memoryLimit.use(chars.length)
|
||||
for (let i = str.length - 1, set = new Set(chars); i >= 0; i--) {
|
||||
if (!set.has(str[i])) return str.slice(0, i + 1)
|
||||
}
|
||||
@@ -99,7 +88,6 @@ export function rstrip (this: FilterImpl, str: string, chars?: string) {
|
||||
|
||||
export function split (this: FilterImpl, v: string, arg: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
const arr = str.split(stringify(arg))
|
||||
// align to ruby split, which is the behavior of shopify/liquid
|
||||
// see: https://ruby-doc.org/core-2.4.0/String.html#method-i-split
|
||||
@@ -109,10 +97,8 @@ export function split (this: FilterImpl, v: string, arg: string) {
|
||||
|
||||
export function strip (this: FilterImpl, v: string, chars?: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
if (chars) {
|
||||
const set = new Set(stringify(chars))
|
||||
this.context.memoryLimit.use(set.size)
|
||||
let i = 0
|
||||
let j = str.length - 1
|
||||
while (set.has(str[i])) i++
|
||||
@@ -124,13 +110,11 @@ export function strip (this: FilterImpl, v: string, chars?: string) {
|
||||
|
||||
export function strip_newlines (this: FilterImpl, v: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.replace(/\r?\n/gm, '')
|
||||
}
|
||||
|
||||
export function capitalize (this: FilterImpl, str: string) {
|
||||
str = stringify(str)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
|
||||
}
|
||||
|
||||
@@ -139,8 +123,6 @@ export function replace (this: FilterImpl, v: string, pattern: string, replaceme
|
||||
pattern = stringify(pattern)
|
||||
replacement = stringify(replacement)
|
||||
const parts = str.split(pattern)
|
||||
const outputSize = str.length + (parts.length - 1) * (replacement.length - pattern.length)
|
||||
this.context.memoryLimit.use(outputSize)
|
||||
return parts.join(replacement)
|
||||
}
|
||||
|
||||
@@ -148,7 +130,6 @@ export function replace_first (this: FilterImpl, v: string, arg1: string, arg2:
|
||||
const str = stringify(v)
|
||||
arg1 = stringify(arg1)
|
||||
arg2 = stringify(arg2)
|
||||
this.context.memoryLimit.use(str.length + arg1.length + arg2.length)
|
||||
return str.replace(arg1, () => arg2)
|
||||
}
|
||||
|
||||
@@ -156,7 +137,6 @@ export function replace_last (this: FilterImpl, v: string, arg1: string, arg2: s
|
||||
const str = stringify(v)
|
||||
const pattern = stringify(arg1)
|
||||
const replacement = stringify(arg2)
|
||||
this.context.memoryLimit.use(str.length + pattern.length + replacement.length)
|
||||
const index = str.lastIndexOf(pattern)
|
||||
if (index === -1) return str
|
||||
return str.substring(0, index) + replacement + str.substring(index + pattern.length)
|
||||
@@ -165,7 +145,6 @@ export function replace_last (this: FilterImpl, v: string, arg1: string, arg2: s
|
||||
export function truncate (this: FilterImpl, v: string, l = 50, o = '...') {
|
||||
const str = stringify(v)
|
||||
o = stringify(o)
|
||||
this.context.memoryLimit.use(str.length + o.length)
|
||||
if (str.length <= l) return v
|
||||
return str.substring(0, l - o.length) + o
|
||||
}
|
||||
@@ -173,7 +152,6 @@ export function truncate (this: FilterImpl, v: string, l = 50, o = '...') {
|
||||
export function truncatewords (this: FilterImpl, v: string, words = 15, o = '...') {
|
||||
const str = stringify(v)
|
||||
o = stringify(o)
|
||||
this.context.memoryLimit.use(str.length + o.length)
|
||||
const arr = str.split(/\s+/)
|
||||
if (words <= 0) words = 1
|
||||
let ret = arr.slice(0, words).join(' ')
|
||||
@@ -183,13 +161,11 @@ export function truncatewords (this: FilterImpl, v: string, words = 15, o = '...
|
||||
|
||||
export function normalize_whitespace (this: FilterImpl, v: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.replace(/\s+/g, ' ')
|
||||
}
|
||||
|
||||
export function number_of_words (this: FilterImpl, input: string, mode?: 'cjk' | 'auto') {
|
||||
const str = stringify(input)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
input = str.trim()
|
||||
if (!input) return 0
|
||||
switch (mode) {
|
||||
@@ -209,7 +185,6 @@ export function number_of_words (this: FilterImpl, input: string, mode?: 'cjk' |
|
||||
|
||||
export function array_to_sentence_string (this: FilterImpl, array: unknown[], connector = 'and') {
|
||||
connector = stringify(connector)
|
||||
this.context.memoryLimit.use(array.length + connector.length)
|
||||
switch (array.length) {
|
||||
case 0:
|
||||
return ''
|
||||
|
||||
+20
-22
@@ -38,7 +38,7 @@ export interface LiquidOptions {
|
||||
strictVariables?: boolean;
|
||||
/** Catch all errors instead of exit upon one. Please note that render errors won't be reached when parse fails. */
|
||||
catchAllErrors?: boolean;
|
||||
/** Hide scope variables from prototypes, useful when you're passing a not sanitized object into LiquidJS or need to hide prototypes from templates. */
|
||||
/** Limit template property reads on plain scope objects to own properties. Defaults to `true`. See https://liquidjs.com/tutorials/security-model.html */
|
||||
ownPropertyOnly?: boolean;
|
||||
/** Modifies the behavior of `strictVariables`. If set, a single undefined variable will *not* cause an exception in the context of the `if`/`elsif`/`unless` tag and the `default` filter. Instead, it will evaluate to `false` and `null`, respectively. Irrelevant if `strictVariables` is not set. Defaults to `false`. **/
|
||||
lenientIf?: boolean;
|
||||
@@ -76,8 +76,6 @@ export interface LiquidOptions {
|
||||
templates?: {[key: string]: string};
|
||||
/** the global scope passed down to all partial and layout templates, i.e. templates included by `include`, `layout` and `render` tags. */
|
||||
globals?: object;
|
||||
/** Whether or not to keep value type when writing the Output, not working for streamed rendering. Defaults to `false`. */
|
||||
keepOutputType?: boolean;
|
||||
/** Default escape filter applied to output values, when set, you'll have to add `| raw` for values don't need to be escaped. Defaults to `undefined`. */
|
||||
outputEscape?: OutputEscapeOption;
|
||||
/** An object of operators for conditional statements. Defaults to the regular Liquid operators. */
|
||||
@@ -86,10 +84,12 @@ export interface LiquidOptions {
|
||||
orderedFilterParameters?: boolean;
|
||||
/** For DoS handling, limit total length of templates parsed in one `parse()` call. A typical PC can handle 1e8 (100M) characters without issues. */
|
||||
parseLimit?: number;
|
||||
/** For DoS handling, limit total time (in ms) for each `render()` call. */
|
||||
renderLimit?: number;
|
||||
/** For DoS handling, limit new objects creation, including array concat/join/strftime, etc. A typical PC can handle 1e9 (1G) memory without issue. */
|
||||
memoryLimit?: number;
|
||||
/** For DoS handling, limit total renders of tag/HTML/output in one `render()` call. */
|
||||
templateLimit?: number;
|
||||
/** For DoS handling, limit total output length in one `render()` call. */
|
||||
outputLengthLimit?: number;
|
||||
/** For DoS handling, limit nesting depth of `{% render %}`, `{% include %}`, and `{% layout %}` tags. Defaults to `128`. */
|
||||
maxDepth?: number;
|
||||
}
|
||||
|
||||
export interface RenderOptions {
|
||||
@@ -109,12 +109,10 @@ export interface RenderOptions {
|
||||
* Same as `ownPropertyOnly` on LiquidOptions, but only for current render() call
|
||||
*/
|
||||
ownPropertyOnly?: boolean;
|
||||
/** For DoS handling, limit total renders of tag/HTML/output in one `render()` call. A typical PC can handle 1e5 renders of typical templates per second. */
|
||||
/** For DoS handling, limit total renders of tag/HTML/output in one `render()` call. */
|
||||
templateLimit?: number;
|
||||
/** For DoS handling, limit total time (in ms) for each `render()` call. */
|
||||
renderLimit?: number;
|
||||
/** For DoS handling, limit new objects creation, including array concat/join/strftime, etc. A typical PC can handle 1e9 (1G) memory without issue.. */
|
||||
memoryLimit?: number;
|
||||
/** For DoS handling, limit total output length in one `render()` call. */
|
||||
outputLengthLimit?: number;
|
||||
}
|
||||
|
||||
export interface RenderFileOptions extends RenderOptions {
|
||||
@@ -157,11 +155,11 @@ export interface NormalizedFullOptions extends NormalizedOptions {
|
||||
preserveTimezones: boolean;
|
||||
greedy: boolean;
|
||||
globals: object;
|
||||
keepOutputType: boolean;
|
||||
operators: Operators;
|
||||
parseLimit: number;
|
||||
renderLimit: number;
|
||||
memoryLimit: number;
|
||||
templateLimit: number;
|
||||
outputLengthLimit: number;
|
||||
maxDepth: number;
|
||||
}
|
||||
|
||||
export const defaultOptions: NormalizedFullOptions = {
|
||||
@@ -193,19 +191,19 @@ export const defaultOptions: NormalizedFullOptions = {
|
||||
ownPropertyOnly: true,
|
||||
lenientIf: false,
|
||||
globals: {},
|
||||
keepOutputType: false,
|
||||
operators: defaultOperators,
|
||||
memoryLimit: Infinity,
|
||||
parseLimit: Infinity,
|
||||
renderLimit: Infinity
|
||||
templateLimit: Infinity,
|
||||
outputLengthLimit: Infinity,
|
||||
maxDepth: 128
|
||||
}
|
||||
|
||||
export function normalize (options: LiquidOptions): NormalizedFullOptions {
|
||||
if (options.hasOwnProperty('root')) {
|
||||
if (!options.hasOwnProperty('partials')) options.partials = options.root
|
||||
if (!options.hasOwnProperty('layouts')) options.layouts = options.root
|
||||
if ('root' in options) {
|
||||
if (!('partials' in options)) options.partials = options.root
|
||||
if (!('layouts' in options)) options.layouts = options.root
|
||||
}
|
||||
if (options.hasOwnProperty('cache')) {
|
||||
if ('cache' in options) {
|
||||
let cache: LiquidCache | undefined
|
||||
if (typeof options.cache === 'number') cache = options.cache > 0 ? new LRU(options.cache) : undefined
|
||||
else if (typeof options.cache === 'object') cache = options.cache
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
import { Context } from './context'
|
||||
import { toPromise, toValueSync, isFunction, forOwn, isString, strictUniq } from './util'
|
||||
import { TagClass, createTagClass, TagImplOptions, FilterImplOptions, Template, Value, StaticAnalysisOptions, StaticAnalysis, analyze, analyzeSync, SegmentArray } from './template'
|
||||
import { toPromise, toValueSync, forOwn, isString, strictUniq } from './util'
|
||||
import { TagClass, FilterImplOptions, Template, Value, StaticAnalysisOptions, StaticAnalysis, analyze, analyzeSync, SegmentArray } from './template'
|
||||
import { LookupType } from './fs/loader'
|
||||
import { Render } from './render'
|
||||
import { Parser } from './parser'
|
||||
@@ -101,8 +101,8 @@ export class Liquid {
|
||||
public registerFilter (name: string, filter: FilterImplOptions) {
|
||||
this.filters[name] = filter
|
||||
}
|
||||
public registerTag (name: string, tag: TagClass | TagImplOptions) {
|
||||
this.tags[name] = isFunction(tag) ? tag : createTagClass(tag)
|
||||
public registerTag (name: string, tag: TagClass) {
|
||||
this.tags[name] = tag
|
||||
}
|
||||
public plugin (plugin: (this: Liquid, L: typeof Liquid) => void) {
|
||||
return plugin.call(this, Liquid)
|
||||
|
||||
@@ -522,6 +522,14 @@ describe('Tokenizer', function () {
|
||||
expect(new Tokenizer('contains b').matchTrie(opTrie)).toBe(8)
|
||||
})
|
||||
})
|
||||
describe('#createTrie()', function () {
|
||||
it('should return the same trie for the same input', () => {
|
||||
expect(createTrie(defaultOperators)).toBe(createTrie(defaultOperators))
|
||||
})
|
||||
it('should return distinct tries for distinct inputs', () => {
|
||||
expect(createTrie({ foo: 1 })).not.toBe(createTrie({ foo: 1 }))
|
||||
})
|
||||
})
|
||||
describe('#readLiquidTagTokens', () => {
|
||||
it('should read newline terminated tokens', () => {
|
||||
const tokenizer = new Tokenizer('echo \'hello\'')
|
||||
|
||||
@@ -67,7 +67,6 @@ export function evalQuotedToken (token: QuotedToken) {
|
||||
function * evalRangeToken (token: RangeToken, ctx: Context) {
|
||||
const low: number = yield evalToken(token.lhs, ctx)
|
||||
const high: number = yield evalToken(token.rhs, ctx)
|
||||
ctx.memoryLimit.use(high - low + 1)
|
||||
return range(+low, +high + 1)
|
||||
}
|
||||
|
||||
|
||||
+4
-11
@@ -1,28 +1,21 @@
|
||||
import { getPerformance } from '../util/performance'
|
||||
import { toPromise, RenderError, LiquidErrors, LiquidError } from '../util'
|
||||
import { Context } from '../context'
|
||||
import { Template } from '../template'
|
||||
import { Emitter, KeepingTypeEmitter, StreamedEmitter, SimpleEmitter } from '../emitters'
|
||||
import { Emitter, StreamedEmitter, SimpleEmitter } from '../emitters'
|
||||
|
||||
export class Render {
|
||||
public renderTemplatesToNodeStream (templates: Template[], ctx: Context): NodeJS.ReadableStream {
|
||||
const emitter = new StreamedEmitter()
|
||||
const emitter = new StreamedEmitter(ctx.outputLengthLimit)
|
||||
Promise.resolve().then(() => toPromise(this.renderTemplates(templates, ctx, emitter)))
|
||||
.then(() => emitter.end(), err => emitter.error(err))
|
||||
return emitter.stream
|
||||
}
|
||||
public * renderTemplates (templates: Template[], ctx: Context, emitter?: Emitter): IterableIterator<any> {
|
||||
if (!emitter) {
|
||||
emitter = ctx.opts.keepOutputType ? new KeepingTypeEmitter() : new SimpleEmitter()
|
||||
}
|
||||
ctx.renderLimit.check(getPerformance().now())
|
||||
public * renderTemplates (templates: Template[], ctx: Context, emitter: Emitter = new SimpleEmitter(ctx.outputLengthLimit)): IterableIterator<any> {
|
||||
const errors = []
|
||||
for (const tpl of templates) {
|
||||
ctx.renderLimit.check(getPerformance().now())
|
||||
ctx.templateLimit.use(1)
|
||||
try {
|
||||
// if tpl.render supports emitter, it'll return empty `html`
|
||||
const html = yield tpl.render(ctx, emitter)
|
||||
// if not, it'll return an `html`, write to the emitter for it
|
||||
html && emitter.write(html)
|
||||
if (ctx.breakCalled || ctx.continueCalled) break
|
||||
} catch (e) {
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
import { BlockMode, createScope } from '../context'
|
||||
import { BlockMode } from '../context'
|
||||
import { isTagToken } from '../util'
|
||||
import { BlockDrop } from '../drop'
|
||||
import { Liquid, TagToken, TopLevelToken, Template, Context, Emitter, Tag } from '..'
|
||||
@@ -38,7 +38,7 @@ export default class extends Tag {
|
||||
if (stack.includes(self)) throw new Error('block tag cannot be nested')
|
||||
|
||||
stack.push(self)
|
||||
ctx.push(createScope({ block: superBlock }))
|
||||
ctx.push({ block: superBlock })
|
||||
yield liquid.renderer.renderTemplates(templates, ctx, emitter)
|
||||
ctx.pop()
|
||||
stack.pop()
|
||||
|
||||
+11
-11
@@ -1,6 +1,5 @@
|
||||
import { Hash, ValueToken, Liquid, Tag, evalToken, Emitter, TagToken, TopLevelToken, Context, Template, ParseStream } from '..'
|
||||
import { assertEmpty, isValueToken, toEnumerable } from '../util'
|
||||
import { createScope } from '../context/scope'
|
||||
import { ForloopDrop } from '../drop/forloop-drop'
|
||||
import { Parser } from '../parser'
|
||||
import { Arguments } from '../template'
|
||||
@@ -43,15 +42,8 @@ export default class extends Tag {
|
||||
}
|
||||
* render (ctx: Context, emitter: Emitter): Generator<unknown, void | string, Template[]> {
|
||||
const r = this.liquid.renderer
|
||||
let collection = toEnumerable(yield evalToken(this.collection, ctx))
|
||||
|
||||
if (!collection.length) {
|
||||
yield r.renderTemplates(this.elseTemplates, ctx, emitter)
|
||||
return
|
||||
}
|
||||
|
||||
const continueKey = 'continue-' + this.variable + '-' + this.collection.getText()
|
||||
ctx.push(createScope({ continue: ctx.getRegister(continueKey, {}) }))
|
||||
ctx.push({ continue: ctx.getRegister(continueKey, {}) })
|
||||
const hash = (yield this.hash.render(ctx)) as Record<string, any>
|
||||
ctx.pop()
|
||||
|
||||
@@ -59,6 +51,7 @@ export default class extends Tag {
|
||||
? Object.keys(hash).filter(x => MODIFIERS.includes(x))
|
||||
: MODIFIERS.filter(x => hash[x] !== undefined)
|
||||
|
||||
let collection = toEnumerable(yield evalToken(this.collection, ctx))
|
||||
collection = modifiers.reduce((collection, modifier: valueOf<typeof MODIFIERS>) => {
|
||||
if (modifier === 'offset') return offset(collection, hash['offset'])
|
||||
if (modifier === 'limit') return limit(collection, hash['limit'])
|
||||
@@ -66,8 +59,15 @@ export default class extends Tag {
|
||||
}, collection)
|
||||
|
||||
ctx.setRegister(continueKey, (hash['offset'] || 0) + collection.length)
|
||||
const scope = createScope({ forloop: new ForloopDrop(collection.length, this.collection.getText(), this.variable) })
|
||||
ctx.push(scope)
|
||||
|
||||
if (!collection.length) {
|
||||
yield r.renderTemplates(this.elseTemplates, ctx, emitter)
|
||||
return
|
||||
}
|
||||
|
||||
if (!this.templates.length) return
|
||||
|
||||
const scope = ctx.push({ forloop: new ForloopDrop(collection.length, this.collection.getText(), this.variable) })
|
||||
for (const item of collection) {
|
||||
scope[this.variable] = item
|
||||
ctx.continueCalled = ctx.breakCalled = false
|
||||
|
||||
+5
-3
@@ -1,5 +1,5 @@
|
||||
import { Template, ValueToken, TopLevelToken, Liquid, Tag, assert, evalToken, Hash, Emitter, TagToken, Context } from '..'
|
||||
import { BlockMode, createScope, Scope } from '../context'
|
||||
import { BlockMode, Scope } from '../context'
|
||||
import { Parser } from '../parser'
|
||||
import { Argument, Arguments, PartialScope } from '../template'
|
||||
import { isString, isValueToken } from '../util'
|
||||
@@ -28,6 +28,7 @@ export default class extends Tag {
|
||||
this.hash = new Hash(tokenizer, liquid.options.jekyllInclude || liquid.options.keyValueSeparator)
|
||||
}
|
||||
* render (ctx: Context, emitter: Emitter): Generator<unknown, void, unknown> {
|
||||
ctx.depthLimit.use(1)
|
||||
const { liquid, hash, withVar } = this
|
||||
const { renderer } = liquid
|
||||
const filepath = (yield renderFilePath(this.file, ctx, liquid)) as string
|
||||
@@ -36,13 +37,14 @@ export default class extends Tag {
|
||||
const saved = ctx.saveRegister('blocks', 'blockMode')
|
||||
ctx.setRegister('blocks', {})
|
||||
ctx.setRegister('blockMode', BlockMode.OUTPUT)
|
||||
const scope = createScope((yield hash.render(ctx)) as Scope)
|
||||
const scope = (yield hash.render(ctx)) as Scope
|
||||
if (withVar) scope[filepath] = yield evalToken(withVar, ctx)
|
||||
const templates = (yield liquid._parsePartialFile(filepath, ctx.sync, this.currentFile)) as Template[]
|
||||
ctx.push(ctx.opts.jekyllInclude ? createScope({ include: scope }) : scope)
|
||||
ctx.push(ctx.opts.jekyllInclude ? { include: scope } : scope)
|
||||
yield renderer.renderTemplates(templates, ctx, emitter)
|
||||
ctx.pop()
|
||||
ctx.restoreRegister(saved)
|
||||
ctx.depthLimit.release(1)
|
||||
}
|
||||
|
||||
public * children (partials: boolean, sync: boolean): Generator<unknown, Template[]> {
|
||||
|
||||
+4
-2
@@ -1,5 +1,5 @@
|
||||
import { Scope, Template, Liquid, Tag, assert, Emitter, Hash, TagToken, TopLevelToken, Context } from '..'
|
||||
import { BlockMode, createScope } from '../context'
|
||||
import { BlockMode } from '../context'
|
||||
import { parseFilePath, renderFilePath, ParsedFileName } from './render'
|
||||
import { BlankDrop } from '../drop'
|
||||
import { Parser } from '../parser'
|
||||
@@ -26,6 +26,7 @@ export default class extends Tag {
|
||||
yield renderer.renderTemplates(this.templates, ctx, emitter)
|
||||
return
|
||||
}
|
||||
ctx.depthLimit.use(1)
|
||||
const filepath = (yield renderFilePath(this.file, ctx, liquid)) as string
|
||||
assert(filepath, () => `illegal file path "${filepath}"`)
|
||||
const templates = (yield liquid._parseLayoutFile(filepath, ctx.sync, this.currentFile)) as Template[]
|
||||
@@ -40,9 +41,10 @@ export default class extends Tag {
|
||||
ctx.setRegister('blockMode', BlockMode.OUTPUT)
|
||||
|
||||
// render the layout file use stored blocks
|
||||
ctx.push(createScope((yield args.render(ctx)) as Scope))
|
||||
ctx.push((yield args.render(ctx)) as Scope)
|
||||
yield renderer.renderTemplates(templates, ctx, emitter)
|
||||
ctx.pop()
|
||||
ctx.depthLimit.release(1)
|
||||
}
|
||||
|
||||
public * children (partials: boolean): Generator<unknown, Template[]> {
|
||||
|
||||
@@ -55,6 +55,7 @@ export default class extends Tag {
|
||||
this.hash = new Hash(tokenizer, liquid.options.keyValueSeparator)
|
||||
}
|
||||
* render (ctx: Context, emitter: Emitter): Generator<unknown, void, unknown> {
|
||||
ctx.depthLimit.use(1)
|
||||
const { liquid, hash } = this
|
||||
const filepath = (yield renderFilePath(this.file, ctx, liquid)) as string
|
||||
assert(filepath, () => `illegal file path "${filepath}"`)
|
||||
@@ -81,6 +82,7 @@ export default class extends Tag {
|
||||
const templates = (yield liquid._parsePartialFile(filepath, childCtx.sync, this.currentFile)) as Template[]
|
||||
yield liquid.renderer.renderTemplates(templates, childCtx, emitter)
|
||||
}
|
||||
ctx.depthLimit.release(1)
|
||||
}
|
||||
|
||||
public * children (partials: boolean, sync: boolean): Generator<unknown, Template[]> {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { isValueToken, toEnumerable } from '../util'
|
||||
import { createScope } from '../context/scope'
|
||||
import { ValueToken, Liquid, Tag, evalToken, Emitter, Hash, TagToken, TopLevelToken, Context, Template, ParseStream } from '..'
|
||||
import { TablerowloopDrop } from '../drop/tablerowloop-drop'
|
||||
import { Parser } from '../parser'
|
||||
@@ -45,12 +44,15 @@ export default class extends Tag {
|
||||
const limit = (args.limit === undefined) ? collection.length : args.limit
|
||||
|
||||
collection = collection.slice(offset, offset + limit)
|
||||
if (!collection.length) return
|
||||
|
||||
if (!this.templates.length) return
|
||||
|
||||
const cols = args.cols || collection.length
|
||||
|
||||
const r = this.liquid.renderer
|
||||
const tablerowloop = new TablerowloopDrop(collection.length, cols, this.collection.getText(), this.variable)
|
||||
const scope = createScope({ tablerowloop })
|
||||
ctx.push(scope)
|
||||
const scope = ctx.push({ tablerowloop })
|
||||
|
||||
for (let idx = 0; idx < collection.length; idx++, tablerowloop.next()) {
|
||||
scope[this.variable] = collection[idx]
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
export * from './template'
|
||||
export * from './template-impl'
|
||||
export * from './tag'
|
||||
export * from './tag-options-adapter'
|
||||
export * from './filter'
|
||||
export * from './filter-impl-options'
|
||||
export * from './hash'
|
||||
|
||||
@@ -2,7 +2,6 @@ import { toPromise } from '../util'
|
||||
import { Context } from '../context'
|
||||
import { Output } from '../template'
|
||||
import { OutputToken } from '../tokens'
|
||||
import { defaultOptions } from '../liquid-options'
|
||||
|
||||
describe('Output', function () {
|
||||
const emitter: any = { write: (html: string) => (emitter.html += html), html: '' }
|
||||
@@ -30,59 +29,4 @@ describe('Output', function () {
|
||||
await toPromise(output.render(scope, emitter))
|
||||
return expect(emitter.html).toBe('FOO')
|
||||
})
|
||||
it('should respect to .toString()', async () => {
|
||||
const scope = new Context({ obj: { toString: () => 'FOO' } })
|
||||
const output = new Output(token, liquid)
|
||||
await toPromise(output.render(scope, emitter))
|
||||
return expect(emitter.html).toBe('FOO')
|
||||
})
|
||||
describe('when keepOutputType is enabled', () => {
|
||||
const emitter: any = {
|
||||
write: (html: any) => {
|
||||
if (emitter.keepOutputType && typeof html !== 'string') {
|
||||
emitter.html = html
|
||||
} else {
|
||||
emitter.html += html as string
|
||||
}
|
||||
},
|
||||
html: '',
|
||||
keepOutputType: true
|
||||
}
|
||||
const token = { content: 'foo', input: 'foo' } as OutputToken
|
||||
|
||||
beforeEach(() => { emitter.html = '' })
|
||||
|
||||
it('should respect output variable number type', async () => {
|
||||
const scope = new Context({
|
||||
foo: 42
|
||||
}, { ...defaultOptions, keepOutputType: true })
|
||||
const output = new Output(token, liquid)
|
||||
await toPromise(output.render(scope, emitter))
|
||||
return expect(emitter.html).toBe(42)
|
||||
})
|
||||
it('should respect output variable boolean type', async () => {
|
||||
const scope = new Context({
|
||||
foo: true
|
||||
}, { ...defaultOptions, keepOutputType: true })
|
||||
const output = new Output(token, liquid)
|
||||
await toPromise(output.render(scope, emitter))
|
||||
return expect(emitter.html).toBe(true)
|
||||
})
|
||||
it('should respect output variable object type', async () => {
|
||||
const scope = new Context({
|
||||
foo: 'test'
|
||||
}, { ...defaultOptions, keepOutputType: true })
|
||||
const output = new Output(token, liquid)
|
||||
await toPromise(output.render(scope, emitter))
|
||||
return expect(emitter.html).toBe('test')
|
||||
})
|
||||
it('should respect output variable string type', async () => {
|
||||
const scope = new Context({
|
||||
foo: { a: { b: 42 } }
|
||||
}, { ...defaultOptions, keepOutputType: true })
|
||||
const output = new Output(token, liquid)
|
||||
await toPromise(output.render(scope, emitter))
|
||||
return expect(emitter.html).toEqual({ a: { b: 42 } })
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { isFunction } from '../util'
|
||||
import { Hash } from './hash'
|
||||
import { Tag, TagClass, TagRenderReturn } from './tag'
|
||||
import { TagToken, TopLevelToken } from '../tokens'
|
||||
import { Emitter } from '../emitters'
|
||||
import { Context } from '../context'
|
||||
import type { Liquid } from '../liquid'
|
||||
|
||||
export interface TagImplOptions {
|
||||
[key: string]: any
|
||||
parse?: (this: Tag & TagImplOptions, token: TagToken, remainingTokens: TopLevelToken[]) => void;
|
||||
render: (this: Tag & TagImplOptions, ctx: Context, emitter: Emitter, hash: Record<string, any>) => TagRenderReturn;
|
||||
}
|
||||
|
||||
export function createTagClass (options: TagImplOptions): TagClass {
|
||||
return class extends Tag {
|
||||
constructor (token: TagToken, tokens: TopLevelToken[], liquid: Liquid) {
|
||||
super(token, tokens, liquid)
|
||||
if (isFunction(options.parse)) {
|
||||
options.parse.call(this, token, tokens)
|
||||
}
|
||||
}
|
||||
* render (ctx: Context, emitter: Emitter): TagRenderReturn {
|
||||
const hash = (yield new Hash(this.token.args, ctx.opts.keyValueSeparator).render(ctx)) as Record<string, any>
|
||||
return yield options.render.call(this, ctx, emitter, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,11 @@ export class Limiter {
|
||||
this.base += +count
|
||||
}
|
||||
}
|
||||
release (count: number) {
|
||||
if (+count > 0) {
|
||||
this.base -= +count
|
||||
}
|
||||
}
|
||||
check (count: number) {
|
||||
if (+count > 0) {
|
||||
assert(+count <= this.limit, this.message)
|
||||
|
||||
@@ -10,7 +10,16 @@ export type Trie<T> = {
|
||||
needBoundary?: true
|
||||
} & Record<string, any>
|
||||
|
||||
// Tries are built once per input object and reused: the Tokenizer rebuilds them
|
||||
// on every instantiation, but `input` (operators/literalValues) is a stable
|
||||
// reference. WeakMap-keying by `input` lets short-lived operator objects (and
|
||||
// their tries) be garbage collected. The returned trie is treated as read-only
|
||||
// by callers (matchTrie only reads it); do not mutate it.
|
||||
const trieCache = new WeakMap<TrieInput<any>, Trie<any>>()
|
||||
|
||||
export function createTrie<T = any> (input: TrieInput<T>): Trie<T> {
|
||||
const cached = trieCache.get(input)
|
||||
if (cached) return cached
|
||||
const trie: Trie<T> = {}
|
||||
for (const [name, data] of Object.entries(input)) {
|
||||
let node = trie
|
||||
@@ -29,5 +38,6 @@ export function createTrie<T = any> (input: TrieInput<T>): Trie<T> {
|
||||
node.data = data
|
||||
node.end = true
|
||||
}
|
||||
trieCache.set(input, trie)
|
||||
return trie
|
||||
}
|
||||
|
||||
@@ -188,6 +188,14 @@ describe('util/strftime', function () {
|
||||
it('should have higher priority than H', () => {
|
||||
expect(t(then, '%0H')).toBe('03')
|
||||
})
|
||||
it('should allow pad width up to MAX_STRFTIME_PAD', () => {
|
||||
expect(t(now, '%100000d').length).toBe(100000)
|
||||
expect(t(now, `%${1_000_000}d`).length).toBe(1_000_000)
|
||||
})
|
||||
it('should throw when pad width exceeds MAX_STRFTIME_PAD', () => {
|
||||
expect(() => t(now, `%${1024 * 1024 + 1}d`)).toThrow('strftime pad width limit exceeded')
|
||||
expect(() => t(now, '%5000000d')).toThrow('strftime pad width limit exceeded')
|
||||
})
|
||||
})
|
||||
describe('modifier field', () => {
|
||||
it('should ignore E modifier', () => {
|
||||
|
||||
+14
-8
@@ -1,13 +1,15 @@
|
||||
import { changeCase, padStart, padEnd } from './underscore'
|
||||
import { LiquidDate } from './liquid-date'
|
||||
import type { Limiter } from './limiter'
|
||||
import { assert } from './assert'
|
||||
|
||||
/** Per-conversion numeric width cap for strftime (%N, %15d, …). */
|
||||
export const MAX_STRFTIME_PAD = 1024 * 1024
|
||||
|
||||
const rFormat = /%([-_0^#:]+)?(\d+)?([EO])?(.)/
|
||||
interface FormatOptions {
|
||||
flags: Record<string, boolean>;
|
||||
width?: string;
|
||||
modifier?: string;
|
||||
memoryLimit?: Pick<Limiter, 'use'>;
|
||||
}
|
||||
|
||||
// prototype extensions
|
||||
@@ -98,8 +100,8 @@ const formatCodes: Record<string, FormatCodeHandler> = {
|
||||
M: (d: LiquidDate) => d.getMinutes(),
|
||||
N: (d: LiquidDate, opts: FormatOptions) => {
|
||||
const width = Number(opts.width) || 9
|
||||
assertPadWidth(width)
|
||||
const str = String(d.getMilliseconds()).slice(0, width)
|
||||
opts.memoryLimit?.use(width - str.length)
|
||||
return padEnd(str, width, '0')
|
||||
},
|
||||
p: (d: LiquidDate) => (d.getHours() < 12 ? 'AM' : 'PM'),
|
||||
@@ -123,25 +125,29 @@ const formatCodes: Record<string, FormatCodeHandler> = {
|
||||
}
|
||||
formatCodes.h = formatCodes.b
|
||||
|
||||
export function strftime (d: LiquidDate, formatStr: string, memoryLimit?: Pick<Limiter, 'use'>) {
|
||||
export function strftime (d: LiquidDate, formatStr: string) {
|
||||
let output = ''
|
||||
let remaining = formatStr
|
||||
let match
|
||||
while ((match = rFormat.exec(remaining))) {
|
||||
output += remaining.slice(0, match.index)
|
||||
remaining = remaining.slice(match.index + match[0].length)
|
||||
output += format(d, match, memoryLimit)
|
||||
output += format(d, match)
|
||||
}
|
||||
return output + remaining
|
||||
}
|
||||
|
||||
function format (d: LiquidDate, match: RegExpExecArray, memoryLimit?: Pick<Limiter, 'use'>) {
|
||||
function assertPadWidth (width: number) {
|
||||
assert(width <= MAX_STRFTIME_PAD, 'strftime pad width limit exceeded')
|
||||
}
|
||||
|
||||
function format (d: LiquidDate, match: RegExpExecArray) {
|
||||
const [input, flagStr = '', width, modifier, conversion] = match
|
||||
const convert = formatCodes[conversion]
|
||||
if (!convert) return input
|
||||
const flags: Record<string, boolean> = {}
|
||||
for (const flag of flagStr) flags[flag] = true
|
||||
let ret = String(convert(d, { flags, width, modifier, memoryLimit }))
|
||||
let ret = String(convert(d, { flags, width, modifier }))
|
||||
let padChar = padSpaceChars.has(conversion) ? ' ' : '0'
|
||||
let padWidth = Number(width) || padWidths[conversion] || 0
|
||||
if (flags['^']) ret = ret.toUpperCase()
|
||||
@@ -149,6 +155,6 @@ function format (d: LiquidDate, match: RegExpExecArray, memoryLimit?: Pick<Limit
|
||||
if (flags['_']) padChar = ' '
|
||||
else if (flags['0']) padChar = '0'
|
||||
if (flags['-']) padWidth = 0
|
||||
memoryLimit?.use(Number(padWidth) - ret.length)
|
||||
else assertPadWidth(padWidth)
|
||||
return padStart(ret, padWidth, padChar)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { Drop } from '../drop/drop'
|
||||
|
||||
export const toString = Object.prototype.toString
|
||||
export const hasOwnProperty = Object.prototype.hasOwnProperty
|
||||
const toLowerCase = String.prototype.toLowerCase
|
||||
|
||||
export const hasOwnProperty = Object.hasOwnProperty
|
||||
|
||||
export function isString (value: any): value is string {
|
||||
return typeof value === 'string'
|
||||
}
|
||||
@@ -42,6 +41,12 @@ export function stringify (value: any): string {
|
||||
return String(value)
|
||||
}
|
||||
|
||||
export function readArrayElement (arr: any[], index: number, ownPropertyOnly: boolean) {
|
||||
if (index < 0) index = arr.length + index
|
||||
if (ownPropertyOnly && !hasOwnProperty.call(arr, index)) return undefined
|
||||
return arr[index]
|
||||
}
|
||||
|
||||
export function toEnumerable<T = unknown> (val: any): T[] {
|
||||
val = toValue(val)
|
||||
if (isArray(val)) return val
|
||||
@@ -84,8 +89,7 @@ export function isUndefined (value: any): boolean {
|
||||
}
|
||||
|
||||
export function isArray (value: any): value is any[] {
|
||||
// be compatible with IE 8
|
||||
return toString.call(value) === '[object Array]'
|
||||
return Array.isArray(value)
|
||||
}
|
||||
|
||||
export function isArrayLike (value: any): value is any[] {
|
||||
|
||||
+2
-2
@@ -14,9 +14,9 @@ for demo in $(ls demo); do
|
||||
npm link liquidjs
|
||||
|
||||
if npm test; then
|
||||
echo [success] demo/webpack
|
||||
echo "[success] demo/$demo"
|
||||
else
|
||||
echo [fail] demo/webpack
|
||||
echo "[fail] demo/$demo"
|
||||
exit 1
|
||||
fi
|
||||
cd -
|
||||
|
||||
+1
-33
@@ -1,4 +1,4 @@
|
||||
import { TopLevelToken, TagToken, Tokenizer, Context, Liquid, Drop, toValueSync, LiquidError, IfTag } from '../..'
|
||||
import { Tokenizer, Context, Liquid, Drop, toValueSync, LiquidError, IfTag } from '../..'
|
||||
import { spawnSync } from 'child_process'
|
||||
import { resolve as resolvePath } from 'path'
|
||||
const LiquidUMD = require('../../dist/liquid.browser.umd.js').Liquid
|
||||
@@ -362,33 +362,8 @@ describe('Issues', function () {
|
||||
const html = await liquid.parseAndRender(tpl)
|
||||
expect(html).toMatch(/^\s*This is a love or luck potion.\s+This is a strength or health or love potion.\s*$/)
|
||||
})
|
||||
it('tag registration compatible to v9 #570', async () => {
|
||||
const liquid = new Liquid()
|
||||
liquid.registerTag('metadata_file', {
|
||||
parse (tagToken: TagToken, remainTokens: TopLevelToken[]) {
|
||||
this.str = tagToken.args
|
||||
},
|
||||
async render (ctx: Context) {
|
||||
const content = await Promise.resolve(`{{${this.str}}}`)
|
||||
return this.liquid.parseAndRender(content.toString(), ctx)
|
||||
}
|
||||
})
|
||||
const tpl = '{% metadata_file foo %}'
|
||||
const ctx = { foo: 'FOO' }
|
||||
const html = await liquid.parseAndRender(tpl, ctx)
|
||||
expect(html).toBe('FOO')
|
||||
})
|
||||
it('date filter should return parsed input when no format is provided #573', async () => {
|
||||
const liquid = new Liquid()
|
||||
liquid.registerTag('metadata_file', {
|
||||
parse (tagToken: TagToken, remainTokens: TopLevelToken[]) {
|
||||
this.str = tagToken.args
|
||||
},
|
||||
async render (ctx: Context) {
|
||||
const content = await Promise.resolve(`{{${this.str}}}`)
|
||||
return this.liquid.parseAndRender(content.toString(), ctx)
|
||||
}
|
||||
})
|
||||
const tpl = `{{ 'now' | date }}`
|
||||
const html = await liquid.parseAndRender(tpl)
|
||||
// sample: Thursday, February 2, 2023 at 6:25 pm +0000
|
||||
@@ -544,13 +519,6 @@ describe('Issues', function () {
|
||||
const result = engine.parseAndRenderSync(`\n{{ "foo" | pos }}`)
|
||||
expect(result).toEqual('\n[2,12] foo')
|
||||
})
|
||||
it("memoryLimit doesn't work in for tag #776", () => {
|
||||
const engine = new Liquid({
|
||||
memoryLimit: 1e5
|
||||
})
|
||||
const tpl = `{% for i in (1..1000000000) %} {{'a'}} {% endfor %}`
|
||||
expect(() => engine.parseAndRenderSync(tpl)).toThrow('memory alloc limit exceeded, line:1, col:1')
|
||||
})
|
||||
it('group_by_exp fails with object as input #785', () => {
|
||||
const site = {
|
||||
tags: {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Liquid } from '../../../src/liquid'
|
||||
|
||||
describe('ownPropertyOnly / inherited array indices', function () {
|
||||
const engine = new Liquid({ ownPropertyOnly: true })
|
||||
|
||||
function pollutedArrays () {
|
||||
// eslint-disable-next-line no-extend-native
|
||||
Array.prototype[0] = 'ARRAY_PROTO_POLLUTED'
|
||||
;(Object.prototype as any).secret = 'OBJECT_PROTO_POLLUTED'
|
||||
const a: any[] = []
|
||||
a.length = 1
|
||||
const o = {}
|
||||
return {
|
||||
a,
|
||||
o,
|
||||
cleanup () {
|
||||
delete (Array.prototype as any)[0]
|
||||
delete (Object.prototype as any).secret
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cases: [string, (ctx: ReturnType<typeof pollutedArrays>) => object, string][] = [
|
||||
['{{ a[0] }}', ({ a }) => ({ a }), ''],
|
||||
['{{ a[-1] }}', ({ a }) => ({ a }), ''],
|
||||
['{{ o.secret }}', ({ o }) => ({ o }), ''],
|
||||
['{{ a.first }}', ({ a }) => ({ a }), ''],
|
||||
['{{ a.last }}', ({ a }) => ({ a }), ''],
|
||||
['{{ a | first }}', ({ a }) => ({ a }), ''],
|
||||
['{{ a | last }}', ({ a }) => ({ a }), ''],
|
||||
['{% assign x = a | first %}{{ x }}', ({ a }) => ({ a }), '']
|
||||
]
|
||||
|
||||
it.each(cases)('%s', function (src, scopeFn, expected) {
|
||||
const ctx = pollutedArrays()
|
||||
try {
|
||||
expect(engine.parseAndRenderSync(src, scopeFn(ctx))).toBe(expected)
|
||||
} finally {
|
||||
ctx.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('still allows array length and size', function () {
|
||||
const { a, cleanup } = pollutedArrays()
|
||||
try {
|
||||
expect(engine.parseAndRenderSync('{{ a.size }}', { a })).toBe('1')
|
||||
const arr = [1, 2]
|
||||
expect(engine.parseAndRenderSync('{{ arr | first }}', { arr })).toBe('1')
|
||||
expect(engine.parseAndRenderSync('{{ arr[-1] }}', { arr })).toBe('2')
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -204,31 +204,21 @@ describe('filters/date', function () {
|
||||
return test('{{ "1990-12-31T23:00:00Z" | date: "%Y-%m-%dT%H:%M:%S" }}', '1991-01-01T04:30:00', undefined, optsWithDateFormat)
|
||||
})
|
||||
})
|
||||
describe('strftime width / memoryLimit', () => {
|
||||
it('should charge memoryLimit for huge numeric strftime widths', () => {
|
||||
const liquid = new Liquid({ memoryLimit: 500 })
|
||||
expect(() => liquid.parseAndRenderSync('{{ d | date: f }}', { d: 'now', f: '%5000000d' }))
|
||||
.toThrow('memory alloc limit exceeded')
|
||||
})
|
||||
it('should charge memoryLimit for array format PoC', () => {
|
||||
const liquid = new Liquid({ memoryLimit: 50, renderLimit: 1e9 })
|
||||
expect(() => liquid.parseAndRenderSync('{{ d | date: f }}', { d: 'now', f: ['a'.repeat(2000000)] }))
|
||||
.toThrow('memory alloc limit exceeded')
|
||||
})
|
||||
it('should charge memoryLimit for object toString format PoC', () => {
|
||||
const liquid = new Liquid({ memoryLimit: 50, renderLimit: 1e9 })
|
||||
const huge = 'a'.repeat(2000000)
|
||||
const f = { toString: () => huge }
|
||||
expect(() => liquid.parseAndRenderSync('{{ d | date: f }}', { d: 'now', f }))
|
||||
.toThrow('memory alloc limit exceeded')
|
||||
})
|
||||
it('should honor numeric strftime pad width when memoryLimit allows', () => {
|
||||
const liquid = new Liquid({ memoryLimit: 1e7 })
|
||||
describe('strftime width', () => {
|
||||
it('should honor numeric strftime pad width', () => {
|
||||
const liquid = new Liquid()
|
||||
const out = liquid.parseAndRenderSync('{{ d | date: f }}', { d: 'now', f: '%5000d' })
|
||||
expect(out.length).toBe(5000)
|
||||
const tight = new Liquid({ memoryLimit: 100 })
|
||||
expect(() => tight.parseAndRenderSync('{{ d | date: f }}', { d: 'now', f: '%5000d' }))
|
||||
.toThrow('memory alloc limit exceeded')
|
||||
})
|
||||
it('should honor large numeric strftime pad width up to the cap', () => {
|
||||
const liquid = new Liquid()
|
||||
const out = liquid.parseAndRenderSync('{{ d | date: f }}', { d: 'now', f: '%100000d' })
|
||||
expect(out.length).toBe(100000)
|
||||
})
|
||||
it('should throw when numeric strftime pad width is too large', () => {
|
||||
const liquid = new Liquid()
|
||||
expect(() => liquid.parseAndRenderSync('{{ d | date: f }}', { d: 'now', f: '%5000000d' }))
|
||||
.toThrow('strftime pad width limit exceeded')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -85,5 +85,9 @@ describe('filters/html', function () {
|
||||
expect(liquid.parseAndRenderSync('{{"<img\rsrc=x\ronerror=alert(1)>" | strip_html}}')).toBe('')
|
||||
expect(liquid.parseAndRenderSync('{{"<svg\nonload=alert(1)>" | strip_html}}')).toBe('')
|
||||
})
|
||||
it('should not loop on unclosed openers (GHSA-m7fp-h3p4-hr49)', function () {
|
||||
expect(liquid.parseAndRenderSync('{{ "a<" | strip_html }}')).toBe('a<')
|
||||
expect(liquid.parseAndRenderSync('{{ "hello<world<again" | strip_html }}')).toBe('hello<world<again')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -50,6 +50,9 @@ describe('filters/math', function () {
|
||||
expect(Number(html)).toBeCloseTo(3.357, 3)
|
||||
})
|
||||
it('should convert string', () => test('{{ "24" | modulo: "7" }}', '3'))
|
||||
it('should follow divisor sign for negative dividend', () => test('{{ -7 | modulo: 3 }}', '2'))
|
||||
it('should follow divisor sign for negative divisor', () => test('{{ 7 | modulo: -3 }}', '-2'))
|
||||
it('should follow divisor sign for negative float', () => test('{{ -4.5 | modulo: 3 }}', '1.5'))
|
||||
})
|
||||
describe('plus', function () {
|
||||
it('should return "6" for 4,2', () => test('{{ 4 | plus: 2 }}', '6'))
|
||||
@@ -70,6 +73,10 @@ describe('filters/math', function () {
|
||||
it('should return "183.36" for 183.357,2',
|
||||
() => test('{{183.357|round: 2}}', '183.36'))
|
||||
it('should convert string to number', () => test('{{"2.7"|round}}', '3'))
|
||||
it('odd number 1.005 should round correctly', () => test('{{1.005|round:2}}', '1.01'))
|
||||
it('odd number -1.005 should round correctly', () => test('{{num|round:2}}', { num: -1.005 }, '-1.01'))
|
||||
it('odd number 9.075 should round correctly', () => test('{{9.075|round:2}}', '9.08'))
|
||||
it('odd number -9.075 should round correctly', () => test('{{num|round:2}}', { num: -9.075 }, '-9.08'))
|
||||
})
|
||||
describe('times', function () {
|
||||
it('should return "6" for 3,2', () => test('{{ 3 | times: 2 }}', '6'))
|
||||
|
||||
@@ -4,15 +4,18 @@ import { mock, restore } from '../../stub/mockfs'
|
||||
describe('DoS related', function () {
|
||||
describe('#parseLimit', function () {
|
||||
afterEach(restore)
|
||||
|
||||
it('should throw when parse limit exceeded', async () => {
|
||||
const noLimit = new Liquid()
|
||||
const limit10 = new Liquid({ parseLimit: 10 })
|
||||
const limit90 = new Liquid({ parseLimit: 90 })
|
||||
const template = '{% capture bar %}{{ foo | bar: 3, a[3] }}{% endcapture %}'
|
||||
|
||||
await expect(noLimit.parseAndRender(template)).resolves.toBe('')
|
||||
await expect(limit10.parseAndRender(template)).rejects.toThrow('parse length limit exceeded')
|
||||
await expect(limit90.parseAndRender(template)).resolves.toBe('')
|
||||
})
|
||||
|
||||
it('should take included template into account', async () => {
|
||||
mock({
|
||||
'/small': 'Lorem ipsum',
|
||||
@@ -23,78 +26,151 @@ describe('DoS related', function () {
|
||||
await expect(liquid.parseAndRender('{% include "large" %}')).rejects.toThrow('parse length limit exceeded')
|
||||
})
|
||||
})
|
||||
describe('#renderLimit', () => {
|
||||
|
||||
describe('#templateLimit', () => {
|
||||
it('should throw when rendering too many templates', async () => {
|
||||
const src = '{% for i in (1..1000) %}{{i}},{% endfor %}'
|
||||
const noLimit = new Liquid()
|
||||
const limitSmall = new Liquid({ renderLimit: 0.01 })
|
||||
const limitLarge = new Liquid({ renderLimit: 2e4 })
|
||||
const limitSmall = new Liquid({ templateLimit: 100 })
|
||||
const limitLarge = new Liquid({ templateLimit: 2001 })
|
||||
await expect(noLimit.parseAndRender(src)).resolves.toMatch(/^1,2,3,4,5,.*,999,1000,$/)
|
||||
await expect(limitSmall.parseAndRender(src)).rejects.toThrow('template render limit exceeded')
|
||||
await expect(limitSmall.parseAndRender(src)).rejects.toThrow('template limit exceeded')
|
||||
await expect(limitLarge.parseAndRender(src)).resolves.toMatch(/^1,2,3,4,5,.*,999,1000,$/)
|
||||
})
|
||||
|
||||
it('should support reset when calling render', async () => {
|
||||
const src = '{% for i in (1..1000) %}{{i}},{% endfor %}'
|
||||
const liquid = new Liquid({ renderLimit: 0.01 })
|
||||
await expect(liquid.parseAndRender(src)).rejects.toThrow('template render limit exceeded')
|
||||
await expect(liquid.parseAndRender(src, {}, { renderLimit: 1e6 })).resolves.toMatch(/^1,2,3,4,5,.*,999,1000,$/)
|
||||
const liquid = new Liquid({ templateLimit: 100 })
|
||||
await expect(liquid.parseAndRender(src)).rejects.toThrow('template limit exceeded')
|
||||
await expect(liquid.parseAndRender(src, {}, { templateLimit: 2001 })).resolves.toMatch(/^1,2,3,4,5,.*,999,1000,$/)
|
||||
})
|
||||
|
||||
it('should take partials into account', async () => {
|
||||
mock({
|
||||
'/small': '{% for i in (1..5) %}{{i}}{% endfor %}',
|
||||
'/large': '{% for i in (1..50000000) %}{{i}}{% endfor %}'
|
||||
})
|
||||
const liquid = new Liquid({ root: '/', renderLimit: 1000 })
|
||||
await expect(liquid.parseAndRender('{% render "large" %}')).rejects.toThrow('template render limit exceeded')
|
||||
const liquid = new Liquid({ root: '/', templateLimit: 1000 })
|
||||
await expect(liquid.parseAndRender('{% render "large" %}')).rejects.toThrow('template limit exceeded')
|
||||
await expect(liquid.parseAndRender('{% render "small" %}')).resolves.toBe('12345')
|
||||
})
|
||||
it('should enforce renderLimit when for body has no template nodes', () => {
|
||||
const liquid = new Liquid({ memoryLimit: 1e9, renderLimit: 1 })
|
||||
expect(() => liquid.parseAndRenderSync('{%- for i in (1..5000000) -%}{%- endfor -%}', {}))
|
||||
.toThrow('template render limit exceeded')
|
||||
})
|
||||
it('should enforce renderLimit when tablerow body has no template nodes', () => {
|
||||
const liquid = new Liquid({ memoryLimit: 1e9, renderLimit: 1 })
|
||||
expect(() => liquid.parseAndRenderSync('{%- tablerow i in (1..1000000) cols:1 -%}{%- endtablerow -%}', {}))
|
||||
.toThrow('template render limit exceeded')
|
||||
})
|
||||
})
|
||||
describe('#memoryLimit', () => {
|
||||
it('should throw for too many array creation in filters', async () => {
|
||||
const array = Array(1e3).fill(0)
|
||||
const liquid = new Liquid({ memoryLimit: 100 })
|
||||
await expect(liquid.parseAndRender('{{ array | slice: 0, 3 | join }}', { array })).resolves.toBe('0 0 0')
|
||||
await expect(liquid.parseAndRender('{{ array | slice: 0, 300 | join }}', { array })).rejects.toThrow('memory alloc limit exceeded, line:1, col:1')
|
||||
|
||||
describe('#outputLengthLimit', () => {
|
||||
it('should throw when output length exceeded', async () => {
|
||||
const src = '{% for i in (1..1000) %}{{i}},{% endfor %}'
|
||||
const noLimit = new Liquid()
|
||||
const limitSmall = new Liquid({ outputLengthLimit: 10 })
|
||||
const limitLarge = new Liquid({ outputLengthLimit: 5000 })
|
||||
await expect(noLimit.parseAndRender(src)).resolves.toMatch(/^1,2,3,4,5,.*,999,1000,$/)
|
||||
await expect(limitSmall.parseAndRender(src)).rejects.toThrow('output length limit exceeded')
|
||||
await expect(limitLarge.parseAndRender(src)).resolves.toMatch(/^1,2,3,4,5,.*,999,1000,$/)
|
||||
})
|
||||
|
||||
it('should support reset when calling render', async () => {
|
||||
const array = Array(1e3).fill(0)
|
||||
const liquid = new Liquid({ memoryLimit: 100 })
|
||||
await expect(liquid.parseAndRender('{{ array | slice: 0, 300 | join }}', { array })).rejects.toThrow('memory alloc limit exceeded, line:1, col:1')
|
||||
await expect(liquid.parseAndRender('{{ array | slice: 0, 300 | join }}', { array }, { memoryLimit: 1e3 })).resolves.toBe(Array(300).fill(0).join(' '))
|
||||
const src = '{% for i in (1..1000) %}{{i}},{% endfor %}'
|
||||
const liquid = new Liquid({ outputLengthLimit: 10 })
|
||||
await expect(liquid.parseAndRender(src)).rejects.toThrow('output length limit exceeded')
|
||||
await expect(liquid.parseAndRender(src, {}, { outputLengthLimit: 5000 })).resolves.toMatch(/^1,2,3,4,5,.*,999,1000,$/)
|
||||
})
|
||||
it('should throw for too many array iteration in tags', async () => {
|
||||
const array = ['a']
|
||||
const liquid = new Liquid({ memoryLimit: 100 })
|
||||
const src = '{% for i in (1..count) %}{% assign array = array | concat: array %}{% endfor %}{{ array | join }}'
|
||||
await expect(liquid.parseAndRender(src, { array, count: 3 })).resolves.toBe('a a a a a a a a')
|
||||
await expect(liquid.parseAndRender(src, { array, count: 100 })).rejects.toThrow('memory alloc limit exceeded, line:1, col:26')
|
||||
|
||||
it('should take partials into account', async () => {
|
||||
mock({
|
||||
'/small': 'abc',
|
||||
'/large': '{% for i in (1..1000) %}{{i}}{% endfor %}'
|
||||
})
|
||||
const liquid = new Liquid({ root: '/', outputLengthLimit: 10 })
|
||||
await expect(liquid.parseAndRender('{% render "small" %}')).resolves.toBe('abc')
|
||||
await expect(liquid.parseAndRender('{% render "large" %}')).rejects.toThrow('output length limit exceeded')
|
||||
})
|
||||
it('should charge pop allocation to memoryLimit', async () => {
|
||||
const array = Array(1e3).fill(0)
|
||||
const liquid = new Liquid({ memoryLimit: 100 })
|
||||
await expect(liquid.parseAndRender('{{ array | pop | size }}', { array })).rejects.toThrow('memory alloc limit exceeded')
|
||||
|
||||
it('should enforce outputLengthLimit in sync render', () => {
|
||||
const liquid = new Liquid({ outputLengthLimit: 5 })
|
||||
expect(() => liquid.parseAndRenderSync('{% for i in (1..100) %}{{i}}{% endfor %}'))
|
||||
.toThrow('output length limit exceeded')
|
||||
})
|
||||
it('should charge sample allocation to memoryLimit', async () => {
|
||||
const array = Array(1e3).fill(0)
|
||||
const liquid = new Liquid({ memoryLimit: 100 })
|
||||
await expect(liquid.parseAndRender('{{ array | sample: 1 | size }}', { array })).rejects.toThrow('memory alloc limit exceeded')
|
||||
})
|
||||
it('should charge strip_html input length to memoryLimit', () => {
|
||||
const liquid = new Liquid({ memoryLimit: 100 })
|
||||
expect(() => liquid.parseAndRenderSync('{{ s | strip_html }}', { s: 'a'.repeat(200) }))
|
||||
.toThrow('memory alloc limit exceeded')
|
||||
|
||||
it('should enforce outputLengthLimit in stream render', async () => {
|
||||
const liquid = new Liquid({ outputLengthLimit: 5 })
|
||||
const tpl = liquid.parse('{% for i in (1..100) %}{{i}}{% endfor %}')
|
||||
const stream = liquid.renderToNodeStream(tpl)
|
||||
await expect(new Promise((resolve, reject) => {
|
||||
stream.on('error', reject)
|
||||
stream.on('end', resolve)
|
||||
})).rejects.toThrow('output length limit exceeded')
|
||||
})
|
||||
})
|
||||
|
||||
describe('#maxDepth', () => {
|
||||
function chain (depth: number, tag: string) {
|
||||
const templates: Record<string, string> = {}
|
||||
for (let i = 0; i < depth; i++) {
|
||||
templates[`t${i}`] = i === depth - 1 ? 'done' : `{% ${tag} "t${i + 1}" %}`
|
||||
}
|
||||
return templates
|
||||
}
|
||||
|
||||
it('should throw when include depth exceeded', async () => {
|
||||
const liquid = new Liquid({ templates: chain(3, 'include'), maxDepth: 2 })
|
||||
await expect(liquid.parseAndRender('{% include "t0" %}')).rejects.toThrow('template depth limit exceeded')
|
||||
})
|
||||
|
||||
it('should allow include within maxDepth', async () => {
|
||||
const liquid = new Liquid({ templates: chain(2, 'include'), maxDepth: 2 })
|
||||
await expect(liquid.parseAndRender('{% include "t0" %}')).resolves.toBe('done')
|
||||
})
|
||||
|
||||
it('should throw when render depth exceeded', async () => {
|
||||
const liquid = new Liquid({ templates: chain(3, 'render'), maxDepth: 2 })
|
||||
await expect(liquid.parseAndRender('{% render "t0" %}')).rejects.toThrow('template depth limit exceeded')
|
||||
})
|
||||
|
||||
it('should allow render within maxDepth', async () => {
|
||||
const liquid = new Liquid({ templates: chain(2, 'render'), maxDepth: 2 })
|
||||
await expect(liquid.parseAndRender('{% render "t0" %}')).resolves.toBe('done')
|
||||
})
|
||||
|
||||
it('should throw when layout depth exceeded', async () => {
|
||||
const liquid = new Liquid({
|
||||
templates: {
|
||||
a: '{% layout "b" %}body-a',
|
||||
b: '{% layout "c" %}body-b',
|
||||
c: 'body-c'
|
||||
},
|
||||
maxDepth: 2
|
||||
})
|
||||
await expect(liquid.parseAndRender('{% layout "a" %}root')).rejects.toThrow('template depth limit exceeded')
|
||||
})
|
||||
|
||||
it('should allow layout within maxDepth', async () => {
|
||||
const liquid = new Liquid({
|
||||
templates: {
|
||||
a: '{% layout "b" %}body-a',
|
||||
b: 'body-b'
|
||||
},
|
||||
maxDepth: 2
|
||||
})
|
||||
await expect(liquid.parseAndRender('{% layout "a" %}root')).resolves.toBe('body-b')
|
||||
})
|
||||
|
||||
it('should not count layout none toward depth', async () => {
|
||||
const liquid = new Liquid({ maxDepth: 0 })
|
||||
await expect(liquid.parseAndRender('{% layout none %}ok')).resolves.toBe('ok')
|
||||
})
|
||||
|
||||
it('should default maxDepth to 128', async () => {
|
||||
const liquid = new Liquid({ templates: chain(128, 'include') })
|
||||
await expect(liquid.parseAndRender('{% include "t0" %}')).resolves.toBe('done')
|
||||
const overflow = new Liquid({ templates: chain(129, 'include') })
|
||||
await expect(overflow.parseAndRender('{% include "t0" %}')).rejects.toThrow('template depth limit exceeded')
|
||||
})
|
||||
|
||||
it('should enforce maxDepth in sync render', () => {
|
||||
const liquid = new Liquid({ templates: chain(3, 'include'), maxDepth: 2 })
|
||||
expect(() => liquid.parseAndRenderSync('{% include "t0" %}')).toThrow('template depth limit exceeded')
|
||||
})
|
||||
})
|
||||
|
||||
describe('strip_html ReDoS', () => {
|
||||
// Regression for O(n^2) backtracking on unclosed `<script` / `<style` openers.
|
||||
// The previous regex stalled the event loop for ~10s on 350KB of `'<script'.repeat`.
|
||||
@@ -104,11 +180,13 @@ describe('DoS related', function () {
|
||||
const payload = '<script'.repeat(50000)
|
||||
expect(liquid.parseAndRenderSync('{{ x | strip_html }}', { x: payload })).toBe(payload)
|
||||
}, 1000)
|
||||
|
||||
it('should handle many unclosed <style openers in linear time', () => {
|
||||
const liquid = new Liquid()
|
||||
const payload = '<style'.repeat(50000)
|
||||
expect(liquid.parseAndRenderSync('{{ x | strip_html }}', { x: payload })).toBe(payload)
|
||||
}, 1000)
|
||||
|
||||
it('should handle <script openers that have > but no </script> in linear time', () => {
|
||||
const liquid = new Liquid()
|
||||
const payload = '<script>foo'.repeat(50000)
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { Liquid } from '../../../src/liquid'
|
||||
|
||||
describe('LiquidOptions#*keepOutputType*', function () {
|
||||
it('should respect keepOutputType', async function () {
|
||||
const engine = new Liquid({
|
||||
keepOutputType: true
|
||||
})
|
||||
const context = {
|
||||
'my-boolean': true,
|
||||
'my-number': 42,
|
||||
'my-string': 'test'
|
||||
}
|
||||
const booleanHtml = await engine.parseAndRender('{{my-boolean}}', context)
|
||||
expect(booleanHtml).toBe(true)
|
||||
const numberHtml = await engine.parseAndRender('{{my-number}}', context)
|
||||
expect(numberHtml).toBe(42)
|
||||
const html = await engine.parseAndRender('{{my-string}}', context)
|
||||
expect(html).toBe('test')
|
||||
const composedHtml = await engine.parseAndRender('{{my-string}}:{{my-number}}', context)
|
||||
expect(composedHtml).toBe('test:42')
|
||||
})
|
||||
|
||||
it('should respect keepOutputType = false as default', async function () {
|
||||
const engine = new Liquid()
|
||||
const context = {
|
||||
'my-boolean': true,
|
||||
'my-number': 42,
|
||||
'my-string': 'test'
|
||||
}
|
||||
const booleanHtml = await engine.parseAndRender('{{my-boolean}}', context)
|
||||
expect(booleanHtml).toBe('true')
|
||||
const numberHtml = await engine.parseAndRender('{{my-number}}', context)
|
||||
expect(numberHtml).toBe('42')
|
||||
const html = await engine.parseAndRender('{{my-string}}', context)
|
||||
expect(html).toBe('test')
|
||||
const composedHtml = await engine.parseAndRender('{{my-string}}:{{my-number}}', context)
|
||||
expect(composedHtml).toBe('test:42')
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Liquid, Context, isFalsy } from '../../../src'
|
||||
import { mock, restore } from '../../stub/mockfs'
|
||||
import { drainStream } from '../../stub/stream'
|
||||
import { ThrowingTag } from '../../stub/tags'
|
||||
import { resolve } from 'path'
|
||||
|
||||
describe('Liquid', function () {
|
||||
@@ -231,11 +232,7 @@ describe('Liquid', function () {
|
||||
'/root/error.html': 'A{%throwingTag%}B'
|
||||
})
|
||||
engine = new Liquid({ root: ['/root/'] })
|
||||
engine.registerTag('throwingTag', {
|
||||
render: function () {
|
||||
throw new Error('intended render error')
|
||||
}
|
||||
})
|
||||
engine.registerTag('throwingTag', ThrowingTag)
|
||||
})
|
||||
afterEach(restore)
|
||||
it('should render a simple value', async () => {
|
||||
@@ -244,7 +241,7 @@ describe('Liquid', function () {
|
||||
})
|
||||
it('should throw RenderError when tag throws', async () => {
|
||||
const stream = await engine.renderFileToNodeStream('error.html')
|
||||
expect(drainStream(stream)).rejects.toThrow(/intended render error/)
|
||||
expect(drainStream(stream)).rejects.toThrow(/intended error/)
|
||||
})
|
||||
})
|
||||
describe('#analyze', () => {
|
||||
|
||||
@@ -1,38 +1,57 @@
|
||||
import { Liquid } from '../../../src/liquid'
|
||||
import { Tag } from '../../../src/template/tag'
|
||||
import type { Context } from '../../../src/context'
|
||||
import type { TagToken, TopLevelToken } from '../../../src/tokens'
|
||||
|
||||
describe('liquid#registerTag()', function () {
|
||||
it('should support render to simple string', async () => {
|
||||
class SimpleStringTag extends Tag {
|
||||
render () {
|
||||
return 'B'
|
||||
}
|
||||
}
|
||||
const liquid = new Liquid()
|
||||
liquid.registerTag('simple-string', {
|
||||
render: () => 'B'
|
||||
})
|
||||
liquid.registerTag('simple-string', SimpleStringTag)
|
||||
const html = await liquid.parseAndRender(`A{% simple-string %}C`)
|
||||
return expect(html).toBe('ABC')
|
||||
})
|
||||
it('should support async tag render', async () => {
|
||||
class AsyncStringTag extends Tag {
|
||||
async render () {
|
||||
return 'B'
|
||||
}
|
||||
}
|
||||
const liquid = new Liquid()
|
||||
liquid.registerTag('async-string', {
|
||||
render: async () => 'B'
|
||||
})
|
||||
liquid.registerTag('async-string', AsyncStringTag)
|
||||
const html = await liquid.parseAndRender(`A{% async-string %}C`)
|
||||
return expect(html).toBe('ABC')
|
||||
})
|
||||
it('should have access to ctx in render()', async () => {
|
||||
class DynamicStringTag extends Tag {
|
||||
async render (ctx: Context) {
|
||||
return ctx.get(['c'])
|
||||
}
|
||||
}
|
||||
const liquid = new Liquid()
|
||||
liquid.registerTag('dynamic-string', {
|
||||
render: async (ctx) => ctx.get(['c'])
|
||||
})
|
||||
liquid.registerTag('dynamic-string', DynamicStringTag)
|
||||
const html = await liquid.parseAndRender(`A{% dynamic-string %}C`, {
|
||||
c: 'B'
|
||||
})
|
||||
return expect(html).toBe('ABC')
|
||||
})
|
||||
it('should have access to tag arguments', async () => {
|
||||
class ArgumentReflectorTag extends Tag {
|
||||
variable: string
|
||||
constructor (token: TagToken, remainTokens: TopLevelToken[], liquid: Liquid) {
|
||||
super(token, remainTokens, liquid)
|
||||
this.variable = token.args.split('=')[1]
|
||||
}
|
||||
async render (ctx: Context) {
|
||||
return ctx.get([this.variable])
|
||||
}
|
||||
}
|
||||
const liquid = new Liquid()
|
||||
liquid.registerTag('argument-reflector', {
|
||||
parse: function (token) { this.variable = token.args.split('=')[1] },
|
||||
render: async function (ctx) { return ctx.get(this.variable) }
|
||||
})
|
||||
liquid.registerTag('argument-reflector', ArgumentReflectorTag)
|
||||
const html = await liquid.parseAndRender(`A{% argument-reflector variable=c %}C`, {
|
||||
c: 'B'
|
||||
})
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Liquid } from '../../../src/liquid'
|
||||
import { Drop } from '../../../src/drop/drop'
|
||||
|
||||
describe('scope security', function () {
|
||||
let liquid: Liquid
|
||||
|
||||
beforeEach(function () {
|
||||
liquid = new Liquid()
|
||||
})
|
||||
|
||||
it('should iterate plain objects via inherited Symbol.iterator (ownPropertyOnly exception)', async function () {
|
||||
// eslint-disable-next-line no-extend-native
|
||||
(Object.prototype as any)[Symbol.iterator] = function * () { yield 'inherited' }
|
||||
try {
|
||||
await expect(liquid.parseAndRender(
|
||||
'{% for x in obj %}{{ x }}{% endfor %}',
|
||||
{ obj: {} }
|
||||
)).resolves.toBe('inherited')
|
||||
} finally {
|
||||
delete (Object.prototype as any)[Symbol.iterator]
|
||||
}
|
||||
})
|
||||
|
||||
it('should not read inherited size on plain objects', async function () {
|
||||
const obj = Object.create({ size: 99 })
|
||||
obj.own = 'yes'
|
||||
await expect(liquid.parseAndRender('{{ obj.size }}', { obj })).resolves.toBe('1')
|
||||
})
|
||||
|
||||
it('should read inherited size when ownPropertyOnly=false', async function () {
|
||||
liquid = new Liquid({ ownPropertyOnly: false })
|
||||
const obj = Object.create({ size: 99 })
|
||||
await expect(liquid.parseAndRender('{{ obj.size }}', { obj })).resolves.toBe('99')
|
||||
})
|
||||
|
||||
it('should still iterate Drop with Symbol.iterator', async function () {
|
||||
class IterableDrop extends Drop {
|
||||
* [Symbol.iterator] () {
|
||||
yield 'a'
|
||||
yield 'b'
|
||||
}
|
||||
}
|
||||
await expect(liquid.parseAndRender(
|
||||
'{% for x in drop %}{{ x }}{% endfor %}',
|
||||
{ drop: new IterableDrop() }
|
||||
)).resolves.toBe('ab')
|
||||
})
|
||||
|
||||
it('should block own blocked keys when ownPropertyOnly=true', async function () {
|
||||
const scope = JSON.parse('{"__proto__": {"polluted": true}, "constructor": {"name": "Custom"}, "name": "Alice"}')
|
||||
await expect(liquid.parseAndRender('{{ __proto__.polluted }}', scope)).resolves.toBe('')
|
||||
await expect(liquid.parseAndRender('{{ constructor.name }}', scope)).resolves.toBe('')
|
||||
await expect(liquid.parseAndRender('{{ name }}', scope)).resolves.toBe('Alice')
|
||||
})
|
||||
|
||||
it('should block inherited properties when ownPropertyOnly=true', async function () {
|
||||
const scope = { foo: Object.create({ __proto__: { bar: 'BAR' }, constructor: { name: 'Evil' } }) }
|
||||
await expect(liquid.parseAndRender('{{ foo.__proto__ }}', scope)).resolves.toBe('')
|
||||
await expect(liquid.parseAndRender('{{ foo.constructor }}', scope)).resolves.toBe('')
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,8 @@ import { RenderError } from '../../../src/util/error'
|
||||
import { Liquid } from '../../../src/liquid'
|
||||
import { resolve } from 'path'
|
||||
import { mock, restore } from '../../stub/mockfs'
|
||||
import { throwIntendedError, rejectIntendedError } from '../../stub/util'
|
||||
import { throwIntendedError } from '../../stub/util'
|
||||
import { ThrowingTag, RejectingTag, ThrowsOnParseTag } from '../../stub/tags'
|
||||
|
||||
const strictEngine = new Liquid({
|
||||
strictVariables: true,
|
||||
@@ -13,9 +14,9 @@ const strictCatchingEngine = new Liquid({
|
||||
strictVariables: true,
|
||||
strictFilters: true
|
||||
})
|
||||
strictEngine.registerTag('throwingTag', { render: throwIntendedError })
|
||||
strictEngine.registerTag('throwingTag', ThrowingTag)
|
||||
strictEngine.registerFilter('throwingFilter', throwIntendedError)
|
||||
strictCatchingEngine.registerTag('throwingTag', { render: throwIntendedError })
|
||||
strictCatchingEngine.registerTag('throwingTag', ThrowingTag)
|
||||
strictCatchingEngine.registerFilter('throwingFilter', throwIntendedError)
|
||||
|
||||
describe('error', function () {
|
||||
@@ -83,8 +84,8 @@ describe('error', function () {
|
||||
engine = new Liquid({
|
||||
root: '/'
|
||||
})
|
||||
engine.registerTag('throwingTag', { render: throwIntendedError })
|
||||
engine.registerTag('rejectingTag', { render: rejectIntendedError })
|
||||
engine.registerTag('throwingTag', ThrowingTag)
|
||||
engine.registerTag('rejectingTag', RejectingTag)
|
||||
engine.registerFilter('throwingFilter', throwIntendedError)
|
||||
})
|
||||
it('should throw RenderError when tag throws', async function () {
|
||||
@@ -244,10 +245,7 @@ describe('error', function () {
|
||||
let engine: Liquid
|
||||
beforeEach(function () {
|
||||
engine = new Liquid()
|
||||
engine.registerTag('throwsOnParse', {
|
||||
parse: throwIntendedError,
|
||||
render: () => ''
|
||||
})
|
||||
engine.registerTag('throwsOnParse', ThrowsOnParseTag)
|
||||
})
|
||||
it('should throw ParseError when filter not defined', async function () {
|
||||
await expect(strictEngine.parseAndRender('{{1 | a}}')).rejects.toMatchObject({
|
||||
@@ -337,11 +335,7 @@ describe('error', function () {
|
||||
engine = new Liquid({
|
||||
root: '/'
|
||||
})
|
||||
engine.registerTag('throwingTag', {
|
||||
render: function () {
|
||||
throw new Error('intended error')
|
||||
}
|
||||
})
|
||||
engine.registerTag('throwingTag', ThrowingTag)
|
||||
})
|
||||
it('should throw RenderError when tag throws', function () {
|
||||
const src = '{%throwingTag%}'
|
||||
|
||||
@@ -7,9 +7,6 @@ describe('tags/for', function () {
|
||||
let liquid: Liquid, scope: Scope
|
||||
beforeEach(function () {
|
||||
liquid = new Liquid()
|
||||
liquid.registerTag('throwingTag', {
|
||||
render: function () { throw new Error('intended render error') }
|
||||
})
|
||||
scope = {
|
||||
one: 1,
|
||||
// eslint-disable-next-line
|
||||
@@ -123,6 +120,18 @@ describe('tags/for', function () {
|
||||
const html = await liquid.parseAndRender(src, scope)
|
||||
return expect(html).toBe('b')
|
||||
})
|
||||
|
||||
it('should goto else when limit empties collection', async function () {
|
||||
const src = '{%for c in alpha limit:0%}a{%else%}b{%endfor%}'
|
||||
const html = await liquid.parseAndRender(src, scope)
|
||||
return expect(html).toBe('b')
|
||||
})
|
||||
|
||||
it('should goto else when offset past end', async function () {
|
||||
const src = '{%for c in alpha offset:10%}a{%else%}b{%endfor%}'
|
||||
const html = await liquid.parseAndRender(src, scope)
|
||||
return expect(html).toBe('b')
|
||||
})
|
||||
})
|
||||
|
||||
it('should support for with forloop', async function () {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { throwIntendedError, rejectIntendedError } from './util'
|
||||
import { Tag } from '../../src/template/tag'
|
||||
import type { TagToken, TopLevelToken } from '../../src/tokens'
|
||||
import type { Liquid } from '../../src/liquid'
|
||||
|
||||
export class ThrowingTag extends Tag {
|
||||
render () {
|
||||
throwIntendedError()
|
||||
}
|
||||
}
|
||||
|
||||
export class RejectingTag extends Tag {
|
||||
async render () {
|
||||
await rejectIntendedError()
|
||||
}
|
||||
}
|
||||
|
||||
export class ThrowsOnParseTag extends Tag {
|
||||
constructor (token: TagToken, remainTokens: TopLevelToken[], liquid: Liquid) {
|
||||
super(token, remainTokens, liquid)
|
||||
throwIntendedError()
|
||||
}
|
||||
render () {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -1,8 +1,9 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es6",
|
||||
"module":"CommonJS",
|
||||
"lib": ["es2015", "es2016", "es2017", "dom"],
|
||||
"target": "ES2020",
|
||||
"module":"ES2020",
|
||||
"lib": ["ES2020", "dom"],
|
||||
"moduleResolution": "node",
|
||||
"sourceMap": true,
|
||||
"outDir": "dist",
|
||||
"declaration": true,
|
||||
|
||||
Reference in New Issue
Block a user