mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-12 19:00:39 -07:00
Compare commits
101
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7910e4996c | ||
|
|
dbbf628803 | ||
|
|
26ea2856c7 | ||
|
|
a55f543f49 | ||
|
|
d1d517d1ec | ||
|
|
1c816d4fc3 | ||
|
|
34877950bf | ||
|
|
75c815a4d7 | ||
|
|
f1f896c29d | ||
|
|
0ee6dbb511 | ||
|
|
30e04ba16d | ||
|
|
e2311dfd6e | ||
|
|
2def22c85e | ||
|
|
4af7be695c | ||
|
|
05c47da46d | ||
|
|
66011d14b0 | ||
|
|
1cdf10b57d | ||
|
|
4f9a49988a | ||
|
|
f41c1fc02f | ||
|
|
db4348507e | ||
|
|
e743da0020 | ||
|
|
8f69a08399 | ||
|
|
529dd67eeb | ||
|
|
abc058be0f | ||
|
|
521177e3f6 | ||
|
|
75e06eff92 | ||
|
|
0ad2b11ab1 | ||
|
|
97d829116c | ||
|
|
35d5230263 | ||
|
|
94440a0653 | ||
|
|
95ddefc056 | ||
|
|
1b85fdaa9c | ||
|
|
93c38c7c6d | ||
|
|
c7a291b46b | ||
|
|
eb4683ee3f | ||
|
|
f1fc573a65 | ||
|
|
524cd92cfe | ||
|
|
0d9e797889 | ||
|
|
3cd024d652 | ||
|
|
85233e0568 | ||
|
|
02403a1879 | ||
|
|
1c6316111d | ||
|
|
71aa1b1998 | ||
|
|
350f95c8f7 | ||
|
|
955b7971c0 | ||
|
|
8686876067 | ||
|
|
3a02eb12bf | ||
|
|
906707833e | ||
|
|
a2da822cb8 | ||
|
|
86fc135d9e | ||
|
|
5d953132e8 | ||
|
|
2858271c8f | ||
|
|
d22945ed5f | ||
|
|
4f7d2fd84a | ||
|
|
597ce7305f | ||
|
|
d7fa8ba5f1 | ||
|
|
1b356d350d | ||
|
|
e55128850e | ||
|
|
e8e502c585 | ||
|
|
b8bc4db46c | ||
|
|
68d500c18a | ||
|
|
de12359bfd | ||
|
|
025c40f0f2 | ||
|
|
2f414f8e40 | ||
|
|
40c52124d7 | ||
|
|
ae0c07e60b | ||
|
|
3b9202465e | ||
|
|
fc42ad7548 | ||
|
|
050a7fc68e | ||
|
|
0fdc5c79da | ||
|
|
90d2ecb107 | ||
|
|
0deb93eeae | ||
|
|
b0facc71f7 | ||
|
|
5cb843f162 | ||
|
|
38a0f510b0 | ||
|
|
1a893f8023 | ||
|
|
bf3bd54051 | ||
|
|
a490a70da1 | ||
|
|
a5070af3e4 | ||
|
|
b070594fc7 | ||
|
|
25ef104446 | ||
|
|
59cf3c08db | ||
|
|
5f1a4cfdc9 | ||
|
|
8c32ab4f42 | ||
|
|
94a6715667 | ||
|
|
3492ff63f4 | ||
|
|
35a84421a6 | ||
|
|
bb08cfab1f | ||
|
|
e3ef574674 | ||
|
|
2af297f81a | ||
|
|
d61855bf72 | ||
|
|
734eb52b98 | ||
|
|
2980260fc1 | ||
|
|
062b351598 | ||
|
|
9107eb1b93 | ||
|
|
11f013bf24 | ||
|
|
ad039abea0 | ||
|
|
0b195b21eb | ||
|
|
28b14901d3 | ||
|
|
09aca0d7b3 | ||
|
|
d705888c8d |
+129
-2
@@ -14,7 +14,7 @@
|
||||
"login": "harttle",
|
||||
"name": "Jun Yang",
|
||||
"avatar_url": "https://avatars3.githubusercontent.com/u/4427974?v=4",
|
||||
"profile": "https://harttle.land",
|
||||
"profile": "https://github.com/harttle",
|
||||
"contributions": [
|
||||
"maintenance",
|
||||
"code"
|
||||
@@ -483,7 +483,8 @@
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/1557563?v=4",
|
||||
"profile": "http://santialbo.com",
|
||||
"contributions": [
|
||||
"doc"
|
||||
"doc",
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -711,6 +712,132 @@
|
||||
"contributions": [
|
||||
"doc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "timvandam",
|
||||
"name": "Tim van Dam",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/35376389?v=4",
|
||||
"profile": "https://tovd.dev",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "edh649",
|
||||
"name": "Ed Hanton",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/527604?v=4",
|
||||
"profile": "https://github.com/edh649",
|
||||
"contributions": [
|
||||
"doc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "gurdiga",
|
||||
"name": "Vlad GURDIGA",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/53922?v=4",
|
||||
"profile": "https://gurdiga.com",
|
||||
"contributions": [
|
||||
"doc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "StreakingMan",
|
||||
"name": "裸奔狂甩丁丁",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/30397306?v=4",
|
||||
"profile": "https://www.streakingman.com",
|
||||
"contributions": [
|
||||
"doc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "skynetigor",
|
||||
"name": "Ihor Panasiuk",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/20903171?v=4",
|
||||
"profile": "https://github.com/skynetigor",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "rosomri",
|
||||
"name": "Omri Rosner",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/68001413?v=4",
|
||||
"profile": "https://github.com/rosomri",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "immerrr",
|
||||
"name": "immerrr again",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/579798?v=4",
|
||||
"profile": "https://github.com/immerrr",
|
||||
"contributions": [
|
||||
"doc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "rongjiecomputer",
|
||||
"name": "Loo Rong Jie",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/13115060?v=4",
|
||||
"profile": "https://github.com/rongjiecomputer",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "MorielHarush",
|
||||
"name": "MorielHarush",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/93482738?v=4",
|
||||
"profile": "https://github.com/MorielHarush",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "peaktwilight",
|
||||
"name": "Peak Twilight",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/77903714?v=4",
|
||||
"profile": "https://doruk.ch",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "joecottam",
|
||||
"name": "Joe Cottam",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/44173086?v=4",
|
||||
"profile": "https://github.com/joecottam",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "timbze",
|
||||
"name": "Timmy Braun",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/35117769?v=4",
|
||||
"profile": "https://github.com/timbze",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "talboren",
|
||||
"name": "Tal",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/68807791?v=4",
|
||||
"profile": "https://github.com/talboren",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "VladimirFilonov",
|
||||
"name": "Vladimir Filonov",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/813224?v=4",
|
||||
"profile": "https://filonov.dev",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
}
|
||||
],
|
||||
"contributorsPerLine": 7,
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
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`.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
description: Project conventions for liquidjs
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
- Keep edits minimal: change only what the task requires, match existing style.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
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).
|
||||
@@ -28,13 +28,13 @@ jobs:
|
||||
- name: Build
|
||||
run: npm run build
|
||||
- name: Archive artifacts
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dist-${{ inputs.os }}
|
||||
path: dist
|
||||
- name: Archive npm failure logs
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: npm-logs
|
||||
name: npm-logs-${{ inputs.os }}
|
||||
path: ~/.npm/_logs
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Archive npm failure logs
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: npm-logs
|
||||
|
||||
@@ -24,7 +24,7 @@ jobs:
|
||||
branch: gh-pages
|
||||
folder: docs/public
|
||||
- name: Archive npm failure logs
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: npm-logs
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
- name: Archive npm failure logs
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: npm-logs
|
||||
|
||||
@@ -19,14 +19,14 @@ jobs:
|
||||
with:
|
||||
node-version: '20'
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: dist-${{ inputs.os }}
|
||||
path: dist
|
||||
- name: Check Performance
|
||||
run: npm run perf:diff
|
||||
- name: Archive npm failure logs
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: npm-logs
|
||||
|
||||
@@ -4,6 +4,11 @@ jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
@@ -12,7 +17,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '14'
|
||||
node-version: '22'
|
||||
- name: Install Dependencies
|
||||
run: npm ci
|
||||
- name: Release
|
||||
@@ -26,7 +31,7 @@ jobs:
|
||||
npx semantic-release --dry-run
|
||||
fi
|
||||
- name: Archive npm failure logs
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: npm-logs
|
||||
|
||||
+12
-12
@@ -14,13 +14,13 @@ jobs:
|
||||
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
|
||||
- os: ubuntu-latest
|
||||
timezone: Asia/Shanghai
|
||||
node-version: 15
|
||||
- os: ubuntu-latest
|
||||
timezone: Asia/Shanghai
|
||||
node-version: 14
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -34,17 +34,17 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: dist-${{ matrix.os }}
|
||||
path: dist
|
||||
- name: Run Test
|
||||
run: TZ=${{ matrix.timezone }} npm test
|
||||
- name: Archive npm failure logs
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: npm-logs
|
||||
name: test-npm-logs-${{ matrix.os }}-${{ matrix.node-version }}
|
||||
path: ~/.npm/_logs
|
||||
demo:
|
||||
name: Demo Check
|
||||
@@ -59,15 +59,15 @@ jobs:
|
||||
with:
|
||||
node-version: 22
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: dist-ubuntu-latest
|
||||
path: dist
|
||||
- name: Run Demo Test
|
||||
run: npm run test:demo
|
||||
- name: Archive npm failure logs
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: npm-logs
|
||||
name: demo-npm-logs
|
||||
path: ~/.npm/_logs
|
||||
|
||||
+161
@@ -1,3 +1,164 @@
|
||||
## [10.25.7](https://github.com/harttle/liquidjs/compare/v10.25.6...v10.25.7) (2026-04-23)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **filters:** support Buffer input in base64_encode to prevent binary data corruption ([#881](https://github.com/harttle/liquidjs/issues/881)) ([0ee6dbb](https://github.com/harttle/liquidjs/commit/0ee6dbb511aa926f6d490293282060abf3bab37f))
|
||||
|
||||
## [10.25.6](https://github.com/harttle/liquidjs/compare/v10.25.5...v10.25.6) (2026-04-19)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* nested block for layout ([#883](https://github.com/harttle/liquidjs/issues/883)) ([e2311df](https://github.com/harttle/liquidjs/commit/e2311dfd6e82f73509308aa8a3a1fafc92e226f0))
|
||||
|
||||
## [10.25.5](https://github.com/harttle/liquidjs/compare/v10.25.4...v10.25.5) (2026-04-07)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* enforce root containment for renderFile/parseFile lookups ([#870](https://github.com/harttle/liquidjs/issues/870)) ([f41c1fc](https://github.com/harttle/liquidjs/commit/f41c1fc02fe901598f3328118b42b13bc6bc9b04))
|
||||
* null date should return empty ([#868](https://github.com/harttle/liquidjs/issues/868)) ([#872](https://github.com/harttle/liquidjs/issues/872)) ([4f9a499](https://github.com/harttle/liquidjs/commit/4f9a49988a93c156524981e189a4fec238e682b8))
|
||||
* rounding negative away from zero when half ([#873](https://github.com/harttle/liquidjs/issues/873)) ([1cdf10b](https://github.com/harttle/liquidjs/commit/1cdf10b57d82f0592414efbfca19e204b37aea9f))
|
||||
|
||||
## [10.25.4](https://github.com/harttle/liquidjs/compare/v10.25.3...v10.25.4) (2026-04-07)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* sort and sort_natural filters bypass ownPropertyOnly ([#869](https://github.com/harttle/liquidjs/issues/869)) ([e743da0](https://github.com/harttle/liquidjs/commit/e743da0020d34e2ee547e1cc1a86b58377ebe1ce))
|
||||
|
||||
## [10.25.3](https://github.com/harttle/liquidjs/compare/v10.25.2...v10.25.3) (2026-04-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* precise memoryLimit for string replace ([abc058b](https://github.com/harttle/liquidjs/commit/abc058be0f33d6372cd2216f4945183167abeb25))
|
||||
* use realpath for fs.contains ([#867](https://github.com/harttle/liquidjs/issues/867)) ([529dd67](https://github.com/harttle/liquidjs/commit/529dd67eeb6b125637623d6a723601f0938d3613))
|
||||
|
||||
## [10.25.2](https://github.com/harttle/liquidjs/compare/v10.25.1...v10.25.2) (2026-03-25)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* handle undefined replacement argument in replace filter ([#864](https://github.com/harttle/liquidjs/issues/864)) ([0ad2b11](https://github.com/harttle/liquidjs/commit/0ad2b11ab15e7da608a9ef936b2a00a6a6517038))
|
||||
|
||||
## [10.25.1](https://github.com/harttle/liquidjs/compare/v10.25.0...v10.25.1) (2026-03-22)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* mem limiter for invalid ranges ([95ddefc](https://github.com/harttle/liquidjs/commit/95ddefc056a11a44d9e753fd47a39db2c241e578))
|
||||
* treat args for replace_first as literal ([35d5230](https://github.com/harttle/liquidjs/commit/35d523026345d80458df24c72e653db78b5d061d))
|
||||
|
||||
# [10.25.0](https://github.com/harttle/liquidjs/compare/v10.24.0...v10.25.0) (2026-03-07)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* path traversal vulnerability, [#851](https://github.com/harttle/liquidjs/issues/851) ([#855](https://github.com/harttle/liquidjs/issues/855)) ([3cd024d](https://github.com/harttle/liquidjs/commit/3cd024d652dc883c46307581e979fe32302adbac))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* export error types, resolving [#837](https://github.com/harttle/liquidjs/issues/837) ([#840](https://github.com/harttle/liquidjs/issues/840)) ([71aa1b1](https://github.com/harttle/liquidjs/commit/71aa1b1998a3a66e536af67c6ea8947a28616eaf))
|
||||
|
||||
# [10.24.0](https://github.com/harttle/liquidjs/compare/v10.23.0...v10.24.0) (2025-10-27)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **filters:** Add base64_encode and base64_decode filters for Shopify compatibility ([#828](https://github.com/harttle/liquidjs/issues/828)) ([86fc135](https://github.com/harttle/liquidjs/commit/86fc135d9ec0137689faf150535b9315e75ecc30))
|
||||
|
||||
# [10.23.0](https://github.com/harttle/liquidjs/compare/v10.22.0...v10.23.0) (2025-10-23)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Export specific tokens as types ([#824](https://github.com/harttle/liquidjs/issues/824)) ([4f7d2fd](https://github.com/harttle/liquidjs/commit/4f7d2fd84a8884e1009b13346d331a99b9721149))
|
||||
|
||||
# [10.22.0](https://github.com/harttle/liquidjs/compare/v10.21.1...v10.22.0) (2025-10-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* math filters coerce invalid string to 0, [#813](https://github.com/harttle/liquidjs/issues/813) ([#819](https://github.com/harttle/liquidjs/issues/819)) ([e8e502c](https://github.com/harttle/liquidjs/commit/e8e502c5854c9649bf7611a671a068dc260011d1))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* allow context access in liquidMethodMissing, [#808](https://github.com/harttle/liquidjs/issues/808) ([#820](https://github.com/harttle/liquidjs/issues/820)) ([e551288](https://github.com/harttle/liquidjs/commit/e55128850e507687f9d85a012fc3a72ac2550f3b))
|
||||
|
||||
## [10.21.1](https://github.com/harttle/liquidjs/compare/v10.21.0...v10.21.1) (2025-05-14)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* block.super with strictVariables, [#806](https://github.com/harttle/liquidjs/issues/806) ([#807](https://github.com/harttle/liquidjs/issues/807)) ([025c40f](https://github.com/harttle/liquidjs/commit/025c40f0f2f13efa62193c61d2fa56943917ac3c))
|
||||
|
||||
# [10.21.0](https://github.com/harttle/liquidjs/compare/v10.20.3...v10.21.0) (2025-02-23)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add find_index, has, and reject filters ([#799](https://github.com/harttle/liquidjs/issues/799)) ([0deb93e](https://github.com/harttle/liquidjs/commit/0deb93eeae4f530901e9a7d099bcc47207ad7385))
|
||||
|
||||
## [10.20.3](https://github.com/harttle/liquidjs/compare/v10.20.2...v10.20.3) (2025-02-09)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* empty tagToken.args since 10.20.0, fixes [#796](https://github.com/harttle/liquidjs/issues/796) ([38a0f51](https://github.com/harttle/liquidjs/commit/38a0f510b0a14baf35a368e9f07b536253394d06))
|
||||
|
||||
## [10.20.2](https://github.com/harttle/liquidjs/compare/v10.20.1...v10.20.2) (2025-01-19)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* consistent range syntax parsing, [#791](https://github.com/harttle/liquidjs/issues/791) ([a490a70](https://github.com/harttle/liquidjs/commit/a490a70da1ca2b479065c6618207bf4789db6b4f))
|
||||
* context for group_by_exp/where_exp/find_exp, [#790](https://github.com/harttle/liquidjs/issues/790) ([a5070af](https://github.com/harttle/liquidjs/commit/a5070af3e4b4d1ae3b6398c6638b130e50e1cf6e))
|
||||
|
||||
## [10.20.1](https://github.com/harttle/liquidjs/compare/v10.20.0...v10.20.1) (2025-01-04)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* break/continue stops whole template, [#783](https://github.com/harttle/liquidjs/issues/783) ([5f1a4cf](https://github.com/harttle/liquidjs/commit/5f1a4cfdc9d6bde31ce86ddc88b8f4bdf52f7893))
|
||||
* enumerate plain objects in where/where_exp, [#785](https://github.com/harttle/liquidjs/issues/785) ([#788](https://github.com/harttle/liquidjs/issues/788)) ([25ef104](https://github.com/harttle/liquidjs/commit/25ef104446731f4b6cb3a2e78f4d3b99efb635f4))
|
||||
* preserveTimezones support for RFC2822 date, [#784](https://github.com/harttle/liquidjs/issues/784) ([59cf3c0](https://github.com/harttle/liquidjs/commit/59cf3c08dbc5f2e5b109ffcb5375ae738b5ac386))
|
||||
|
||||
# [10.20.0](https://github.com/harttle/liquidjs/compare/v10.19.1...v10.20.0) (2024-12-28)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* `size`, `first`, `last` support arraylike objects, [#781](https://github.com/harttle/liquidjs/issues/781) ([35a8442](https://github.com/harttle/liquidjs/commit/35a84421a622b3a6657946b9395839da2b8e154a))
|
||||
* static variable analysis ([#770](https://github.com/harttle/liquidjs/issues/770)) ([3492ff6](https://github.com/harttle/liquidjs/commit/3492ff63f40abb8ff8adb8b6b0ce29408f99e19b))
|
||||
|
||||
## [10.19.1](https://github.com/harttle/liquidjs/compare/v10.19.0...v10.19.1) (2024-12-22)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add sideEffects=false to package.json ([734eb52](https://github.com/harttle/liquidjs/commit/734eb52b987d46d33cf8f03281a3773a0f1f0e4a))
|
||||
* inconsistent continue behaviour, fixes [#779](https://github.com/harttle/liquidjs/issues/779) ([e3ef574](https://github.com/harttle/liquidjs/commit/e3ef574674c5a21a37b3ffc929f514c8a3d0b866))
|
||||
* memoryLimit doesn't work in for tag, [#776](https://github.com/harttle/liquidjs/issues/776) ([2af297f](https://github.com/harttle/liquidjs/commit/2af297f81ac465feb3277ba7b92f7236409370b0))
|
||||
|
||||
# [10.19.0](https://github.com/harttle/liquidjs/compare/v10.18.0...v10.19.0) (2024-11-17)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* allow drops in property access ([#769](https://github.com/harttle/liquidjs/issues/769)) ([11f013b](https://github.com/harttle/liquidjs/commit/11f013bf249f1366306c1f0d728d45a95eb2df1a))
|
||||
* support Jekyll style `where`, [#768](https://github.com/harttle/liquidjs/issues/768) ([9107eb1](https://github.com/harttle/liquidjs/commit/9107eb1b93f5c11dca0ee0f0d2c1c8243849c3ab))
|
||||
|
||||
# [10.18.0](https://github.com/harttle/liquidjs/compare/v10.17.0...v10.18.0) (2024-10-16)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* expose FilterToken to filter `this`, [#762](https://github.com/harttle/liquidjs/issues/762) ([d705888](https://github.com/harttle/liquidjs/commit/d705888c8d46d9dd95fcb41c0fb7bfbaf647eddd))
|
||||
|
||||
# [10.17.0](https://github.com/harttle/liquidjs/compare/v10.16.7...v10.17.0) (2024-09-22)
|
||||
|
||||
|
||||
|
||||
@@ -53,9 +53,10 @@ For more details, refer to the [Setup Guide][setup].
|
||||
## Who's Using LiquidJS?
|
||||
|
||||
- [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.
|
||||
- [Semgrep](https://github.com/returntocorp/semgrep): Lightweight static analysis for many languages.
|
||||
- [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.
|
||||
@@ -63,6 +64,7 @@ For more details, refer to the [Setup Guide][setup].
|
||||
- [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.
|
||||
|
||||
Feel free to create a PR or contact me to add your use case into this list!
|
||||
|
||||
@@ -71,31 +73,31 @@ Feel free to create a PR or contact me to add your use case into this list!
|
||||
If you personally love LiquidJS or it's benefiting your business, please consider financially support us via [GitHub Sponsors](https://github.com/sponsors/harttle). Special thanks to our sponsors!
|
||||
|
||||
<!-- FINANCIAL-CONTRIBUTORS-BEGIN -->
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://www.opensense.com/"><img src="https://images.opencollective.com/opensense-inc/bf840ae/logo/256.png?height=100" width="100px;" alt="Opensense Inc."/><br /><sub><b>Opensense</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://www.11ty.dev/"><img src="https://avatars.githubusercontent.com/u/35147177?v=4?s=100" width="100px;" alt="Eleventy"/><br /><sub><b>Eleventy</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://about.me/peterdehaan"><img src="https://avatars2.githubusercontent.com/u/557895?v=4?s=100" width="100px;" alt="Peter deHaan"/><br /><sub><b>Peter deHaan</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://opencollective.com/touchless"><img src="https://images.opencollective.com/touchless/273bc74/logo/256.png?height=100" width="100px;" alt="Touchless"/><br /><sub><b>Touchless</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://www.dropkiq.com/"><img src="https://images.opencollective.com/1bertlol/43a8ea8/logo/256.png?height=100" width="100px;" alt="Adam Darrah"/><br /><sub><b>Dropkiq</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://dailycontributors.com/"><img src="https://images.opencollective.com/dailycontributors/3c2e057/logo/256.png?height=100&width=100" width="100px;" alt="Dailycontributors"/><br /><sub><b>Dailycontributors</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/coni2k"><img src="https://avatars0.githubusercontent.com/u/1284601?v=4?s=100" width="100px;" alt="coni2k"/><br /><sub><b>Serkan Holat</b></sub></a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/amit777"><img src="https://avatars0.githubusercontent.com/u/2703309?v=4?s=100" width="100px;" alt="amit777"/><br /><sub><b>amit777</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://opencollective.com/khaled-salem"><img src="https://images.opencollective.com/khaled-salem/avatar/256.png?height=256" width="100px;" alt="Khaled Salem"/><br /><sub><b>Khaled Salem</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://sentry.io/"><img src="https://avatars.githubusercontent.com/u/1396951?v=4?s=100" width="100px;" alt="Sentry"/><br /><sub><b>Sentry</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://www.checkoutblocks.com/"><img src="https://avatars.githubusercontent.com/u/114603307?v=4?s=100" width="100px;" alt="Checkout Blocks"/><br /><sub><b>Checkout Blocks</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://customer.io/"><img src="https://avatars.githubusercontent.com/u/1152079?v=4?s=100" width="100px;" alt="Customer IO"/><br /><sub><b>Customer IO</b></sub></a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/15fathoms"><img src="https://avatars.githubusercontent.com/u/79156039?v=4?s=100" width="100px;" alt="Emmanuel Cartelli"/><br /><sub><b>Emmanuel Cartelli</b></sub></a><br /></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/microsoft"><img src="https://avatars.githubusercontent.com/u/6154722?v=4?s=100" width="100px;" alt="Microsoft"/><br /><sub><b>Microsoft</b></sub></a><br /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://www.pakstyle.pk/"><img src="https://images.opencollective.com/pakstyle/2b81605/logo/256.png?height=100" width="100px;" alt="PakStyle.pk"/><br /><sub><b>PakStyle.pk</b></sub></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<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 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://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/>
|
||||
<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://github.com/talboren" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/68807791?v=4&s=100" height="80" style="vertical-align: middle;" alt="Tal" title="Tal (@talboren)"/></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://dailycontributors.com/" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/dailycontributors/3c2e057/logo/256.png?height=50&width=100" width="120" style="vertical-align: middle;" alt="Dailycontributors" title="Dailycontributors"/></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>
|
||||
<br/>
|
||||
<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>
|
||||
<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://about.me/peterdehaan" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars2.githubusercontent.com/u/557895?v=4&s=100" height="80" style="vertical-align: middle;" alt="Peter deHaan" title="Peter deHaan"/></a>
|
||||
<a href="https://github.com/coni2k" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars0.githubusercontent.com/u/1284601?v=4&s=100" height="80" style="vertical-align: middle;" alt="Serkan Holat" title="Serkan Holat"/></a>
|
||||
<a href="https://github.com/amit777" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars0.githubusercontent.com/u/2703309?v=4&s=100" height="80" style="vertical-align: middle;" alt="amit777" title="amit777"/></a>
|
||||
<a href="https://opencollective.com/khaled-salem" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/khaled-salem/avatar/256.png?height=256" height="80" style="vertical-align: middle;" alt="Khaled Salem" title="Khaled Salem"/></a>
|
||||
<a href="https://github.com/15fathoms" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://avatars.githubusercontent.com/u/79156039?v=4&s=100" height="80" style="vertical-align: middle;" alt="Emmanuel Cartelli" title="Emmanuel Cartelli"/></a>
|
||||
<a href="https://opencollective.com/cartelli-emmanuel" style="display: inline-block; vertical-align: middle; margin: 8px;"><img src="https://images.opencollective.com/cartelli-emmanuel/avatar/256.png?height=100" height="80" style="vertical-align: middle;" alt="Cartelli Emmanuel" title="Cartelli Emmanuel"/></a>
|
||||
</p>
|
||||
<!-- FINANCIAL-CONTRIBUTORS-END -->
|
||||
|
||||
## Contributors ✨
|
||||
@@ -108,7 +110,7 @@ Want to contribute? see [Contribution Guidelines][contribution]. Thanks goes to
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://harttle.land"><img src="https://avatars3.githubusercontent.com/u/4427974?v=4?s=100" width="100px;" alt="Jun Yang"/><br /><sub><b>Jun Yang</b></sub></a><br /><a href="#maintenance-harttle" title="Maintenance">🚧</a> <a href="https://github.com/harttle/liquidjs/commits?author=harttle" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/harttle"><img src="https://avatars3.githubusercontent.com/u/4427974?v=4?s=100" width="100px;" alt="Jun Yang"/><br /><sub><b>Jun Yang</b></sub></a><br /><a href="#maintenance-harttle" title="Maintenance">🚧</a> <a href="https://github.com/harttle/liquidjs/commits?author=harttle" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/chenos"><img src="https://avatars0.githubusercontent.com/u/2993310?v=4?s=100" width="100px;" alt="chenos"/><br /><sub><b>chenos</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=chenos" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://zachleat.com/"><img src="https://avatars2.githubusercontent.com/u/39355?v=4?s=100" width="100px;" alt="Zach Leatherman"/><br /><sub><b>Zach Leatherman</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/issues?q=author%3Azachleat" title="Bug reports">🐛</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/thardy"><img src="https://avatars3.githubusercontent.com/u/120636?v=4?s=100" width="100px;" alt="Tim Hardy"/><br /><sub><b>Tim Hardy</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=thardy" title="Code">💻</a></td>
|
||||
@@ -173,7 +175,7 @@ Want to contribute? see [Contribution Guidelines][contribution]. Thanks goes to
|
||||
<tr>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/ameyaapte1"><img src="https://avatars.githubusercontent.com/u/16054747?v=4?s=100" width="100px;" alt="Ameya Apte"/><br /><sub><b>Ameya Apte</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=ameyaapte1" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/tbdrz"><img src="https://avatars.githubusercontent.com/u/50599116?v=4?s=100" width="100px;" alt="tbdrz"/><br /><sub><b>tbdrz</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=tbdrz" title="Documentation">📖</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="http://santialbo.com"><img src="https://avatars.githubusercontent.com/u/1557563?v=4?s=100" width="100px;" alt="Santi Albo"/><br /><sub><b>Santi Albo</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=santialbo" title="Documentation">📖</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="http://santialbo.com"><img src="https://avatars.githubusercontent.com/u/1557563?v=4?s=100" width="100px;" alt="Santi Albo"/><br /><sub><b>Santi Albo</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=santialbo" title="Documentation">📖</a> <a href="https://github.com/harttle/liquidjs/commits?author=santialbo" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/YahangWu"><img src="https://avatars.githubusercontent.com/u/12295975?v=4?s=100" width="100px;" alt="Yahang Wu"/><br /><sub><b>Yahang Wu</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=YahangWu" title="Documentation">📖</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/hongl-1"><img src="https://avatars.githubusercontent.com/u/101576612?v=4?s=100" width="100px;" alt="hongl"/><br /><sub><b>hongl</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=hongl-1" title="Documentation">📖</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/zxx-457"><img src="https://avatars.githubusercontent.com/u/114141362?v=4?s=100" width="100px;" alt="zxx-457"/><br /><sub><b>zxx-457</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=zxx-457" title="Documentation">📖</a></td>
|
||||
@@ -206,6 +208,24 @@ Want to contribute? see [Contribution Guidelines][contribution]. Thanks goes to
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://vrugtehagel.nl"><img src="https://avatars.githubusercontent.com/u/41021050?v=4?s=100" width="100px;" alt="Koen"/><br /><sub><b>Koen</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=vrugtehagel" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://neamar.fr"><img src="https://avatars.githubusercontent.com/u/536844?v=4?s=100" width="100px;" alt="Matthieu Bacconnier"/><br /><sub><b>Matthieu Bacconnier</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=Neamar" title="Documentation">📖</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://tovd.dev"><img src="https://avatars.githubusercontent.com/u/35376389?v=4?s=100" width="100px;" alt="Tim van Dam"/><br /><sub><b>Tim van Dam</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=timvandam" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/edh649"><img src="https://avatars.githubusercontent.com/u/527604?v=4?s=100" width="100px;" alt="Ed Hanton"/><br /><sub><b>Ed Hanton</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=edh649" title="Documentation">📖</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://gurdiga.com"><img src="https://avatars.githubusercontent.com/u/53922?v=4?s=100" width="100px;" alt="Vlad GURDIGA"/><br /><sub><b>Vlad GURDIGA</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=gurdiga" title="Documentation">📖</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://www.streakingman.com"><img src="https://avatars.githubusercontent.com/u/30397306?v=4?s=100" width="100px;" alt="裸奔狂甩丁丁"/><br /><sub><b>裸奔狂甩丁丁</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=StreakingMan" title="Documentation">📖</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/skynetigor"><img src="https://avatars.githubusercontent.com/u/20903171?v=4?s=100" width="100px;" alt="Ihor Panasiuk"/><br /><sub><b>Ihor Panasiuk</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=skynetigor" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/rosomri"><img src="https://avatars.githubusercontent.com/u/68001413?v=4?s=100" width="100px;" alt="Omri Rosner"/><br /><sub><b>Omri Rosner</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=rosomri" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/immerrr"><img src="https://avatars.githubusercontent.com/u/579798?v=4?s=100" width="100px;" alt="immerrr again"/><br /><sub><b>immerrr again</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=immerrr" title="Documentation">📖</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/rongjiecomputer"><img src="https://avatars.githubusercontent.com/u/13115060?v=4?s=100" width="100px;" alt="Loo Rong Jie"/><br /><sub><b>Loo Rong Jie</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=rongjiecomputer" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/MorielHarush"><img src="https://avatars.githubusercontent.com/u/93482738?v=4?s=100" width="100px;" alt="MorielHarush"/><br /><sub><b>MorielHarush</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=MorielHarush" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://doruk.ch"><img src="https://avatars.githubusercontent.com/u/77903714?v=4?s=100" width="100px;" alt="Peak Twilight"/><br /><sub><b>Peak Twilight</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=peaktwilight" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/joecottam"><img src="https://avatars.githubusercontent.com/u/44173086?v=4?s=100" width="100px;" alt="Joe Cottam"/><br /><sub><b>Joe Cottam</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=joecottam" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/timbze"><img src="https://avatars.githubusercontent.com/u/35117769?v=4?s=100" width="100px;" alt="Timmy Braun"/><br /><sub><b>Timmy Braun</b></sub></a><br /><a href="https://github.com/harttle/liquidjs/commits?author=timbze" title="Code">💻</a></td>
|
||||
<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>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ Only the latest major version is supported with security updates. It can be chan
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please contact yangjvn@126.com to report a vulnerability or change request.
|
||||
Please contact harttleharttle@gmail.com to report a vulnerability or change request.
|
||||
|
||||
- If the vulnerability in question affects common use cases, it will be treated as a bug and fixed very soon (typically within 1 week).
|
||||
- Otherwise, it'll be scheduled in the same priority of feature request (which is lower than bugs).
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
rm -rf docs/source/api
|
||||
typedoc --plugin typedoc-plugin-missing-exports ./src --gitRevision master --out docs/source/api
|
||||
@@ -0,0 +1,24 @@
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const src = path.join(root, 'CHANGELOG.md')
|
||||
|
||||
let content = fs.readFileSync(src, 'utf8').replace(/\r\n/g, '\n')
|
||||
|
||||
const lines = content.split('\n')
|
||||
lines[0] = lines[0]
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
content = lines.join('\n')
|
||||
|
||||
content = content
|
||||
.replace(/{%/g, '{% raw %}{%{% endraw %}')
|
||||
.replace(/\{\{/g, '{% raw %}{{{% endraw %}')
|
||||
|
||||
const enFrontmatter = '---\ntitle: Changelog\nauto: true\n---\n\n'
|
||||
const zhFrontmatter = '---\ntitle: 更新日志\nauto: true\n---\n\n'
|
||||
|
||||
fs.writeFileSync(path.join(root, 'docs/source/tutorials/changelog.md'), enFrontmatter + content)
|
||||
fs.writeFileSync(path.join(root, 'docs/source/zh-cn/tutorials/changelog.md'), zhFrontmatter + content)
|
||||
@@ -1,15 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
cd docs
|
||||
cp ../CHANGELOG.md source/tutorials/changelog.md
|
||||
sed -i \
|
||||
-e 's/{%/{% raw %}{%{% endraw %}/g' \
|
||||
-e 's/{{/{% raw %}{{{% endraw %}/g' \
|
||||
-e '1 s/"/\"/g' \
|
||||
-e '1 s/</\</g' \
|
||||
-e '1 s/>/\>/g' \
|
||||
source/tutorials/changelog.md
|
||||
cp source/tutorials/changelog.md source/zh-cn/tutorials/changelog.md
|
||||
|
||||
sed -i -e '1i\---\ntitle: Changelog\nauto: true\n---\n' source/tutorials/changelog.md
|
||||
sed -i -e '1i\---\ntitle: 更新日志\nauto: true\n---\n' source/zh-cn/tutorials/changelog.md
|
||||
@@ -0,0 +1,39 @@
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const readme = fs.readFileSync(path.join(root, 'README.md'), 'utf8').replace(/\r\n/g, '\n')
|
||||
|
||||
function extractSection (text, beginMarker, endMarker) {
|
||||
const lines = text.split('\n')
|
||||
let inside = false
|
||||
const result = []
|
||||
for (const line of lines) {
|
||||
if (line.includes(endMarker)) inside = false
|
||||
if (inside) result.push(line)
|
||||
if (line.includes(beginMarker)) inside = true
|
||||
}
|
||||
return result.join('\n')
|
||||
}
|
||||
|
||||
function transformContributors (html) {
|
||||
return html
|
||||
.replace(/<br \/>.*?<\/td>/g, '</a></td>')
|
||||
.replace(/width="[^"]*"/g, '')
|
||||
.replace(/\n/g, '')
|
||||
.replace(/<\/tr>\s*<tr>/g, '')
|
||||
}
|
||||
|
||||
function transformFinancial (html) {
|
||||
return html
|
||||
.replace(/<br \/>.*?<\/td>/g, '</a></td>')
|
||||
.replace(/\n/g, '')
|
||||
.replace(/<\/tr>\s*<tr>/g, '')
|
||||
}
|
||||
|
||||
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 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)
|
||||
@@ -1,26 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Run `sed` in a way that's compatible with both macOS (BSD) and Linux (GNU)
|
||||
sedi() {
|
||||
if [[ "$OSTYPE" == "darwin"* ]]; then
|
||||
/usr/bin/sed -i '' "$@"
|
||||
else
|
||||
sed -i "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
# create docs/themes/navy/layout/partial/all-contributors.swig
|
||||
awk '/ALL-CONTRIBUTORS-LIST:START/{flag=1;next}/ALL-CONTRIBUTORS-LIST:END/{flag=0}flag' README.md | \
|
||||
sed 's/<br \/>.*<\/td>/<\/a><\/td>/g' | \
|
||||
sed 's/width="[^"]*"//g' | \
|
||||
tr -d '\n' | \
|
||||
sed 's/<\/tr>\s*<tr>//g' \
|
||||
> docs/themes/navy/layout/partial/all-contributors.swig
|
||||
|
||||
# create docs/themes/navy/layout/partial/financial-contributors.swig
|
||||
awk '/FINANCIAL-CONTRIBUTORS-BEGIN/{flag=1;next}/FINANCIAL-CONTRIBUTORS-END/{flag=0}flag' README.md | \
|
||||
sed 's/<br \/>.*<\/td>/<\/a><\/td>/g' | \
|
||||
sed 's/width="[^"]*"//g' | \
|
||||
tr -d '\n' | \
|
||||
sed 's/<\/tr>\s*<tr>//g' \
|
||||
> docs/themes/navy/layout/partial/financial-contributors.swig
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
BUNDLES=min npm run build
|
||||
mkdir -p docs/public/js/
|
||||
cp dist/liquid.browser.min.js docs/public/js/
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -ex
|
||||
|
||||
./bin/build-docs-liquid.sh
|
||||
./bin/build-contributors.sh
|
||||
./bin/build-apidoc.sh
|
||||
./bin/build-changelog.sh
|
||||
|
||||
cd docs
|
||||
npm ci
|
||||
npm run build
|
||||
cp CNAME public/
|
||||
|
||||
if [ "$HEXO_ALGOLIA_INDEXING_KEY" != "" ]; then
|
||||
npm run index
|
||||
fi
|
||||
@@ -1,36 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Prerequisites:
|
||||
# 1.imagemagick. try brew install imagemagick
|
||||
# 2. logo.png in size 512x512
|
||||
# 3. this script should be run with cwd docs/source/icon/
|
||||
|
||||
echo creating apple touch icons...
|
||||
apple=(57x57 60x60 72x72 76x76 114x114 120x120 144x144 152x152)
|
||||
for size in "${apple[@]}"; do
|
||||
echo $size
|
||||
convert logo.png -resize $size apple-touch-icon-$size.png
|
||||
done
|
||||
cp logo.png apple-touch-icon.png
|
||||
convert logo.png \
|
||||
\( +clone -alpha extract \
|
||||
-draw 'fill black polygon 0,0 0,80 80,0 fill white circle 80,80 80,0' \
|
||||
\( +clone -flip \) -compose Multiply -composite \
|
||||
\( +clone -flop \) -compose Multiply -composite \
|
||||
\) -alpha off -compose CopyOpacity -composite apple-touch-icon-precomposed.png
|
||||
|
||||
echo creating favicon...
|
||||
convert logo.png -resize 48x48 ../favicon.ico
|
||||
favicon=(16x16 32x32 96x96 160x160 196x196)
|
||||
for size in "${favicon[@]}"; do
|
||||
echo $size
|
||||
convert logo.png -resize $size favicon-$size.png
|
||||
done
|
||||
|
||||
echo creating mstile icons...
|
||||
mstile=(70x70 144x144 150x150 310x310)
|
||||
for size in "${mstile[@]}"; do
|
||||
echo $size
|
||||
convert logo.png -resize $size mstile-$size.png
|
||||
done
|
||||
convert mstile-150x150.png -gravity center -background white -extent 310x150 mstile-310x150.png
|
||||
@@ -0,0 +1,17 @@
|
||||
const { execSync } = require('child_process')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const version = require(path.join(root, 'package.json')).version
|
||||
|
||||
const fileLocal = path.join(root, 'dist/liquid.node.js')
|
||||
const fileLatest = path.join(root, `dist/liquid.node.${version}.js`)
|
||||
|
||||
if (!fs.existsSync(fileLatest)) {
|
||||
const url = `https://unpkg.com/liquidjs@${version}/dist/liquid.node.js`
|
||||
console.log(`Downloading liquidjs@${version}...`)
|
||||
execSync(`curl -sL -o "${fileLatest}" "${url}"`)
|
||||
}
|
||||
|
||||
execSync(`node benchmark/diff.js "${fileLocal}" "${fileLatest}"`, { cwd: root, stdio: 'inherit' })
|
||||
@@ -1,12 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
VERSION_LATEST=$(cat package.json | grep '"version":' | head -1 | awk -F'"' '{print $4}')
|
||||
FILE_LOCAL=dist/liquid.node.js
|
||||
FILE_LATEST=dist/liquid.node.$VERSION_LATEST.js
|
||||
URL_LATEST=https://unpkg.com/liquidjs@$VERSION_LATEST/dist/liquid.node.js
|
||||
|
||||
if [ ! -f "$FILE_LATEST" ]; then
|
||||
curl $URL_LATEST > $FILE_LATEST
|
||||
fi
|
||||
|
||||
exec node benchmark/diff.js $FILE_LOCAL $FILE_LATEST
|
||||
@@ -8,7 +8,7 @@
|
||||
"test": "echo not implemented",
|
||||
"start": "http-server -c-1 "
|
||||
},
|
||||
"author": "harttle <yangjvn@126.com>",
|
||||
"author": "harttle <harttleharttle@gmail.com>",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"http-server": "^0.11.1",
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ const engine = new Liquid({
|
||||
// layout files for `{% layout %}`
|
||||
layouts: process.cwd() + '/layouts',
|
||||
// partial files for `{% include %}` and `{% render %}`
|
||||
partials: process.cwd() + '/partials'
|
||||
partials: [process.cwd() + '/partials', 'node_modules']
|
||||
})
|
||||
|
||||
const ctx = {
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
set -ex
|
||||
set -e
|
||||
|
||||
npm start | grep 'LiquidJS Demo'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
set -x
|
||||
set -e
|
||||
|
||||
LOG_FILE=$(mktemp)
|
||||
npm start > $LOG_FILE 2>&1 &
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
set -ex
|
||||
set -e
|
||||
|
||||
npm start | grep 'NodeJS Demo for LiquidJS'
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
set -ex
|
||||
set -e
|
||||
|
||||
npm start | grep '\[11:8] {{ todo }}'
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
set -ex
|
||||
set -e
|
||||
|
||||
npm run build && npm start | grep 'TypeScript Demo for LiquidJS'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
set -ex
|
||||
set -e
|
||||
|
||||
npm run build
|
||||
npm start | grep 'Webpack Demo for LiquidJS'
|
||||
|
||||
+2
-2
@@ -30,8 +30,8 @@ prismjs:
|
||||
tab_replace: ""
|
||||
|
||||
algolia:
|
||||
applicationID: 0X19J927JZ
|
||||
apiKey: 533161d821384919672e4ce8a39451b3
|
||||
applicationID: QJ35YOZTU4
|
||||
apiKey: 8c6cbb824b4c5023f0bb2ef29e228bef
|
||||
indexName: liquidjs
|
||||
twitter: harttleharttle
|
||||
github: harttle/liquidjs
|
||||
|
||||
+1
-1
@@ -34,4 +34,4 @@
|
||||
"engines": {
|
||||
"node": ">=8.10.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ tutorials:
|
||||
operators: operators.html
|
||||
truth: truthy-and-falsy.html
|
||||
dos: dos.html
|
||||
static_analysis: static-analysis.html
|
||||
miscellaneous:
|
||||
migration9: migrate-to-9.html
|
||||
changelog: changelog.html
|
||||
@@ -50,10 +51,14 @@ filters:
|
||||
escape_once: escape_once.html
|
||||
find: find.html
|
||||
find_exp: find_exp.html
|
||||
find_index: find_index.html
|
||||
find_index_exp: find_index_exp.html
|
||||
first: first.html
|
||||
floor: floor.html
|
||||
group_by: group_by.html
|
||||
group_by_exp: group_by_exp.html
|
||||
has: has.html
|
||||
has_exp: has_exp.html
|
||||
inspect: inspect.html
|
||||
join: join.html
|
||||
json: json.html
|
||||
@@ -71,6 +76,8 @@ filters:
|
||||
push: push.html
|
||||
prepend: prepend.html
|
||||
raw: raw.html
|
||||
reject: reject.html
|
||||
reject_exp: reject_exp.html
|
||||
remove: remove.html
|
||||
remove_first: remove_first.html
|
||||
remove_last: remove_last.html
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
title: base64_decode
|
||||
---
|
||||
|
||||
{% since %}v10.24.0{% endsince %}
|
||||
|
||||
Decodes a Base64-formatted string back to its original text.
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{{ "b25lIHR3byB0aHJlZQ==" | base64_decode }}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
one two three
|
||||
```
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{{ "SGVsbG8sIFdvcmxkISBAIyQl" | base64_decode }}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
Hello, World! @#$%
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
title: base64_encode
|
||||
---
|
||||
|
||||
{% since %}v10.24.0{% endsince %}
|
||||
|
||||
Encodes a string into Base64 format.
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{{ "one two three" | base64_encode }}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
b25lIHR3byB0aHJlZQ==
|
||||
```
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{{ "Hello, World! @#$%" | base64_encode }}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
SGVsbG8sIFdvcmxkISBAIyQl
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: find_index
|
||||
---
|
||||
|
||||
{% since %}v10.21.0{% endsince %}
|
||||
|
||||
Return the 0-based index of the first object in an array for which the queried attribute has the given value or return `nil` if no item in the array satisfies the given criteria. For the following `members` array:
|
||||
|
||||
```javascript
|
||||
const members = [
|
||||
{ graduation_year: 2013, name: 'Jay' },
|
||||
{ graduation_year: 2014, name: 'John' },
|
||||
{ graduation_year: 2014, name: 'Jack' }
|
||||
]
|
||||
```
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{{ members | find_index: "graduation_year", 2014 | json }}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
1
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: find_index_exp
|
||||
---
|
||||
|
||||
{% since %}v10.21.0{% endsince %}
|
||||
|
||||
Return the 0-based index of the first object in an array for which the given expression evaluates to true or return `nil` if no item in the array satisfies the evaluated expression.
|
||||
|
||||
```javascript
|
||||
const members = [
|
||||
{ graduation_year: 2013, name: 'Jay' },
|
||||
{ graduation_year: 2014, name: 'John' },
|
||||
{ graduation_year: 2014, name: 'Jack' }
|
||||
]
|
||||
```
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{{ members | find_index_exp: "item", "item.graduation_year == 2014" | json }}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
1
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: has
|
||||
---
|
||||
|
||||
{% since %}v10.21.0{% endsince %}
|
||||
|
||||
Return `true` if the array includes an item for which the queried attribute has the given value or return `false` if no item in the array satisfies the given criteria. For the following `members` array:
|
||||
|
||||
```javascript
|
||||
const members = [
|
||||
{ graduation_year: 2013, name: 'Jay' },
|
||||
{ graduation_year: 2014, name: 'John' },
|
||||
{ graduation_year: 2014, name: 'Jack' }
|
||||
]
|
||||
```
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{{ members | has: "graduation_year", 2014 | json }}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
true
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: has_exp
|
||||
---
|
||||
|
||||
{% since %}v10.21.0{% endsince %}
|
||||
|
||||
Return `true` if an item exists in an array for which the given expression evaluates to true or return `false` if no item in the array satisfies the evaluated expression.
|
||||
|
||||
```javascript
|
||||
const members = [
|
||||
{ graduation_year: 2013, name: 'Jay' },
|
||||
{ graduation_year: 2014, name: 'John' },
|
||||
{ graduation_year: 2014, name: 'Jack' }
|
||||
]
|
||||
```
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{{ members | has_exp: "item", "item.graduation_year == 2014" | json }}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
true
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: hmac_sha256
|
||||
---
|
||||
|
||||
{% since %}vNEXT{% endsince %}
|
||||
|
||||
Converts a string into an SHA-256 hash using a hash message authentication code (HMAC). The secret key is passed as the filter argument. The output is a lowercase hexadecimal string.
|
||||
|
||||
Input
|
||||
|
||||
```liquid
|
||||
{%- assign secret_potion = 'Polyjuice' | hmac_sha256: 'Polina' -%}
|
||||
My secret potion: {{ secret_potion }}
|
||||
```
|
||||
|
||||
Output
|
||||
|
||||
```text
|
||||
My secret potion: 8e0d5d65cff1242a4af66c8f4a32854fd5fb80edcc8aabe9b302b29c7c71dc20
|
||||
```
|
||||
@@ -15,5 +15,7 @@ HTML/URI | escape, escape_once, url_encode, url_decode, strip_html, newline_to_b
|
||||
Array | slice, map, sort, sort_natural, uniq, where, where_exp, group_by, group_by_exp, find, find_exp, first, last, join, reverse, concat, compact, size, push, pop, shift, unshift
|
||||
Date | date, date_to_xmlschema, date_to_rfc822, date_to_string, date_to_long_string
|
||||
Misc | default, json, jsonify, inspect, raw, to_integer
|
||||
Base64 | base64_encode, base64_decode
|
||||
Crypto | sha256, hmac_sha256
|
||||
|
||||
[shopify/liquid]: https://github.com/Shopify/liquid
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
---
|
||||
title: reject
|
||||
---
|
||||
|
||||
{% since %}v10.21.0{% endsince %}
|
||||
|
||||
Creates an array excluding the objects with a given property value, or excluding [truthy][truthy] values by default when a property is not given.
|
||||
|
||||
In this example, assume you have a list of products and you want to filter out kitchen products. Using `reject`, you can create an array excluding only the products that have a `"type"` of `"kitchen"`.
|
||||
|
||||
Input
|
||||
```liquid
|
||||
All products:
|
||||
{% for product in products %}
|
||||
- {{ product.title }}
|
||||
{% endfor %}
|
||||
|
||||
{% assign non_kitchen_products = products | reject: "type", "kitchen" %}
|
||||
|
||||
Kitchen products:
|
||||
{% for product in non_kitchen_products %}
|
||||
- {{ product.title }}
|
||||
{% endfor %}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
All products:
|
||||
- Vacuum
|
||||
- Spatula
|
||||
- Television
|
||||
- Garlic press
|
||||
|
||||
Kitchen products:
|
||||
- Vacuum
|
||||
- Television
|
||||
```
|
||||
|
||||
Say instead you have a list of products and you want to exclude taxable products. You can `reject` with a property name but no target value to reject all products with a [truthy][truthy] `"taxable"` value.
|
||||
|
||||
Input
|
||||
```liquid
|
||||
All products:
|
||||
{% for product in products %}
|
||||
- {{ product.title }}
|
||||
{% endfor %}
|
||||
|
||||
{% assign not_taxed_products = products | reject: "taxable" %}
|
||||
|
||||
Available products:
|
||||
{% for product in not_taxed_products %}
|
||||
- {{ product.title }}
|
||||
{% endfor %}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
All products:
|
||||
- Vacuum
|
||||
- Spatula
|
||||
- Television
|
||||
- Garlic press
|
||||
|
||||
Available products:
|
||||
- Spatula
|
||||
- Television
|
||||
```
|
||||
|
||||
Additionally, `property` can be any valid Liquid variable expression as used in output syntax, except that the scope of this expression is within each item. For the following `products` array:
|
||||
|
||||
```javascript
|
||||
const products = [
|
||||
{ meta: { details: { class: 'A' } }, order: 1 },
|
||||
{ meta: { details: { class: 'B' } }, order: 2 },
|
||||
{ meta: { details: { class: 'B' } }, order: 3 }
|
||||
]
|
||||
```
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{% assign selected = products | reject: 'meta.details["class"]', "B" %}
|
||||
{% for item in selected -%}
|
||||
- {{ item.order }}
|
||||
{% endfor %}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
- 1
|
||||
```
|
||||
|
||||
## Jekyll style
|
||||
|
||||
{% since %}v10.21.0{% endsince %}
|
||||
|
||||
For Liquid users migrating from Jekyll, there's a `jekyllWhere` option to mimic the behavior of Jekyll's `where` filter. This option is set to `false` by default. When enabled, if `property` is an array, the target value is matched using `Array.includes` instead of `==`, which is particularly useful for excluding tags.
|
||||
|
||||
```javascript
|
||||
const pages = [
|
||||
{ tags: ["cat", "food"], title: 'Cat Food' },
|
||||
{ tags: ["dog", "food"], title: 'Dog Food' },
|
||||
]
|
||||
```
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{% assign selected = pages | reject: 'tags', "cat" %}
|
||||
{% for item in selected -%}
|
||||
- {{ item.title }}
|
||||
{% endfor %}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
Dog Food
|
||||
```
|
||||
|
||||
[truthy]: ../tutorials/truthy-and-falsy.html
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
title: reject_exp
|
||||
---
|
||||
|
||||
{% since %}v10.21.0{% endsince %}
|
||||
|
||||
Select all the objects in an array where the expression is false. In this example, assume you have a list of products and you want to hide your kitchen products. Using `reject_exp`, you can create an array that omits only the products that have a `"type"` of `"kitchen"`.
|
||||
|
||||
Input
|
||||
```liquid
|
||||
All products:
|
||||
{% for product in products %}
|
||||
- {{ product.title }}
|
||||
{% endfor %}
|
||||
|
||||
{% assign non_kitchen_products = products | reject_exp: "item", "item.type == 'kitchen'" %}
|
||||
|
||||
Kitchen products:
|
||||
{% for product in non_kitchen_products %}
|
||||
- {{ product.title }}
|
||||
{% endfor %}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
All products:
|
||||
- Vacuum
|
||||
- Spatula
|
||||
- Television
|
||||
- Garlic press
|
||||
|
||||
Kitchen products:
|
||||
- Vacuum
|
||||
- Television
|
||||
```
|
||||
|
||||
[truthy]: ../tutorials/truthy-and-falsy.html
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: sha256
|
||||
---
|
||||
|
||||
{% since %}vNEXT{% endsince %}
|
||||
|
||||
Converts a string into an SHA-256 hash. The output is a lowercase hexadecimal string.
|
||||
|
||||
Input
|
||||
|
||||
```liquid
|
||||
{%- assign secret_potion = 'Polyjuice' | sha256 -%}
|
||||
My secret potion: {{ secret_potion }}
|
||||
```
|
||||
|
||||
Output
|
||||
|
||||
```text
|
||||
My secret potion: 44ac1d7a2936e30a5de07082fd65d6fe9b1fb658a1a98bfe65bc5959beac5dd0
|
||||
```
|
||||
@@ -37,6 +37,7 @@ Kitchen products:
|
||||
```
|
||||
|
||||
Say instead you have a list of products and you only want to show those that are available to buy. You can `where` with a property name but no target value to include all products with a [truthy][truthy] `"available"` value.
|
||||
As a special case, the same will happen if the target value is given but evaluates to `undefined`.
|
||||
|
||||
Input
|
||||
```liquid
|
||||
@@ -70,7 +71,6 @@ The `where` filter can also be used to find a single object in an array when com
|
||||
Input
|
||||
```liquid
|
||||
{% assign new_shirt = products | where: "type", "shirt" | first %}
|
||||
|
||||
Featured product: {{ new_shirt.title }}
|
||||
```
|
||||
|
||||
@@ -103,4 +103,32 @@ Output
|
||||
- 3
|
||||
```
|
||||
|
||||
## Jekyll style
|
||||
|
||||
{% since %}v10.21.0{% endsince %}
|
||||
|
||||
For Liquid users migrating from Jekyll, there's a `jekyllWhere` option to mimic the behavior of Jekyll's `where` filter. This option is set to `false` by default. When enabled, if `property` is an array, the target value is matched using `Array.includes` instead of `==`, which is particularly useful for filtering tags. Additionally, a target value of `undefined` is treated normally, entries matched are exactly those which are themselves `undefined`.
|
||||
|
||||
This option affects other array selection filters as well, such as `reject` and `find`.
|
||||
|
||||
```javascript
|
||||
const pages = [
|
||||
{ tags: ["cat", "food"], title: 'Cat Food' },
|
||||
{ tags: ["dog", "food"], title: 'Dog Food' },
|
||||
]
|
||||
```
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{% assign selected = pages | where: 'tags', "cat" %}
|
||||
{% for item in selected -%}
|
||||
- {{ item.title }}
|
||||
{% endfor %}
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
Cat Food
|
||||
```
|
||||
|
||||
[truthy]: ../tutorials/truthy-and-falsy.html
|
||||
|
||||
@@ -10,6 +10,7 @@ const urlsToCache = [
|
||||
]
|
||||
const blackList = [
|
||||
/chrome-extension:/,
|
||||
/algolia.net/,
|
||||
/google-analytics.com.*collect/
|
||||
]
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ title: Echo
|
||||
|
||||
{% since %}v9.31.0{% endsince %}
|
||||
|
||||
Outputs an expression in the rendered HTML. This is identical to wrapping an expression in `{{` and `}}`, but works inside liquid tags and supports filters.
|
||||
Outputs an expression in the rendered HTML. This is identical to wrapping an expression in <code>{{</code> and <code>}}</code>, but works inside liquid tags and supports filters.
|
||||
|
||||
## echo
|
||||
|
||||
|
||||
@@ -20,7 +20,11 @@ Getting started and building is described in [CONTRIBUTING.md](https://github.co
|
||||
|
||||
## Financial Support
|
||||
|
||||
LiquidJS is Open Source and Free. To help it live and thrive, especially when LiquidJS is benefiting your business, please consider contribute on [GitHub Sponsors](https://github.com/sponsors/harttle) or [Open Collective][oc]. If I'm missing anything, find me via Twitter (harttleharttle) or email (harttleharttle at gmail), to add you into [the contributors table](https://github.com/harttle/liquidjs#contributors-).
|
||||
LiquidJS is Open Source and Free. To help it live and thrive, especially when LiquidJS is benefiting your business, please consider contribute on [GitHub Sponsors](https://github.com/sponsors/harttle) or [Open Collective][oc].
|
||||
|
||||
I'll add all financial contributors into [README.md](https://github.com/harttle/liquidjs#financial-support) and it'll be also shown on https://liquidjs.com after next GitHub Actions build.
|
||||
|
||||
If I'm missing anything or you observed it not working, please don't hesitate to file an issue or find me via email (harttleharttle at gmail).
|
||||
|
||||
[oc]: https://opencollective.com/liquidjs/contribute/backer-10665/checkout
|
||||
[shopify/liquid]: https://shopify.github.io/liquid/
|
||||
|
||||
@@ -24,6 +24,7 @@ Though we're trying to be compatible with the Ruby version, there are still some
|
||||
|
||||
* Truthy and Falsy. All values except `undefined`, `null`, `false` are truthy, whereas in Ruby Liquid all except `nil` and `false` are truthy. See [#26][#26].
|
||||
* Number. In JavaScript we cannot distinguish or convert between `float` and `integer`, see [#59][#59]. And when applied `size` filter, numbers always return 0, which is 8 for integer in ruby, cause they do not have a `length` property.
|
||||
* Stringify: We've aligned string coercion for primitive types. While some differences remain; for example, in Shopify/liquid, `strip` returns the "inspected" string of an input array, whereas in LiquidJS, the `strip` filter simply stringifies the input array [#852][#852].
|
||||
* [.to_liquid()](https://github.com/Shopify/liquid/wiki/Introduction-to-Drops) is replaced by `.toLiquid()`
|
||||
* [.to_s()](https://www.rubydoc.info/gems/liquid/Liquid/Drop) is replaced by JavaScript `.toString()`
|
||||
* Iteration order for objects. The iteration order of JavaScript objects, and thus LiquidJS objects, is a combination of the insertion order for string keys, and ascending order for number-like keys, while the iteration order of Ruby Hash is simply the insertion order.
|
||||
@@ -47,6 +48,7 @@ Though we're trying to be compatible with the Ruby version, there are still some
|
||||
[#236]: https://github.com/harttle/liquidjs/issues/236
|
||||
[#414]: https://github.com/harttle/liquidjs/discussions/414
|
||||
[#485]: https://github.com/harttle/liquidjs/discussions/485
|
||||
[#852]: https://github.com/harttle/liquidjs/discussions/852
|
||||
[sort]: https://liquidjs.com/filters/sort.html
|
||||
[stable-sort]: https://v8.dev/features/stable-sort
|
||||
[plugins]: ./plugins.html#Plugin-List
|
||||
|
||||
@@ -5,17 +5,64 @@ title: Operators
|
||||
LiquidJS operators are very simple and different. There're 2 types of operators supported:
|
||||
|
||||
* Comparison operators: `==`, `!=`, `>`, `<`, `>=`, `<=`
|
||||
* Logic operators: `or`, `and`, `contains`
|
||||
* Logic operators: `not`, `or`, `and`, `contains`
|
||||
|
||||
Thus numerical operators are not supported and you cannot even plus two numbers like this `{% raw %}{{a + b}}{% endraw %}`, instead we need a filter `{% raw %}{{ a | plus: b}}{% endraw %}`. Actually `+` is a valid variable name in LiquidJS.
|
||||
|
||||
## Logic Operators
|
||||
|
||||
### not
|
||||
|
||||
Negates a condition. Returns `true` if the condition is false, and `false` if the condition is true.
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{% if not user.active %}
|
||||
User is inactive
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
### and
|
||||
|
||||
Returns `true` if both conditions are true.
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{% if user.age >= 18 and user.verified %}
|
||||
Access granted
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
### or
|
||||
|
||||
Returns `true` if at least one condition is true.
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{% if user.isAdmin or user.isModerator %}
|
||||
You have elevated privileges
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
### contains
|
||||
|
||||
Checks if a string contains a substring, or if an array contains an element.
|
||||
|
||||
Input
|
||||
```liquid
|
||||
{% if product.title contains "Pack" %}
|
||||
This is a pack
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
## Precedence
|
||||
|
||||
1. Comparison operators. All comparison operations have the same precedence and higher than logic operators.
|
||||
2. Logic operators. All logic operators have the same precedence.
|
||||
1. Comparison operators, and `contains`. All comparison operators alongside `contains` have the same (highest) precedence.
|
||||
2. `not` operator. It has slightly more precedence than `or` and `and`.
|
||||
3. `or` and `and` operators. These logic operators have the same (lowest) precedence.
|
||||
|
||||
## Associativity
|
||||
|
||||
Logic operators are evaluated from right to left, see [shopify docs][operator-order].
|
||||
|
||||
[operator-order]: https://help.shopify.com/en/themes/liquid/basics/operators#order-of-operations
|
||||
[operator-order]: https://shopify.dev/docs/api/liquid/basics#order-of-operations
|
||||
|
||||
@@ -116,7 +116,7 @@ it defaults to false. For example, when set to true, a blank string would evalu
|
||||
|
||||
**preserveTimezones** is a boolean effects only literal timestamps. When set to `true`, all literal timestamps will remain the same when output. This is a parser option, so Date objects passed to LiquidJS as data will not be affected. Note that `preserveTimezones` has a higher priority than `timezoneOffset`.
|
||||
|
||||
**dateFormat** is used to specify a default format to output dates. `%A, %B %-e, %Y at %-l:%M %P %z` will be used if not specified. For example, set `dateFormat: %Y-%m-%dT%H:%M:%S:%LZ` to output all dates in [JavaScript Date.toJson()][https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON] format.
|
||||
**dateFormat** is used to specify a default format to output dates. `%A, %B %-e, %Y at %-l:%M %P %z` will be used if not specified. For example, set `dateFormat: %Y-%m-%dT%H:%M:%S:%LZ` to output all dates in [JavaScript Date.toJson()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) format.
|
||||
|
||||
## Trimming
|
||||
|
||||
@@ -146,7 +146,7 @@ Nonexistent tags always throw errors during parsing and this behavior cannot be
|
||||
|
||||
## Parameter Order
|
||||
|
||||
Parameter orders are ignored by default, for ea `{% for i in (1..8) reversed limit:3 %}` will always perform `limit` before `reversed`, even if `reversed` occurs before `limit`. To make parameter order respected, set **orderedFilterParameters** to `true`. Its default value is `false`.
|
||||
Parameter orders are ignored by default, for example `{% for i in (1..8) reversed limit:3 %}` will always perform `limit` before `reversed`, even if `reversed` occurs before `limit`. To make parameter order respected, set **orderedFilterParameters** to `true`. Its default value is `false`.
|
||||
|
||||
[liquid]: /api/classes/Liquid.html
|
||||
[caching]: ./caching.html
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Value, TagToken, Context, Emitter, TopLevelToken } from 'liquidjs'
|
||||
|
||||
engine.registerTag('upper', {
|
||||
parse: function(tagToken: TagToken, remainTokens: TopLevelToken[]) {
|
||||
this.value = new Value(token.args, liquid)
|
||||
this.value = new Value(tagToken.args, engine)
|
||||
},
|
||||
render: function*(ctx: Context) {
|
||||
const str = yield this.value.value(ctx); // 'alice'
|
||||
@@ -80,4 +80,4 @@ function disabledFilter(name) {
|
||||
}
|
||||
}
|
||||
engine.registerFilter('plus', disabledFilter('plus'));
|
||||
```
|
||||
```
|
||||
|
||||
@@ -45,26 +45,20 @@ It can be a string-typed path (see above example), or a list of root directories
|
||||
|
||||
```javascript
|
||||
var engine = new Liquid({
|
||||
root: ['views/', 'views/partials/'],
|
||||
root: ['views/'],
|
||||
partials: ['views/partials/'],
|
||||
layouts: ['views/layouts/'],
|
||||
extname: '.liquid'
|
||||
});
|
||||
```
|
||||
|
||||
{% note tip Relative Paths %}Relative paths in <code>root</code> will be resolved against <code>cwd()</code>.{% endnote %}
|
||||
|
||||
When `{% raw %}{% render "foo" %}{% endraw %}` is rendered or `liquid.renderFile('foo')` is called, the following files will be looked up and the first existing file will be used:
|
||||
- When `parse()`, `render()` functions are called, for example `liquid.renderFile('foo')`, templates under `root` will be looked up.
|
||||
- When a partial is requested, for example `{% raw %}{% render "foo" %}{% endraw %}`, templates under `partials` will be looked up.
|
||||
- When a layout is requested, for example `{% raw %}{% layout "foo" %}{% endraw %}`, templates under `layouts` will be looked up.
|
||||
|
||||
- `cwd()`/views/foo.liquid
|
||||
- `cwd()`/views/partials/foo.liquid
|
||||
|
||||
If none of the above files exists, an `ENOENT` error will be thrown. Here's a demo for Node.js: [demo/nodejs](https://github.com/harttle/liquidjs/tree/master/demo/nodejs).
|
||||
|
||||
When LiquidJS is used in browser, say current location is <https://example.com/bar/index.html>, only the first `root` will be used and the file to be fetched is:
|
||||
|
||||
- <https://example.com/bar/foo.liquid>
|
||||
|
||||
If fetch fails, a 404/500 error or network failures for example, an `ENOENT` error will be thrown.
|
||||
Here's a demo for browsers: [demo/browser](https://github.com/harttle/liquidjs/tree/master/demo/browser).
|
||||
When LiquidJS is used in browser, the paths will be resolved based on current location. Here's a demo for browsers: [demo/browser](https://github.com/harttle/liquidjs/tree/master/demo/browser).
|
||||
|
||||
## Abstract File System
|
||||
|
||||
@@ -98,7 +92,7 @@ var engine = new Liquid({
|
||||
});
|
||||
```
|
||||
|
||||
{% note warn Path Traversal Vulnerability %}The default value of <code>contains()</code> always returns true. That means when specifying an abstract file system, you'll need to provide a proper <code>contains()</code> to avoid expose such vulnerabilities.{% endnote %}
|
||||
{% note warn Path Traversal Vulnerability %}The built-in Node <code>fs</code> implements <code>contains()</code> with realpath so templates cannot escape the root via symlinks. The browser bundle omits <code>contains</code> (loader treats paths as allowed). For a custom abstract <code>fs</code>, implement <code>contains</code> unless every resolved path is trusted.{% endnote %}
|
||||
|
||||
## In-memory Template
|
||||
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
---
|
||||
title: Static Template Analysis
|
||||
---
|
||||
|
||||
{% since %}v10.20.0{% endsince %}
|
||||
|
||||
{% note warn Experimental %}
|
||||
Note that this is an experimental feature and future APIs are subject to change. And internal structures returned can be changed w/o a major version bump.
|
||||
{% endnote %}
|
||||
|
||||
{% note info Sync and Async %}
|
||||
There are synchronous and asynchronous versions of each of the methods demonstrated on this page. See the [Liquid API][liquid-api] for a complete reference.
|
||||
{% endnote %}
|
||||
|
||||
## Variables
|
||||
|
||||
Retrieve the names of variables used in a template with `Liquid.variables(template)`. It returns an array of strings, one string for each distinct variable, without its properties.
|
||||
|
||||
```javascript
|
||||
import { Liquid } from 'liquidjs'
|
||||
|
||||
const engine = new Liquid()
|
||||
|
||||
const template = engine.parse(`
|
||||
<p>
|
||||
{% assign title = user.title | capitalize %}
|
||||
{{ title }} {{ user.first_name | default: user.name }} {{ user.last_name }}
|
||||
{% if user.address %}
|
||||
{{ user.address.line1 }}
|
||||
{% else %}
|
||||
{{ user.email_addresses[0] }}
|
||||
{% for email in user.email_addresses %}
|
||||
- {{ email }}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{{ a[b.c].d }}
|
||||
<p>
|
||||
`)
|
||||
|
||||
console.log(engine.variablesSync(template))
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
```javascript
|
||||
[ 'user', 'title', 'email', 'a', 'b' ]
|
||||
```
|
||||
|
||||
Notice that variables from tag and filter arguments are included, as well as nested variables like `b` in the example. Alternatively, use `Liquid.fullVariables(template)` to get a list of variables including their properties as strings.
|
||||
|
||||
```javascript
|
||||
// continued from above
|
||||
engine.fullVariables(template).then(console.log)
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
```javascript
|
||||
[
|
||||
'user.title',
|
||||
'user.first_name',
|
||||
'user.name',
|
||||
'user.last_name',
|
||||
'user.address',
|
||||
'user.address.line1',
|
||||
'user.email_addresses[0]',
|
||||
'user.email_addresses',
|
||||
'title',
|
||||
'email',
|
||||
'a[b.c].d',
|
||||
'b.c'
|
||||
]
|
||||
```
|
||||
|
||||
Or use `Liquid.variableSegments(template)` to get an array of strings and numbers that make up each variable's path.
|
||||
|
||||
```javascript
|
||||
// continued from above
|
||||
engine.variableSegments(template).then(console.log)
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
```javascript
|
||||
[
|
||||
[ 'user', 'title' ],
|
||||
[ 'user', 'first_name' ],
|
||||
[ 'user', 'name' ],
|
||||
[ 'user', 'last_name' ],
|
||||
[ 'user', 'address' ],
|
||||
[ 'user', 'address', 'line1' ],
|
||||
[ 'user', 'email_addresses', 0 ],
|
||||
[ 'user', 'email_addresses' ],
|
||||
[ 'title' ],
|
||||
[ 'email' ],
|
||||
[ 'a', [ 'b', 'c' ], 'd' ],
|
||||
[ 'b', 'c' ]
|
||||
]
|
||||
```
|
||||
|
||||
### Global Variables
|
||||
|
||||
Notice, in the examples above, that `title` and `email` are included in the results. Often you'll want to exclude names that are in scope from `{% assign %}` tags, and temporary variables like those introduced by a `{% for %}` tag.
|
||||
|
||||
To get names that are expected to be _global_, that is, provided by application developers rather than template authors, use the `globalVariables`, `globalFullVariables` or `globalVariableSegments` methods (or their synchronous equivalents) of a `Liquid` class instance.
|
||||
|
||||
```javascript
|
||||
// continued from above
|
||||
engine.globalVariableSegments(template).then(console.log)
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
```javascript
|
||||
[
|
||||
[ 'user', 'title' ],
|
||||
[ 'user', 'first_name' ],
|
||||
[ 'user', 'name' ],
|
||||
[ 'user', 'last_name' ],
|
||||
[ 'user', 'address' ],
|
||||
[ 'user', 'address', 'line1' ],
|
||||
[ 'user', 'email_addresses', 0 ],
|
||||
[ 'user', 'email_addresses' ],
|
||||
[ 'a', [ 'b', 'c' ], 'd' ],
|
||||
[ 'b', 'c' ]
|
||||
]
|
||||
```
|
||||
|
||||
### Partial Templates
|
||||
|
||||
By default, LiquidJS will try to load and analyze any included and rendered templates too.
|
||||
|
||||
```javascript
|
||||
import { Liquid } from 'liquidjs'
|
||||
|
||||
const footer = `
|
||||
<footer>
|
||||
<p>© {{ "now" | date: "%Y" }} {{ site_name }}</p>
|
||||
<p>{{ site_description }}</p>
|
||||
</footer>`
|
||||
|
||||
const engine = new Liquid({ templates: { footer } })
|
||||
|
||||
const template = engine.parse(`
|
||||
<body>
|
||||
<h1>Hi, {{ you | default: 'World' }}!</h1>
|
||||
{% assign some = 'thing' %}
|
||||
{% include 'footer' %}
|
||||
</body>
|
||||
`)
|
||||
|
||||
engine.globalVariables(template).then(console.log)
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
```javascript
|
||||
[ 'you', 'site_name', 'site_description' ]
|
||||
```
|
||||
|
||||
You can disable analysis of partial templates by setting the `partials` options to `false`.
|
||||
|
||||
```javascript
|
||||
// continue from above
|
||||
engine.globalVariables(template, { partials: false }).then(console.log)
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
```javascript
|
||||
[ 'you' ]
|
||||
```
|
||||
|
||||
If an `{% include %}` tag uses a dynamic template name (one that can't be determined without rendering the template) it will be ignored, even if `partials` is set to `true`.
|
||||
|
||||
### Advanced Usage
|
||||
|
||||
The examples so far all use convenience methods of the `Liquid` class, intended to cover the most common use cases. Instead, you can work with [analysis results][static-analysis-interface] directly, which expose the row, column and file name for every occurrence of each variable.
|
||||
|
||||
This is an example of an object returned from `Liquid.analyze()`, passing it the template from the [Partial Template](#partial-templates) section above.
|
||||
|
||||
```javascript
|
||||
{
|
||||
variables: {
|
||||
you: [
|
||||
[String (Variable): 'you'] {
|
||||
segments: [ 'you' ],
|
||||
location: { row: 2, col: 14, file: undefined }
|
||||
}
|
||||
],
|
||||
site_name: [
|
||||
[String (Variable): 'site_name'] {
|
||||
segments: [ 'site_name' ],
|
||||
location: { row: 2, col: 41, file: 'footer' }
|
||||
}
|
||||
],
|
||||
site_description: [
|
||||
[String (Variable): 'site_description'] {
|
||||
segments: [ 'site_description' ],
|
||||
location: { row: 3, col: 9, file: 'footer' }
|
||||
}
|
||||
]
|
||||
},
|
||||
globals: {
|
||||
you: [
|
||||
[String (Variable): 'you'] {
|
||||
segments: [ 'you' ],
|
||||
location: { row: 2, col: 14, file: undefined }
|
||||
}
|
||||
],
|
||||
site_name: [
|
||||
[String (Variable): 'site_name'] {
|
||||
segments: [ 'site_name' ],
|
||||
location: { row: 2, col: 41, file: 'footer' }
|
||||
}
|
||||
],
|
||||
site_description: [
|
||||
[String (Variable): 'site_description'] {
|
||||
segments: [ 'site_description' ],
|
||||
location: { row: 3, col: 9, file: 'footer' }
|
||||
}
|
||||
]
|
||||
},
|
||||
locals: {
|
||||
some: [
|
||||
[String (Variable): 'some'] {
|
||||
segments: [ 'some' ],
|
||||
location: { row: 3, col: 13, file: undefined }
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Analyzing Custom Tags
|
||||
|
||||
For static analysis to include results from custom tags, those tags must implement some additional methods defined on the [Template interface]( /api/interfaces/Template.html). LiquidJS will use the information returned from these methods to traverse the template and report variable usage.
|
||||
|
||||
Not all methods are required, depending in the kind of tag. If it's a block with a start tag, end tag and any amount of Liquid markup in between, it will need to implement the [`children()`](/api/interfaces/Template.html#children) method. `children()` is defined as a generator, so that we can use it in synchronous and asynchronous contexts, just like `render()`. It should return HTML content, output statements and tags that are child nodes of the current tag.
|
||||
|
||||
The [`blockScope()`](/api/interfaces/Template.html#blockScope) method is responsible for telling LiquidJS which names will be in scope for the duration of the tag's block. Some of these names could depend on the tag's arguments, and some will be fixed, like `forloop` from the `{% for %}` tag.
|
||||
|
||||
Whether a tag is an inline tag or a block tag, if it accepts arguments it should implement [`arguments()`](/api/interfaces/Template.html#arguments), which is responsible for returning the tag's arguments as a sequence of [`Value`](/api/classes/Value.html) instances or tokens of type [`ValueToken`](/api/types/ValueToken.html).
|
||||
|
||||
This example demonstrates these methods for a block tag. See LiquidJS's [built-in tags][built-in] for more examples.
|
||||
|
||||
```javascript
|
||||
import { Liquid, Tag, Hash } from 'liquidjs'
|
||||
|
||||
class ExampleTag extends Tag {
|
||||
args
|
||||
templates
|
||||
|
||||
constructor (token, remainTokens, liquid, parser) {
|
||||
super(token, remainTokens, liquid)
|
||||
this.args = new Hash(token.tokenizer)
|
||||
this.templates = []
|
||||
|
||||
const stream = parser.parseStream(remainTokens)
|
||||
.on('tag:endexample', () => { stream.stop() })
|
||||
.on('template', (tpl) => this.templates.push(tpl))
|
||||
.on('end', () => { throw new Error(`tag ${token.getText()} not closed`) })
|
||||
|
||||
stream.start()
|
||||
}
|
||||
|
||||
* render (ctx, emitter) {
|
||||
const scope = (yield this.args.render(ctx))
|
||||
ctx.push(scope)
|
||||
yield this.liquid.renderer.renderTemplates(this.templates, ctx, emitter)
|
||||
ctx.pop()
|
||||
}
|
||||
|
||||
* children () {
|
||||
return this.templates
|
||||
}
|
||||
|
||||
* arguments () {
|
||||
yield * Object.values(this.args.hash).filter((el) => el !== undefined)
|
||||
}
|
||||
|
||||
blockScope () {
|
||||
return Object.keys(this.args.hash)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
[liquid-api]: /api/classes/Liquid.html
|
||||
[static-analysis-interface]: /api/interfaces/StaticAnalysis.html
|
||||
[built-in]: https://github.com/harttle/liquidjs/tree/master/src/tags
|
||||
@@ -103,5 +103,32 @@ const products = [
|
||||
- 3
|
||||
```
|
||||
|
||||
## Jekyll 风格
|
||||
|
||||
{% since %}v10.19.0{% endsince %}
|
||||
|
||||
对于从 Jekyll 迁移到 Liquid 的用户,有一个 `jekyllWhere` 选项可以模拟 Jekyll 的 `where` 过滤器的行为。该选项默认设置为 `false`。启用后,如果 `property` 是一个数组,目标值将使用 `Array.includes` 而不是 `==` 进行匹配,这在过滤标签时特别有用。
|
||||
|
||||
例如,以下代码:
|
||||
|
||||
```javascript
|
||||
const pages = [
|
||||
{ tags: ["cat", "food"], title: 'Cat Food' },
|
||||
{ tags: ["dog", "food"], title: 'Dog Food' },
|
||||
]
|
||||
```
|
||||
|
||||
输入
|
||||
```liquid
|
||||
{% assign selected = pages | where: 'tags', "cat" %}
|
||||
{% for item in selected -%}
|
||||
- {{ item.title }}
|
||||
{% endfor %}
|
||||
```
|
||||
|
||||
输出
|
||||
```text
|
||||
Cat Food
|
||||
```
|
||||
|
||||
[truthy]: ../tutorials/truthy-and-falsy.html
|
||||
|
||||
@@ -24,6 +24,7 @@ LiquidJS 一直很重视兼容于 Ruby 版本的 Liquid。Liquid 模板语言最
|
||||
|
||||
* 真和假。在 LiquidJS 中 `undefined`, `null`, `false` 是假,之外的都是真;在 Ruby 中 `nil` 和 `false` 是假,其他都是真。见 [#26][#26]。
|
||||
* 数字。JavaScript 不区分浮点数和整数,因此缺失一部分整数算术,见 [#59][#59]。此外 `size` 过滤器作用于数字时总是返回零,而不是 Ruby 中的浮点数或整数的内存大小。
|
||||
* 输出字符串。基本类型的输出已经和 Shopify/liquid 对齐,但是仍然存在一些区别。比如在 Shopify/liquid 中 `strip` 会返回 inspect 字符串,但 LiquidJS `strip` 只是简单地把输入转换为字符串 [#852][#852]。
|
||||
* Drop 中的 [.to_liquid()](https://github.com/Shopify/liquid/wiki/Introduction-to-Drops) 替换为 `.toLiquid()`。
|
||||
* 数据的 [.to_s()](https://www.rubydoc.info/gems/liquid/Liquid/Drop) 替换为 `.toString()`。
|
||||
* 对象的迭代顺序。JavaScript 对象的迭代顺序是插入顺序和数字键递增顺序的组合,但 Ruby Hash 中只是插入顺序(JavaScript 字面量 Object 和 Ruby 字面量 Hash 的插入顺序解释也不同)。
|
||||
@@ -46,6 +47,7 @@ LiquidJS 一直很重视兼容于 Ruby 版本的 Liquid。Liquid 模板语言最
|
||||
[#236]: https://github.com/harttle/liquidjs/issues/236
|
||||
[#414]: https://github.com/harttle/liquidjs/discussions/414
|
||||
[#485]: https://github.com/harttle/liquidjs/discussions/485
|
||||
[#852]: https://github.com/harttle/liquidjs/discussions/852
|
||||
[sort]: https://liquidjs.com/filters/sort.html
|
||||
[stable-sort]: https://v8.dev/features/stable-sort
|
||||
[plugins]: ./plugins.html#插件列表
|
||||
|
||||
@@ -5,17 +5,64 @@ title: 运算符
|
||||
LiquidJS 运算符非常简单也很特别,只支持两类运算符:
|
||||
|
||||
* 比较运算符:`==`, `!=`, `>`, `<`, `>=`, `<=`
|
||||
* 逻辑运算符:`or`, `and`, `contains`
|
||||
* 逻辑运算符:`not`, `or`, `and`, `contains`
|
||||
|
||||
因此普通的数学运算是不支持的,比如 `{% raw %}{{a + b}}{% endraw %}`。它的替代方案是过滤器 `{% raw %}{{ a | plus: b}}{% endraw %}`。事实上 `+` 在 LiquidJS 中是一个合法的变量名。
|
||||
|
||||
## 逻辑运算符
|
||||
|
||||
### not
|
||||
|
||||
对条件取反。如果条件为假则返回 `true`,如果条件为真则返回 `false`。
|
||||
|
||||
输入
|
||||
```liquid
|
||||
{% if not user.active %}
|
||||
用户未激活
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
### and
|
||||
|
||||
当两个条件都为真时返回 `true`。
|
||||
|
||||
输入
|
||||
```liquid
|
||||
{% if user.age >= 18 and user.verified %}
|
||||
允许访问
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
### or
|
||||
|
||||
当至少一个条件为真时返回 `true`。
|
||||
|
||||
输入
|
||||
```liquid
|
||||
{% if user.isAdmin or user.isModerator %}
|
||||
您拥有提升的权限
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
### contains
|
||||
|
||||
检查字符串是否包含子字符串,或数组是否包含元素。
|
||||
|
||||
输入
|
||||
```liquid
|
||||
{% if product.title contains "Pack" %}
|
||||
这是一个套装
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
## 优先级
|
||||
|
||||
1. 比较运算符。所有比较运算符具有同样的优先级,且高于逻辑运算符。
|
||||
2. 逻辑运算符。所有逻辑运算符具有同样的有衔接。
|
||||
1. 比较运算符和 `contains`。所有比较运算符和 `contains` 具有同样的(最高)优先级。
|
||||
2. `not` 运算符。它的优先级略高于 `or` 和 `and`。
|
||||
3. `or` 和 `and` 运算符。这些逻辑运算符具有同样的(最低)优先级。
|
||||
|
||||
## 结合性
|
||||
|
||||
逻辑运算符是又结合的,所以连续的逻辑运算时计算顺序是从右向左,参考 [Shopify][operator-order] 的文档。
|
||||
逻辑运算符是右结合的,所以连续的逻辑运算时计算顺序是从右向左,参考 [Shopify][operator-order] 的文档。
|
||||
|
||||
[operator-order]: https://help.shopify.com/en/themes/liquid/basics/operators#order-of-operations
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
---
|
||||
title: 静态模板分析
|
||||
---
|
||||
|
||||
{% since %}v10.20.0{% endsince %}
|
||||
|
||||
{% note warn 实验性功能 %}
|
||||
这是一个实验性功能,未来的 API 可能会发生变化,返回的内部结构也可能在不进行主要版本更新的情况下更改。
|
||||
{% endnote %}
|
||||
|
||||
{% note info 同步与异步 %}
|
||||
本文中的每种方法都提供了同步和异步版本。请参阅 [Liquid API][liquid-api] 了解完整的参考信息。
|
||||
{% endnote %}
|
||||
|
||||
## 变量
|
||||
|
||||
可以使用 `Liquid.variables(template)` 方法获取模板中使用的变量名称。它会返回一个字符串数组,每个字符串代表一个不同的变量,不包括其属性。
|
||||
|
||||
```javascript
|
||||
import { Liquid } from 'liquidjs'
|
||||
|
||||
const engine = new Liquid()
|
||||
|
||||
const template = engine.parse(`
|
||||
<p>
|
||||
{% assign title = user.title | capitalize %}
|
||||
{{ title }} {{ user.first_name | default: user.name }} {{ user.last_name }}
|
||||
{% if user.address %}
|
||||
{{ user.address.line1 }}
|
||||
{% else %}
|
||||
{{ user.email_addresses[0] }}
|
||||
{% for email in user.email_addresses %}
|
||||
- {{ email }}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{{ a[b.c].d }}
|
||||
<p>
|
||||
`)
|
||||
|
||||
console.log(engine.variablesSync(template))
|
||||
```
|
||||
|
||||
**输出**
|
||||
|
||||
```javascript
|
||||
[ 'user', 'title', 'email', 'a', 'b' ]
|
||||
```
|
||||
|
||||
可以看到,标签和过滤器参数中的变量也会包含在内,例如示例中的嵌套变量 `b`。
|
||||
另外,可以使用 `Liquid.fullVariables(template)` 方法获取包含其属性的完整变量列表。
|
||||
|
||||
```javascript
|
||||
// 上例继续
|
||||
engine.fullVariables(template).then(console.log)
|
||||
```
|
||||
|
||||
**输出**
|
||||
|
||||
```javascript
|
||||
[
|
||||
'user.title',
|
||||
'user.first_name',
|
||||
'user.name',
|
||||
'user.last_name',
|
||||
'user.address',
|
||||
'user.address.line1',
|
||||
'user.email_addresses[0]',
|
||||
'user.email_addresses',
|
||||
'title',
|
||||
'email',
|
||||
'a[b.c].d',
|
||||
'b.c'
|
||||
]
|
||||
```
|
||||
|
||||
或者,使用 `Liquid.variableSegments(template)` 获取每个变量路径的字符串和数字数组。
|
||||
|
||||
```javascript
|
||||
// 上例继续
|
||||
engine.variableSegments(template).then(console.log)
|
||||
```
|
||||
|
||||
**输出**
|
||||
|
||||
```javascript
|
||||
[
|
||||
[ 'user', 'title' ],
|
||||
[ 'user', 'first_name' ],
|
||||
[ 'user', 'name' ],
|
||||
[ 'user', 'last_name' ],
|
||||
[ 'user', 'address' ],
|
||||
[ 'user', 'address', 'line1' ],
|
||||
[ 'user', 'email_addresses', 0 ],
|
||||
[ 'user', 'email_addresses' ],
|
||||
[ 'title' ],
|
||||
[ 'email' ],
|
||||
[ 'a', [ 'b', 'c' ], 'd' ],
|
||||
[ 'b', 'c' ]
|
||||
]
|
||||
```
|
||||
|
||||
### 全局变量
|
||||
|
||||
注意在上述示例中,`title` 和 `email` 被包含在结果中。通常你可能希望排除 `{% assign %}` 标签中定义的变量名,以及由 `{% for %}` 标签引入的临时变量。
|
||||
|
||||
为了获取 _全局_ 变量(即由应用开发者提供,而不是模板作者定义的变量)的名称,可以使用 `globalVariables`、`globalFullVariables` 或 `globalVariableSegments` 方法(及其同步版本)。
|
||||
|
||||
```javascript
|
||||
// 上例继续
|
||||
engine.globalVariableSegments(template).then(console.log)
|
||||
```
|
||||
|
||||
**输出**
|
||||
|
||||
```javascript
|
||||
[
|
||||
[ 'user', 'title' ],
|
||||
[ 'user', 'first_name' ],
|
||||
[ 'user', 'name' ],
|
||||
[ 'user', 'last_name' ],
|
||||
[ 'user', 'address' ],
|
||||
[ 'user', 'address', 'line1' ],
|
||||
[ 'user', 'email_addresses', 0 ],
|
||||
[ 'user', 'email_addresses' ],
|
||||
[ 'a', [ 'b', 'c' ], 'd' ],
|
||||
[ 'b', 'c' ]
|
||||
]
|
||||
```
|
||||
|
||||
### 部分模板
|
||||
|
||||
默认情况下,LiquidJS 还会尝试加载和分析任何被包含和渲染的模板。
|
||||
|
||||
```javascript
|
||||
import { Liquid } from 'liquidjs'
|
||||
|
||||
const footer = `
|
||||
<footer>
|
||||
<p>© {{ "now" | date: "%Y" }} {{ site_name }}</p>
|
||||
<p>{{ site_description }}</p>
|
||||
</footer>`
|
||||
|
||||
const engine = new Liquid({ templates: { footer } })
|
||||
|
||||
const template = engine.parse(`
|
||||
<body>
|
||||
<h1>Hi, {{ you | default: 'World' }}!</h1>
|
||||
{% assign some = 'thing' %}
|
||||
{% include 'footer' %}
|
||||
</body>
|
||||
`)
|
||||
|
||||
engine.globalVariables(template).then(console.log)
|
||||
```
|
||||
|
||||
**输出**
|
||||
|
||||
```javascript
|
||||
[ 'you', 'site_name', 'site_description' ]
|
||||
```
|
||||
|
||||
可以通过将 `partials` 选项设置为 `false` 来禁用部分模板的分析。
|
||||
|
||||
```javascript
|
||||
// 上例继续
|
||||
engine.globalVariables(template, { partials: false }).then(console.log)
|
||||
```
|
||||
|
||||
**输出**
|
||||
|
||||
```javascript
|
||||
[ 'you' ]
|
||||
```
|
||||
|
||||
如果 `{% include %}` 标签使用了动态模板名称(无法在渲染模板之前确定的模板名称),即使 `partials` 设置为 `true`,也会被忽略。
|
||||
|
||||
### 高级用法
|
||||
|
||||
上述示例使用的是 `Liquid` 类的便捷方法,适用于最常见的使用场景。
|
||||
如果需要更详细的信息,可以直接处理 [分析结果][static-analysis-interface],其中每个变量的每次出现都会记录行、列和文件名等信息。
|
||||
|
||||
此处是对 [部分模板](#部分模板) 中模板进行 `Liquid.analyze()` 调用后返回的对象示例。
|
||||
|
||||
```javascript
|
||||
{
|
||||
variables: {
|
||||
you: [
|
||||
[String (Variable): 'you'] {
|
||||
segments: [ 'you' ],
|
||||
location: { row: 2, col: 14, file: undefined }
|
||||
}
|
||||
],
|
||||
site_name: [
|
||||
[String (Variable): 'site_name'] {
|
||||
segments: [ 'site_name' ],
|
||||
location: { row: 2, col: 41, file: 'footer' }
|
||||
}
|
||||
],
|
||||
site_description: [
|
||||
[String (Variable): 'site_description'] {
|
||||
segments: [ 'site_description' ],
|
||||
location: { row: 3, col: 9, file: 'footer' }
|
||||
}
|
||||
]
|
||||
},
|
||||
globals: {
|
||||
you: [
|
||||
[String (Variable): 'you'] {
|
||||
segments: [ 'you' ],
|
||||
location: { row: 2, col: 14, file: undefined }
|
||||
}
|
||||
],
|
||||
site_name: [
|
||||
[String (Variable): 'site_name'] {
|
||||
segments: [ 'site_name' ],
|
||||
location: { row: 2, col: 41, file: 'footer' }
|
||||
}
|
||||
],
|
||||
site_description: [
|
||||
[String (Variable): 'site_description'] {
|
||||
segments: [ 'site_description' ],
|
||||
location: { row: 3, col: 9, file: 'footer' }
|
||||
}
|
||||
]
|
||||
},
|
||||
locals: {
|
||||
some: [
|
||||
[String (Variable): 'some'] {
|
||||
segments: [ 'some' ],
|
||||
location: { row: 3, col: 13, file: undefined }
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 自定义标签的分析
|
||||
|
||||
为了在静态分析中包含自定义标签的结果,这些标签必须实现 [Template 接口]( /api/interfaces/Template.html) 中定义的一些附加方法。LiquidJS 会使用这些方法返回的信息来遍历模板并报告变量使用情况。
|
||||
|
||||
并非所有方法都是必须的,这取决于标签的类型。如果标签是一个块标签,具有起始标签、结束标签以及内容,那么它需要实现 [`children()`](/api/interfaces/Template.html#children) 方法。`children()` 需要返回一个生成器,这是为了像 `render()` 一样既可以同步也可以异步调用。该方法应返回当前标签的子节点,例如 HTML 内容、输出语句和标签。
|
||||
|
||||
[`blockScope()`](/api/interfaces/Template.html#blockScope) 方法用于告知 LiquidJS 在标签块的持续时间内哪些名称会处于作用域中。这些名称可能依赖于标签的参数,也可能是固定的,例如 `{% for %}` 标签生成的 `forloop`。
|
||||
|
||||
无论标签是行内标签还是块标签,如果它接受参数,则应实现 [`arguments()`](/api/interfaces/Template.html#arguments) 方法,该方法负责将标签的参数作为 [`Value`](/api/classes/Value.html) 实例或类型为 [`ValueToken`](/api/types/ValueToken.html) 的标记序列返回。
|
||||
|
||||
以下示例展示了块标签如何实现这些方法。有关更多示例,请参见 LiquidJS 的[内置标签][built-in]。
|
||||
|
||||
```javascript
|
||||
import { Liquid, Tag, Hash } from 'liquidjs'
|
||||
|
||||
class ExampleTag extends Tag {
|
||||
args
|
||||
templates
|
||||
|
||||
constructor (token, remainTokens, liquid, parser) {
|
||||
super(token, remainTokens, liquid)
|
||||
this.args = new Hash(token.tokenizer)
|
||||
this.templates = []
|
||||
|
||||
const stream = parser.parseStream(remainTokens)
|
||||
.on('tag:endexample', () => { stream.stop() })
|
||||
.on('template', (tpl) => this.templates.push(tpl))
|
||||
.on('end', () => { throw new Error(`tag ${token.getText()} not closed`) })
|
||||
|
||||
stream.start()
|
||||
}
|
||||
|
||||
* render (ctx, emitter) {
|
||||
const scope = (yield this.args.render(ctx))
|
||||
ctx.push(scope)
|
||||
yield this.liquid.renderer.renderTemplates(this.templates, ctx, emitter)
|
||||
ctx.pop()
|
||||
}
|
||||
|
||||
* children () {
|
||||
return this.templates
|
||||
}
|
||||
|
||||
* arguments () {
|
||||
yield * Object.values(this.args.hash).filter((el) => el !== undefined)
|
||||
}
|
||||
|
||||
blockScope () {
|
||||
return Object.keys(this.args.hash)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
[liquid-api]: /api/classes/Liquid.html
|
||||
[static-analysis-interface]: /api/interfaces/StaticAnalysis.html
|
||||
[built-in]: https://github.com/harttle/liquidjs/tree/master/src/tags
|
||||
Vendored
+1
@@ -52,6 +52,7 @@ sidebar:
|
||||
operators: Operators
|
||||
truth: Truthy and Falsy
|
||||
dos: DoS
|
||||
static_analysis: Static Analysis
|
||||
|
||||
miscellaneous: Miscellaneous
|
||||
migration9: 'Migrate to LiquidJS 9'
|
||||
|
||||
Vendored
+1
@@ -52,6 +52,7 @@ sidebar:
|
||||
operators: 运算符
|
||||
truth: 真和假
|
||||
dos: DoS
|
||||
static_analysis: 静态分析
|
||||
|
||||
miscellaneous: 其他
|
||||
migration9: '迁移到 LiquidJS 9'
|
||||
|
||||
Vendored
+15
-15
@@ -1,5 +1,5 @@
|
||||
<header id="banner" class="wrapper">
|
||||
<div class="inner">
|
||||
<div class="inner inner-content">
|
||||
<h2 id="banner-title">{{ page.subtitle }}</h2>
|
||||
<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>
|
||||
@@ -9,7 +9,7 @@
|
||||
</header>
|
||||
<div id="intro-news-list">
|
||||
<div class="wrapper">
|
||||
<div class="inner">
|
||||
<div class="inner inner-content">
|
||||
<div id="intro-news-flex">
|
||||
{% for news in site.data.news %}
|
||||
<a href="{{news.url}}" class="intro-news-wrap">
|
||||
@@ -23,7 +23,7 @@
|
||||
</div>
|
||||
<div id="content-wrap">
|
||||
<div class="wrapper">
|
||||
<div class="inner">
|
||||
<div class="inner inner-content">
|
||||
{{ page.content }}
|
||||
<div id="intro-cmd-wrap" class="highlight typescript"><pre><span class="line"><span class="keyword">import</span> { Liquid } <span class="keyword">from</span> <span class="string">'liquidjs'</span></span><br><span class="line"><span class="keyword">const</span> engine = <span class="keyword">new</span> Liquid()</span><br><span class="line"><span class="keyword">const</span> tpl = engine.parse(<span class="string">'Welcome to {% raw %}{{v}}{% endraw %}!'</span>)</span><br><span class="line">engine.render(tpl, {<span class="attr">v</span>: <span class="string">"Liquid"</span>}).then(<span class="built_in">console</span>.log)</span><br><span class="line"><span class="comment">// Outputs "Welcome to Liquid!"</span></span><br></pre></div>
|
||||
<div id="intro-get-started-wrap">
|
||||
@@ -32,20 +32,9 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="contributors-wrap">
|
||||
<div class="wrapper">
|
||||
<div class="inner">
|
||||
<h3>{{__('index.contributors.title')}}</h3>
|
||||
<p class="description">{{__('index.contributors.description')}}</p>
|
||||
<div class="contributors">
|
||||
{{ partial('partial/all-contributors') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sponsors-wrap">
|
||||
<div class="wrapper">
|
||||
<div class="inner">
|
||||
<div class="inner inner-content">
|
||||
<h3>{{__('index.sponsors.title')}}</h3>
|
||||
<p class="description">{{__('index.sponsors.description')}}</p>
|
||||
<div class="contributors">
|
||||
@@ -54,3 +43,14 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="contributors-wrap">
|
||||
<div class="wrapper">
|
||||
<div class="inner inner-content">
|
||||
<h3>{{__('index.contributors.title')}}</h3>
|
||||
<p class="description">{{__('index.contributors.description')}}</p>
|
||||
<div class="contributors">
|
||||
{{ partial('partial/all-contributors') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+2
-1
@@ -9,7 +9,8 @@
|
||||
<script>
|
||||
document.getElementById('search-input-wrap').classList.add('on');
|
||||
docsearch({
|
||||
apiKey: '01f36cc168657a26a385308b9e721bc6',
|
||||
appId: '{{ config.algolia.applicationID }}',
|
||||
apiKey: '{{ config.algolia.apiKey }}',
|
||||
indexName: 'liquidjs',
|
||||
inputSelector: '#search-input',
|
||||
debug: false
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"people": [
|
||||
"alice",
|
||||
"bob",
|
||||
"carol"
|
||||
]
|
||||
}
|
||||
-2
@@ -1,5 +1,3 @@
|
||||
{% assign people = "alice, bob, carol" | split: ", " -%}
|
||||
|
||||
<ul>
|
||||
{%- for person in people %}
|
||||
<li>
|
||||
|
||||
+12
-5
@@ -2,12 +2,19 @@
|
||||
<div class="wrapper">
|
||||
<h1 class="inner">{{__('playground.title')}}</h1>
|
||||
<div class="loader" role=status aria-busy=true></div>
|
||||
<div id="editors" class="row inner hide" aria-hide=true>
|
||||
<div class="col">
|
||||
<div id="editorEl">{{ raw('partial/demo.liquid') }}</div>
|
||||
<div id="dataEl">{}</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>
|
||||
<div class="col" id="previewEl">{{__('playground.loading')}}</div>
|
||||
</div>
|
||||
<p class="inner version"></p>
|
||||
</div>
|
||||
|
||||
+5
-1
@@ -54,7 +54,11 @@ a
|
||||
|
||||
.inner
|
||||
@media screen
|
||||
padding: 0 gutter-width
|
||||
margin: 0 gutter-width
|
||||
.inner.inner-content
|
||||
margin: 0 32px
|
||||
@media mq-tablet
|
||||
margin: 0 48px
|
||||
|
||||
#content-wrap
|
||||
background: var(--color-content-bg)
|
||||
|
||||
+21
-17
@@ -66,6 +66,10 @@
|
||||
.intro-news-wrap
|
||||
padding: 24px 30px
|
||||
text-decoration: none
|
||||
&:first-child
|
||||
padding-left: 0
|
||||
&:last-child
|
||||
padding-right: 0
|
||||
&:hover
|
||||
background-color: var(--color-link-hover)
|
||||
@media mq-normal
|
||||
@@ -105,7 +109,7 @@
|
||||
text-align: center
|
||||
@media mq-normal
|
||||
text-align: left
|
||||
padding-left: 70px
|
||||
padding-left: 48px
|
||||
|
||||
.intro-feature-icon
|
||||
color: var(--color-link)
|
||||
@@ -116,7 +120,7 @@
|
||||
margin-bottom: 26px
|
||||
position: absolute
|
||||
top: 0
|
||||
left: 20px
|
||||
left: 0
|
||||
font-size: 24px
|
||||
width: @font-size
|
||||
|
||||
@@ -177,9 +181,11 @@
|
||||
border-bottom: 1px solid #161d24
|
||||
margin: -1px 0
|
||||
.inner
|
||||
margin: 48px 16px
|
||||
margin-top: 48px
|
||||
margin-bottom: 48px
|
||||
@media mq-tablet
|
||||
margin: 64px 32px
|
||||
margin-top: 64px
|
||||
margin-bottom: 64px
|
||||
h3
|
||||
color: #fff
|
||||
font-size: 32px
|
||||
@@ -192,20 +198,7 @@
|
||||
text-decoration: none
|
||||
|
||||
#contributors-wrap
|
||||
.description a
|
||||
color: #fff
|
||||
&:hover
|
||||
background: #fff
|
||||
color: var(--color-navy-lighter)
|
||||
|
||||
#sponsors-wrap
|
||||
border: none
|
||||
text-align: right
|
||||
background: var(--color-content-bg)
|
||||
overflow: hidden;
|
||||
.contributors
|
||||
display: flex;
|
||||
justify-content: right;
|
||||
.inner
|
||||
h3
|
||||
color: var(--color-default)
|
||||
@@ -227,10 +220,20 @@
|
||||
background: #fff
|
||||
color: var(--color-navy-lighter)
|
||||
|
||||
#sponsors-wrap
|
||||
border: none
|
||||
overflow: hidden;
|
||||
.description a
|
||||
color: #fff
|
||||
&:hover
|
||||
background: #fff
|
||||
color: var(--color-navy-lighter)
|
||||
|
||||
.contributors
|
||||
tr
|
||||
display: flex
|
||||
flex-wrap: wrap
|
||||
justify-content: center;
|
||||
td
|
||||
margin: 10px 2px 0
|
||||
a img
|
||||
@@ -240,3 +243,4 @@
|
||||
background: var(--color-gray)
|
||||
border-radius: 50%
|
||||
margin-bottom: 10px
|
||||
object-fit: contain
|
||||
|
||||
+22
-21
@@ -8,28 +8,29 @@
|
||||
font-weight: 300
|
||||
margin: 40px 0 24px
|
||||
|
||||
.row
|
||||
#editors
|
||||
display: grid
|
||||
overflow: hidden
|
||||
margin-bottom: 16px
|
||||
height: 75vh
|
||||
grid-template-columns: auto auto
|
||||
grid-template-rows: 60% 40%
|
||||
grid-gap: 16px
|
||||
.area-tpl
|
||||
grid-row: 1
|
||||
grid-column: 1
|
||||
.area-data
|
||||
grid-row: 2
|
||||
grid-column: 1
|
||||
.area-output
|
||||
grid-column: 2
|
||||
grid-row: 1 / -1
|
||||
.editor-wrapper
|
||||
display: flex
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between
|
||||
font-size: 1em
|
||||
.col
|
||||
flex: 1 1 100%
|
||||
margin-bottom: 10px
|
||||
|
||||
@media mq-normal
|
||||
.row
|
||||
flex-wrap: nowrap;
|
||||
.col:first-child
|
||||
margin-right: 15px
|
||||
|
||||
#editorEl
|
||||
height: 40vh
|
||||
#dataEl
|
||||
height: 28vh
|
||||
margin-top: 2vh
|
||||
#previewEl
|
||||
height: 70vh
|
||||
gap: 8px
|
||||
flex-direction: column
|
||||
.editor
|
||||
flex-grow: 1
|
||||
.hide
|
||||
display: none
|
||||
.loader
|
||||
|
||||
Vendored
+4
-1
@@ -60,7 +60,10 @@
|
||||
/* global liquidjs, ace */
|
||||
if (!location.pathname.match(/playground.html$/)) return;
|
||||
updateVersion(liquidjs.version);
|
||||
const engine = new liquidjs.Liquid();
|
||||
const engine = new liquidjs.Liquid({
|
||||
memoryLimit: 1e5,
|
||||
renderLimit: 1e5
|
||||
});
|
||||
const editor = createEditor('editorEl', 'liquid');
|
||||
const dataEditor = createEditor('dataEl', 'json');
|
||||
const preview = createEditor('previewEl', 'html');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** @type {import('ts-jest').JestConfigWithTsJest} */
|
||||
module.exports = {
|
||||
preset: 'ts-jest',
|
||||
maxWorkers: '50%',
|
||||
testEnvironment: 'node',
|
||||
testMatch: ['**/*.spec.ts'],
|
||||
collectCoverageFrom: [
|
||||
|
||||
Generated
+10569
-5207
File diff suppressed because it is too large
Load Diff
+17
-6
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "liquidjs",
|
||||
"version": "10.17.0",
|
||||
"version": "10.25.7",
|
||||
"sideEffects": false,
|
||||
"description": "A simple, expressive and safe Shopify / Github Pages compatible template engine in pure JavaScript.",
|
||||
"main": "dist/liquid.node.js",
|
||||
"module": "dist/liquid.node.mjs",
|
||||
@@ -11,7 +12,7 @@
|
||||
},
|
||||
"types": "dist/index.d.ts",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
"node": ">=16"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint \"**/*.mjs\" \"**/*.ts\" .",
|
||||
@@ -20,7 +21,7 @@
|
||||
"test:coverage": "jest --coverage src test/integration",
|
||||
"test:e2e": "jest test/e2e",
|
||||
"test:demo": "./test/demo/test.sh",
|
||||
"perf:diff": "bin/perf-diff.sh",
|
||||
"perf:diff": "node bin/perf-diff.js",
|
||||
"perf:engines": "cd benchmark && npm run engines",
|
||||
"version": "npm run build && npm test",
|
||||
"build": "rollup -c rollup.config.mjs",
|
||||
@@ -28,7 +29,12 @@
|
||||
"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": "bin/build-docs.sh"
|
||||
"build:docs": "run-s build:docs-liquid build:contributors build:apidoc build:changelog build:docs-hexo",
|
||||
"build:docs-liquid": "cross-env BUNDLES=min rollup -c rollup.config.mjs && shx mkdir -p docs/public/js && shx cp dist/liquid.browser.min.js docs/public/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/"
|
||||
},
|
||||
"bin": {
|
||||
"liquidjs": "./bin/liquid.js",
|
||||
@@ -67,7 +73,7 @@
|
||||
"@semantic-release/changelog": "^6.0.2",
|
||||
"@semantic-release/commit-analyzer": "^9.0.2",
|
||||
"@semantic-release/git": "^10.0.1",
|
||||
"@semantic-release/npm": "^9.0.2",
|
||||
"@semantic-release/npm": "^13.1.5",
|
||||
"@semantic-release/release-notes-generator": "^10.0.3",
|
||||
"@types/benchmark": "^1.0.31",
|
||||
"@types/express": "^4.17.2",
|
||||
@@ -94,12 +100,14 @@
|
||||
"husky": "^4.2.5",
|
||||
"jest": "^29.5.0",
|
||||
"jsdom": "^16.5.0",
|
||||
"npm-run-all2": "^8.0.4",
|
||||
"rollup": "^1.26.3",
|
||||
"rollup-plugin-replace": "^2.1.0",
|
||||
"rollup-plugin-typescript2": "^0.31.1",
|
||||
"rollup-plugin-uglify": "^6.0.4",
|
||||
"rollup-plugin-version-injector": "^1.3.3",
|
||||
"semantic-release": "^19.0.3",
|
||||
"semantic-release": "^25.0.3",
|
||||
"shx": "^0.4.0",
|
||||
"sinon": "^15.0.2",
|
||||
"supertest": "^3.4.2",
|
||||
"ts-jest": "^29.0.5",
|
||||
@@ -150,6 +158,9 @@
|
||||
]
|
||||
]
|
||||
},
|
||||
"publishConfig": {
|
||||
"provenance": true
|
||||
},
|
||||
"nyc": {
|
||||
"extension": [
|
||||
".ts"
|
||||
|
||||
+18
-2
@@ -45,6 +45,16 @@ const browserFS = {
|
||||
delimiters: ['', ''],
|
||||
'./fs/fs-impl': './build/fs-impl-browser'
|
||||
}
|
||||
const browserBase64 = {
|
||||
include: './src/filters/base64.ts',
|
||||
delimiters: ['', ''],
|
||||
'./base64-impl': '../build/base64-impl-browser'
|
||||
}
|
||||
const browserCrypto = {
|
||||
include: './src/filters/crypto.ts',
|
||||
delimiters: ['', ''],
|
||||
'./crypto-impl': '../build/crypto-impl-browser'
|
||||
}
|
||||
const browserStream = {
|
||||
include: './src/emitters/index.ts',
|
||||
delimiters: ['', ''],
|
||||
@@ -62,7 +72,7 @@ const nodeCjs = {
|
||||
format: 'cjs',
|
||||
banner
|
||||
}],
|
||||
external: ['path', 'fs', 'stream'],
|
||||
external: ['path', 'fs', 'stream', 'crypto'],
|
||||
plugins: [versionInjection, typescript(tsconfig('ES2020'))],
|
||||
treeshake,
|
||||
input
|
||||
@@ -74,7 +84,7 @@ const nodeEsm = {
|
||||
format: 'esm',
|
||||
banner
|
||||
}],
|
||||
external: ['path', 'fs', 'stream'],
|
||||
external: ['path', 'fs', 'stream', 'crypto'],
|
||||
plugins: [
|
||||
versionInjection,
|
||||
replace(esmRequire),
|
||||
@@ -94,6 +104,8 @@ const browserEsm = {
|
||||
plugins: [
|
||||
versionInjection,
|
||||
replace(browserFS),
|
||||
replace(browserBase64),
|
||||
replace(browserCrypto),
|
||||
replace(browserStream),
|
||||
typescript(tsconfig('es6'))
|
||||
],
|
||||
@@ -112,6 +124,8 @@ const browserUmd = {
|
||||
plugins: [
|
||||
versionInjection,
|
||||
replace(browserFS),
|
||||
replace(browserBase64),
|
||||
replace(browserCrypto),
|
||||
replace(browserStream),
|
||||
typescript(tsconfig('es5'))
|
||||
],
|
||||
@@ -130,6 +144,8 @@ const browserMin = {
|
||||
plugins: [
|
||||
versionInjection,
|
||||
replace(browserFS),
|
||||
replace(browserBase64),
|
||||
replace(browserCrypto),
|
||||
replace(browserStream),
|
||||
typescript(tsconfig('es5')),
|
||||
uglify()
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
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/',
|
||||
contentType: 'text/html',
|
||||
includeNodeLocations: true
|
||||
})
|
||||
|
||||
// Mock btoa and atob on global object
|
||||
Object.defineProperty(global, 'btoa', {
|
||||
value: dom.window.btoa,
|
||||
writable: true,
|
||||
configurable: true
|
||||
})
|
||||
Object.defineProperty(global, 'atob', {
|
||||
value: dom.window.atob,
|
||||
writable: true,
|
||||
configurable: true
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(function () {
|
||||
delete (global as any).btoa
|
||||
delete (global as any).atob
|
||||
})
|
||||
|
||||
describe('#base64Encode()', function () {
|
||||
it('should encode a simple string', function () {
|
||||
expect(base64.base64Encode('one two three')).toBe('b25lIHR3byB0aHJlZQ==')
|
||||
})
|
||||
|
||||
it('should encode an empty string', function () {
|
||||
expect(base64.base64Encode('')).toBe('')
|
||||
})
|
||||
|
||||
it('should encode a string with special characters', function () {
|
||||
expect(base64.base64Encode('Hello, World! @#$%')).toBe('SGVsbG8sIFdvcmxkISBAIyQl')
|
||||
})
|
||||
|
||||
it('should encode numeric strings', function () {
|
||||
expect(base64.base64Encode('123')).toBe('MTIz')
|
||||
})
|
||||
|
||||
it('should encode boolean strings', function () {
|
||||
expect(base64.base64Encode('true')).toBe('dHJ1ZQ==')
|
||||
})
|
||||
})
|
||||
|
||||
describe('#base64Decode()', function () {
|
||||
it('should decode a simple string', function () {
|
||||
expect(base64.base64Decode('b25lIHR3byB0aHJlZQ==')).toBe('one two three')
|
||||
})
|
||||
|
||||
it('should decode an empty string', function () {
|
||||
expect(base64.base64Decode('')).toBe('')
|
||||
})
|
||||
|
||||
it('should decode a string with special characters', function () {
|
||||
expect(base64.base64Decode('SGVsbG8sIFdvcmxkISBAIyQl')).toBe('Hello, World! @#$%')
|
||||
})
|
||||
|
||||
it('should decode numeric strings', function () {
|
||||
expect(base64.base64Decode('MTIz')).toBe('123')
|
||||
})
|
||||
|
||||
it('should decode boolean strings', function () {
|
||||
expect(base64.base64Decode('dHJ1ZQ==')).toBe('true')
|
||||
})
|
||||
})
|
||||
|
||||
describe('round-trip encoding/decoding', function () {
|
||||
it('should encode and decode back to original', function () {
|
||||
const original = 'Hello, World!'
|
||||
const encoded = base64.base64Encode(original)
|
||||
const decoded = base64.base64Decode(encoded)
|
||||
expect(decoded).toBe(original)
|
||||
})
|
||||
|
||||
it('should handle complex strings with special characters', function () {
|
||||
const original = 'Special chars: !@#$%^&*()_+-=[]{}|;:,.<>?'
|
||||
const encoded = base64.base64Encode(original)
|
||||
const decoded = base64.base64Decode(encoded)
|
||||
expect(decoded).toBe(original)
|
||||
})
|
||||
|
||||
it('should handle mixed unicode and ASCII', function () {
|
||||
const original = 'Hello 🌍'
|
||||
const encoded = base64.base64Encode(original)
|
||||
const decoded = base64.base64Decode(encoded)
|
||||
expect(decoded).toBe(original)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
|
||||
export function base64Encode (str: string): string {
|
||||
return btoa(String.fromCharCode(...new TextEncoder().encode(str)))
|
||||
}
|
||||
|
||||
export function base64Decode (str: string): string {
|
||||
return new TextDecoder().decode(
|
||||
Uint8Array.from(atob(str), c => c.charCodeAt(0))
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { webcrypto } from 'crypto'
|
||||
import * as cryptoImpl from './crypto-impl-browser'
|
||||
|
||||
describe('crypto-impl/browser', function () {
|
||||
beforeEach(function () {
|
||||
Object.defineProperty(global, 'crypto', {
|
||||
value: webcrypto,
|
||||
writable: true,
|
||||
configurable: true
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(function () {
|
||||
delete (global as any).crypto
|
||||
})
|
||||
|
||||
describe('#sha256()', function () {
|
||||
it('should hash the Shopify reference example', async function () {
|
||||
expect(await cryptoImpl.sha256('Polyjuice'))
|
||||
.toBe('44ac1d7a2936e30a5de07082fd65d6fe9b1fb658a1a98bfe65bc5959beac5dd0')
|
||||
})
|
||||
|
||||
it('should hash an empty string', async function () {
|
||||
expect(await cryptoImpl.sha256(''))
|
||||
.toBe('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
|
||||
})
|
||||
|
||||
it('should hash unicode characters', async function () {
|
||||
expect(await cryptoImpl.sha256('你好世界'))
|
||||
.toBe('beca6335b20ff57ccc47403ef4d9e0b8fccb4442b3151c2e7d50050673d43172')
|
||||
})
|
||||
})
|
||||
|
||||
describe('#hmacSha256()', function () {
|
||||
it('should hash the Shopify reference example', async function () {
|
||||
expect(await cryptoImpl.hmacSha256('Polyjuice', 'Polina'))
|
||||
.toBe('8e0d5d65cff1242a4af66c8f4a32854fd5fb80edcc8aabe9b302b29c7c71dc20')
|
||||
})
|
||||
|
||||
it('should hash an empty message with a key', async function () {
|
||||
expect(await cryptoImpl.hmacSha256('', 'key'))
|
||||
.toBe('5d5d139563c95b5967b9bd9a8c9b233a9dedb45072794cd232dc1b74832607d0')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
function bufferToHex (buffer: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(buffer)
|
||||
let hex = ''
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
hex += bytes[i].toString(16).padStart(2, '0')
|
||||
}
|
||||
return hex
|
||||
}
|
||||
|
||||
export async function sha256 (str: string): Promise<string> {
|
||||
const data = new TextEncoder().encode(str)
|
||||
const digest = await crypto.subtle.digest('SHA-256', data)
|
||||
return bufferToHex(digest)
|
||||
}
|
||||
|
||||
export async function hmacSha256 (str: string, key: string): Promise<string> {
|
||||
const encoder = new TextEncoder()
|
||||
const cryptoKey = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
encoder.encode(key),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
)
|
||||
const signature = await crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(str))
|
||||
return bufferToHex(signature)
|
||||
}
|
||||
+24
-20
@@ -3,7 +3,7 @@ import { Drop } from '../drop/drop'
|
||||
import { __assign } from 'tslib'
|
||||
import { NormalizedFullOptions, defaultOptions, RenderOptions } from '../liquid-options'
|
||||
import { Scope } from './scope'
|
||||
import { hasOwnProperty, isArray, isNil, isUndefined, isString, isFunction, toLiquid, InternalUndefinedVariableError, toValueSync, isObject, Limiter } from '../util'
|
||||
import { hasOwnProperty, isArray, isNil, isUndefined, isString, isFunction, toLiquid, InternalUndefinedVariableError, toValueSync, isObject, Limiter, toValue } from '../util'
|
||||
|
||||
type PropertyKey = string | number;
|
||||
|
||||
@@ -25,6 +25,8 @@ export class Context {
|
||||
*/
|
||||
public globals: Scope
|
||||
public sync: boolean
|
||||
public breakCalled = false
|
||||
public continueCalled = false
|
||||
/**
|
||||
* The normalized liquid options object
|
||||
*/
|
||||
@@ -46,8 +48,8 @@ export class Context {
|
||||
this.memoryLimit = memoryLimit ?? new Limiter('memory alloc', renderOptions.memoryLimit ?? opts.memoryLimit)
|
||||
this.renderLimit = renderLimit ?? new Limiter('template render', getPerformance().now() + (renderOptions.renderLimit ?? opts.renderLimit))
|
||||
}
|
||||
public getRegister (key: string) {
|
||||
return (this.registers[key] = this.registers[key] || {})
|
||||
public getRegister<T> (key: string, defaultValue: T = undefined as T): T {
|
||||
return (this.registers[key] = this.registers[key] || defaultValue)
|
||||
}
|
||||
public setRegister (key: string, value: any) {
|
||||
return (this.registers[key] = value)
|
||||
@@ -71,8 +73,8 @@ export class Context {
|
||||
public getSync (paths: PropertyKey[]): unknown {
|
||||
return toValueSync(this._get(paths))
|
||||
}
|
||||
public * _get (paths: PropertyKey[]): IterableIterator<unknown> {
|
||||
const scope = this.findScope(paths[0])
|
||||
public * _get (paths: (PropertyKey | Drop)[]): IterableIterator<unknown> {
|
||||
const scope = this.findScope(paths[0] as string) // first prop should always be a string
|
||||
return yield this._getFromScope(scope, paths)
|
||||
}
|
||||
/**
|
||||
@@ -81,10 +83,10 @@ export class Context {
|
||||
public getFromScope (scope: unknown, paths: PropertyKey[] | string): IterableIterator<unknown> {
|
||||
return toValueSync(this._getFromScope(scope, paths))
|
||||
}
|
||||
public * _getFromScope (scope: unknown, paths: PropertyKey[] | string, strictVariables = this.strictVariables): IterableIterator<unknown> {
|
||||
public * _getFromScope (scope: unknown, paths: (PropertyKey | Drop)[] | string, strictVariables = this.strictVariables): IterableIterator<unknown> {
|
||||
if (isString(paths)) paths = paths.split('.')
|
||||
for (let i = 0; i < paths.length; i++) {
|
||||
scope = yield readProperty(scope as object, paths[i], this.ownPropertyOnly)
|
||||
scope = yield this.readProperty(scope as object, paths[i])
|
||||
if (strictVariables && isUndefined(scope)) {
|
||||
throw new InternalUndefinedVariableError((paths as string[]).slice(0, i + 1).join!('.'))
|
||||
}
|
||||
@@ -104,7 +106,8 @@ export class Context {
|
||||
return new Context(scope, this.opts, {
|
||||
sync: this.sync,
|
||||
globals: this.globals,
|
||||
strictVariables: this.strictVariables
|
||||
strictVariables: this.strictVariables,
|
||||
ownPropertyOnly: this.ownPropertyOnly
|
||||
}, {
|
||||
renderLimit: this.renderLimit,
|
||||
memoryLimit: this.memoryLimit
|
||||
@@ -118,20 +121,21 @@ export class Context {
|
||||
if (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]
|
||||
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)
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
export function readProperty (obj: Scope, key: PropertyKey, ownPropertyOnly: boolean) {
|
||||
obj = toLiquid(obj)
|
||||
if (isNil(obj)) return obj
|
||||
if (isArray(obj) && (key as number) < 0) return obj[obj.length + +key]
|
||||
const value = readJSProperty(obj, key, ownPropertyOnly)
|
||||
if (value === undefined && obj instanceof Drop) return obj.liquidMethodMissing(key)
|
||||
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)
|
||||
return value
|
||||
}
|
||||
export function readJSProperty (obj: Scope, key: PropertyKey, ownPropertyOnly: boolean) {
|
||||
if (ownPropertyOnly && !hasOwnProperty.call(obj, key) && !(obj instanceof Drop)) return undefined
|
||||
return obj[key]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Drop } from '../drop/drop'
|
||||
|
||||
interface ScopeObject extends Record<string, any> {
|
||||
interface ScopeObject extends Record<string | number | symbol, any> {
|
||||
toLiquid?: () => any;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,4 +8,7 @@ export class BlankDrop extends EmptyDrop {
|
||||
if (isString(value)) return /^\s*$/.test(value)
|
||||
return super.equals(value)
|
||||
}
|
||||
static is (value: unknown) {
|
||||
return value instanceof BlankDrop
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Emitter, SimpleEmitter } from '../emitters'
|
||||
import { Drop } from './drop'
|
||||
|
||||
export class BlockDrop extends Drop {
|
||||
constructor (
|
||||
// the block render from layout template
|
||||
private superBlockRender: () => Iterable<any> = () => ''
|
||||
private superBlockRender: (emitter: Emitter) => IterableIterator<unknown> | string = () => ''
|
||||
) {
|
||||
super()
|
||||
}
|
||||
@@ -11,7 +12,9 @@ export class BlockDrop extends Drop {
|
||||
* Provide parent access in child block by
|
||||
* {{ block.super }}
|
||||
*/
|
||||
public super () {
|
||||
return this.superBlockRender()
|
||||
public * super (): IterableIterator<unknown> {
|
||||
const emitter = new SimpleEmitter()
|
||||
yield this.superBlockRender(emitter)
|
||||
return emitter.buffer
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -1,5 +1,7 @@
|
||||
import { Context } from '../context'
|
||||
|
||||
export abstract class Drop {
|
||||
public liquidMethodMissing (key: string | number): Promise<any> | any {
|
||||
public liquidMethodMissing (key: string | number, context: Context): Promise<any> | any {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,4 +25,7 @@ export class EmptyDrop extends Drop implements Comparable {
|
||||
public valueOf () {
|
||||
return ''
|
||||
}
|
||||
static is (value: unknown) {
|
||||
return value instanceof EmptyDrop
|
||||
}
|
||||
}
|
||||
|
||||
+94
-38
@@ -1,8 +1,9 @@
|
||||
import { toArray, argumentsToValue, toValue, stringify, caseInsensitiveCompare, isArray, isNil, last as arrayLast } from '../util'
|
||||
import { equals, evalToken, isTruthy } from '../render'
|
||||
import { toArray, argumentsToValue, toValue, stringify, caseInsensitiveCompare, orderedCompare, isArray, isNil, last as arrayLast, isArrayLike, toEnumerable } from '../util'
|
||||
import { arrayIncludes, equals, evalToken, isTruthy } from '../render'
|
||||
import { Value, FilterImpl } from '../template'
|
||||
import { Tokenizer } from '../parser'
|
||||
import type { Scope } from '../context'
|
||||
import { EmptyDrop } from '../drop'
|
||||
|
||||
export const join = argumentsToValue(function (this: FilterImpl, v: any[], arg: string) {
|
||||
const array = toArray(v)
|
||||
@@ -11,16 +12,16 @@ export const join = argumentsToValue(function (this: FilterImpl, v: any[], arg:
|
||||
this.context.memoryLimit.use(complexity)
|
||||
return array.join(sep)
|
||||
})
|
||||
export const last = argumentsToValue((v: any) => isArray(v) ? arrayLast(v) : '')
|
||||
export const first = argumentsToValue((v: any) => isArray(v) ? v[0] : '')
|
||||
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()
|
||||
})
|
||||
|
||||
export function * sort<T> (this: FilterImpl, arr: T[], property?: string): IterableIterator<unknown> {
|
||||
const values: [T, string | number][] = []
|
||||
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) {
|
||||
@@ -29,21 +30,15 @@ export function * sort<T> (this: FilterImpl, arr: T[], property?: string): Itera
|
||||
property ? yield this.context._getFromScope(item, stringify(property).split('.'), false) : item
|
||||
])
|
||||
}
|
||||
return values.sort((lhs, rhs) => {
|
||||
const lvalue = lhs[1]
|
||||
const rvalue = rhs[1]
|
||||
return lvalue < rvalue ? -1 : (lvalue > rvalue ? 1 : 0)
|
||||
}).map(tuple => tuple[0])
|
||||
return values.sort((lhs, rhs) => comparator(lhs[1], rhs[1])).map(tuple => tuple[0])
|
||||
}
|
||||
|
||||
export function sort_natural<T> (this: FilterImpl, input: T[], property?: string) {
|
||||
const propertyString = stringify(property)
|
||||
const compare = property === undefined
|
||||
? caseInsensitiveCompare
|
||||
: (lhs: T, rhs: T) => caseInsensitiveCompare(lhs[propertyString], rhs[propertyString])
|
||||
const array = toArray(input)
|
||||
this.context.memoryLimit.use(array.length)
|
||||
return [...array].sort(compare)
|
||||
export function * sort<T> (this: FilterImpl, arr: T[], property?: string): IterableIterator<unknown> {
|
||||
return yield * sortBy.call(this, arr, property, orderedCompare)
|
||||
}
|
||||
|
||||
export function * sort_natural<T> (this: FilterImpl, arr: T[], property?: string): IterableIterator<unknown> {
|
||||
return yield * sortBy.call(this, arr, property, caseInsensitiveCompare)
|
||||
}
|
||||
|
||||
export const size = (v: string | any[]) => (v && v.length) || 0
|
||||
@@ -116,7 +111,17 @@ export function slice<T> (this: FilterImpl, v: T[] | string, begin: number, leng
|
||||
return v.slice(begin, begin + length)
|
||||
}
|
||||
|
||||
export function * where<T extends object> (this: FilterImpl, arr: T[], property: string, expected?: any): IterableIterator<unknown> {
|
||||
function expectedMatcher (this: FilterImpl, expected: any): (v: any) => boolean {
|
||||
if (this.context.opts.jekyllWhere) {
|
||||
return (v: any) => EmptyDrop.is(expected) ? equals(v, expected) : (isArray(v) ? arrayIncludes(v, expected) : equals(v, expected))
|
||||
} else if (expected === undefined) {
|
||||
return (v: any) => isTruthy(v, this.context)
|
||||
} else {
|
||||
return (v: any) => equals(v, expected)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -124,27 +129,43 @@ export function * where<T extends object> (this: FilterImpl, arr: T[], property:
|
||||
for (const item of arr) {
|
||||
values.push(yield evalToken(token, this.context.spawn(item)))
|
||||
}
|
||||
return arr.filter((_, i) => {
|
||||
if (expected === undefined) return isTruthy(values[i], this.context)
|
||||
return equals(values[i], expected)
|
||||
})
|
||||
const matcher = expectedMatcher.call(this, expected)
|
||||
return arr.filter((_, i) => matcher(values[i]) === include)
|
||||
}
|
||||
|
||||
export function * where_exp<T extends object> (this: FilterImpl, arr: T[], itemName: string, exp: string): IterableIterator<unknown> {
|
||||
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) {
|
||||
const value = yield keyTemplate.value(this.context.spawn({ [itemName]: item }))
|
||||
if (value) filtered.push(item)
|
||||
this.context.push({ [itemName]: item })
|
||||
const value = yield keyTemplate.value(this.context)
|
||||
this.context.pop()
|
||||
if (value === include) filtered.push(item)
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
export function * where<T extends object> (this: FilterImpl, arr: T[], property: string, expected?: any): IterableIterator<unknown> {
|
||||
return yield * filter.call(this, true, arr, property, expected)
|
||||
}
|
||||
|
||||
export function * reject<T extends object> (this: FilterImpl, arr: T[], property: string, expected?: any): IterableIterator<unknown> {
|
||||
return yield * filter.call(this, false, arr, property, expected)
|
||||
}
|
||||
|
||||
export function * where_exp<T extends object> (this: FilterImpl, arr: T[], itemName: string, exp: string): IterableIterator<unknown> {
|
||||
return yield * filter_exp.call(this, true, arr, itemName, exp)
|
||||
}
|
||||
|
||||
export function * reject_exp<T extends object> (this: FilterImpl, arr: T[], itemName: string, exp: string): IterableIterator<unknown> {
|
||||
return yield * filter_exp.call(this, false, arr, itemName, exp)
|
||||
}
|
||||
|
||||
export function * group_by<T extends object> (this: FilterImpl, arr: T[], property: string): IterableIterator<unknown> {
|
||||
const map = new Map()
|
||||
arr = toArray(arr)
|
||||
arr = toEnumerable(arr)
|
||||
const token = new Tokenizer(stringify(property)).readScopeValue()
|
||||
this.context.memoryLimit.use(arr.length)
|
||||
for (const item of arr) {
|
||||
@@ -158,34 +179,69 @@ export function * group_by<T extends object> (this: FilterImpl, arr: T[], proper
|
||||
export function * group_by_exp<T extends object> (this: FilterImpl, arr: T[], itemName: string, exp: string): IterableIterator<unknown> {
|
||||
const map = new Map()
|
||||
const keyTemplate = new Value(stringify(exp), this.liquid)
|
||||
arr = toArray(arr)
|
||||
arr = toEnumerable(arr)
|
||||
this.context.memoryLimit.use(arr.length)
|
||||
for (const item of arr) {
|
||||
const key = yield keyTemplate.value(this.context.spawn({ [itemName]: item }))
|
||||
this.context.push({ [itemName]: item })
|
||||
const key = yield keyTemplate.value(this.context)
|
||||
this.context.pop()
|
||||
if (!map.has(key)) map.set(key, [])
|
||||
map.get(key).push(item)
|
||||
}
|
||||
return [...map.entries()].map(([name, items]) => ({ name, items }))
|
||||
}
|
||||
|
||||
export function * find<T extends object> (this: FilterImpl, arr: T[], property: string, expected: string): IterableIterator<unknown> {
|
||||
function * search<T extends object> (this: FilterImpl, arr: T[], property: string, expected: string): IterableIterator<unknown> {
|
||||
const token = new Tokenizer(stringify(property)).readScopeValue()
|
||||
const array = toArray(arr)
|
||||
for (const item of array) {
|
||||
const value = yield evalToken(token, this.context.spawn(item))
|
||||
if (equals(value, expected)) return item
|
||||
const matcher = expectedMatcher.call(this, expected)
|
||||
for (let index = 0; index < array.length; index++) {
|
||||
const value = yield evalToken(token, this.context.spawn(array[index]))
|
||||
if (matcher(value)) return [index, array[index]]
|
||||
}
|
||||
}
|
||||
|
||||
export function * find_exp<T extends object> (this: FilterImpl, arr: T[], itemName: string, exp: string): IterableIterator<unknown> {
|
||||
function * search_exp<T extends object> (this: FilterImpl, arr: T[], itemName: string, exp: string): IterableIterator<unknown> {
|
||||
const predicate = new Value(stringify(exp), this.liquid)
|
||||
const array = toArray(arr)
|
||||
for (const item of array) {
|
||||
const value = yield predicate.value(this.context.spawn({ [itemName]: item }))
|
||||
if (value) return item
|
||||
for (let index = 0; index < array.length; index++) {
|
||||
this.context.push({ [itemName]: array[index] })
|
||||
const value = yield predicate.value(this.context)
|
||||
this.context.pop()
|
||||
if (value) return [index, array[index]]
|
||||
}
|
||||
}
|
||||
|
||||
export function * has<T extends object> (this: FilterImpl, arr: T[], property: string, expected?: any): IterableIterator<unknown> {
|
||||
const result = yield * search.call(this, arr, property, expected)
|
||||
return !!result
|
||||
}
|
||||
|
||||
export function * has_exp<T extends object> (this: FilterImpl, arr: T[], itemName: string, exp: string): IterableIterator<unknown> {
|
||||
const result = yield * search_exp.call(this, arr, itemName, exp)
|
||||
return !!result
|
||||
}
|
||||
|
||||
export function * find_index<T extends object> (this: FilterImpl, arr: T[], property: string, expected?: any): IterableIterator<unknown> {
|
||||
const result = yield * search.call(this, arr, property, expected)
|
||||
return result ? result[0] : undefined
|
||||
}
|
||||
|
||||
export function * find_index_exp<T extends object> (this: FilterImpl, arr: T[], itemName: string, exp: string): IterableIterator<unknown> {
|
||||
const result = yield * search_exp.call(this, arr, itemName, exp)
|
||||
return result ? result[0] : undefined
|
||||
}
|
||||
|
||||
export function * find<T extends object> (this: FilterImpl, arr: T[], property: string, expected?: any): IterableIterator<unknown> {
|
||||
const result = yield * search.call(this, arr, property, expected)
|
||||
return result ? result[1] : undefined
|
||||
}
|
||||
|
||||
export function * find_exp<T extends object> (this: FilterImpl, arr: T[], itemName: string, exp: string): IterableIterator<unknown> {
|
||||
const result = yield * search_exp.call(this, arr, itemName, exp)
|
||||
return result ? result[1] : undefined
|
||||
}
|
||||
|
||||
export function uniq<T> (this: FilterImpl, arr: T[]): T[] {
|
||||
arr = toArray(arr)
|
||||
this.context.memoryLimit.use(arr.length)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export function base64Encode (str: string): string {
|
||||
return Buffer.from(str, 'utf8').toString('base64')
|
||||
}
|
||||
|
||||
export function base64Decode (str: string): string {
|
||||
return Buffer.from(str, 'base64').toString('utf8')
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Base64 related filters
|
||||
*
|
||||
* Implements base64_encode and base64_decode filters for Shopify compatibility
|
||||
*/
|
||||
|
||||
import { FilterImpl } from '../template'
|
||||
import { stringify } from '../util'
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createHash, createHmac } from 'crypto'
|
||||
|
||||
export function sha256 (str: string): string {
|
||||
return createHash('sha256').update(str, 'utf8').digest('hex')
|
||||
}
|
||||
|
||||
export function hmacSha256 (str: string, key: string): string {
|
||||
return createHmac('sha256', key).update(str, 'utf8').digest('hex')
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Crypto related filters
|
||||
*
|
||||
* Implements sha256 and hmac_sha256 filters for Shopify compatibility
|
||||
*/
|
||||
|
||||
import { FilterImpl } from '../template'
|
||||
import { stringify } from '../util'
|
||||
import { sha256 as sha256Impl, hmacSha256 as hmacSha256Impl } from './crypto-impl'
|
||||
|
||||
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)
|
||||
}
|
||||
+3
-1
@@ -45,7 +45,9 @@ function parseDate (v: string | Date, opts: NormalizedFullOptions, timezoneOffse
|
||||
const defaultTimezoneOffset = timezoneOffset ?? opts.timezoneOffset
|
||||
const locale = opts.locale
|
||||
v = toValue(v)
|
||||
if (v === 'now' || v === 'today') {
|
||||
if (isNil(v)) {
|
||||
return undefined
|
||||
} else if (v === 'now' || v === 'today') {
|
||||
date = new LiquidDate(Date.now(), locale, defaultTimezoneOffset)
|
||||
} else if (isNumber(v)) {
|
||||
date = new LiquidDate(v * 1000, locale, defaultTimezoneOffset)
|
||||
|
||||
+1
-1
@@ -45,5 +45,5 @@ export function newline_to_br (this: FilterImpl, v: string) {
|
||||
export function strip_html (this: FilterImpl, v: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<.*?>|<!--[\s\S]*?-->/g, '')
|
||||
return str.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<[\s\S]*?>|<!--[\s\S]*?-->/g, '')
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import * as urlFilters from './url'
|
||||
import * as arrayFilters from './array'
|
||||
import * as dateFilters from './date'
|
||||
import * as stringFilters from './string'
|
||||
import * as base64Filters from './base64'
|
||||
import * as cryptoFilters from './crypto'
|
||||
import misc from './misc'
|
||||
import { FilterImplOptions } from '../template'
|
||||
|
||||
@@ -14,5 +16,7 @@ export const filters: Record<string, FilterImplOptions> = {
|
||||
...arrayFilters,
|
||||
...dateFilters,
|
||||
...stringFilters,
|
||||
...base64Filters,
|
||||
...cryptoFilters,
|
||||
...misc
|
||||
}
|
||||
|
||||
+16
-19
@@ -1,24 +1,21 @@
|
||||
import { toValue, argumentsToValue } from '../util/underscore'
|
||||
import { toNumber, argumentsToNumber } from '../util/underscore'
|
||||
|
||||
export const abs = argumentsToValue(Math.abs)
|
||||
export const at_least = argumentsToValue(Math.max)
|
||||
export const at_most = argumentsToValue(Math.min)
|
||||
export const ceil = argumentsToValue(Math.ceil)
|
||||
export const divided_by = argumentsToValue((dividend: number, divisor: number, integerArithmetic = false) => integerArithmetic ? Math.floor(dividend / divisor) : dividend / divisor)
|
||||
export const floor = argumentsToValue(Math.floor)
|
||||
export const minus = argumentsToValue((v: number, arg: number) => v - arg)
|
||||
export const modulo = argumentsToValue((v: number, arg: number) => v % arg)
|
||||
export const times = argumentsToValue((v: number, arg: number) => v * arg)
|
||||
export const abs = argumentsToNumber(Math.abs)
|
||||
export const at_least = argumentsToNumber(Math.max)
|
||||
export const at_most = argumentsToNumber(Math.min)
|
||||
export const ceil = argumentsToNumber(Math.ceil)
|
||||
export const divided_by = argumentsToNumber((dividend: number, divisor: number, integerArithmetic = false) => integerArithmetic ? Math.floor(dividend / divisor) : dividend / divisor)
|
||||
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 times = argumentsToNumber((v: number, arg: number) => v * arg)
|
||||
|
||||
export function round (v: number, arg = 0) {
|
||||
v = toValue(v)
|
||||
arg = toValue(arg)
|
||||
v = toNumber(v)
|
||||
arg = toNumber(arg)
|
||||
const amp = Math.pow(10, arg)
|
||||
return Math.round(v * amp) / amp
|
||||
}
|
||||
|
||||
export function plus (v: number, arg: number) {
|
||||
v = toValue(v)
|
||||
arg = toValue(arg)
|
||||
return Number(v) + Number(arg)
|
||||
const scaled = v * amp
|
||||
// Round half away from zero
|
||||
return Math.sign(v) * Math.round(Math.abs(scaled)) / amp
|
||||
}
|
||||
|
||||
+47
-25
@@ -11,7 +11,7 @@
|
||||
// Hiragana (Japanese): \u3040-\u309F
|
||||
// Hangul (Korean): \uAC00-\uD7AF
|
||||
import { FilterImpl } from '../template'
|
||||
import { assert, escapeRegExp, stringify } from '../util'
|
||||
import { assert, stringify } from '../util'
|
||||
|
||||
const rCJKWord = /[\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF]/gu
|
||||
|
||||
@@ -38,10 +38,14 @@ export function lstrip (this: FilterImpl, v: string, chars?: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
if (chars) {
|
||||
chars = escapeRegExp(stringify(chars))
|
||||
return str.replace(new RegExp(`^[${chars}]+`, 'g'), '')
|
||||
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)
|
||||
}
|
||||
return ''
|
||||
}
|
||||
return str.replace(/^\s+/, '')
|
||||
return str.trimStart()
|
||||
}
|
||||
|
||||
export function downcase (this: FilterImpl, v: string) {
|
||||
@@ -58,20 +62,22 @@ export function upcase (this: FilterImpl, v: string) {
|
||||
|
||||
export function remove (this: FilterImpl, v: string, arg: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.split(stringify(arg)).join('')
|
||||
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)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.replace(stringify(l), '')
|
||||
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)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
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)
|
||||
@@ -81,10 +87,14 @@ export function rstrip (this: FilterImpl, str: string, chars?: string) {
|
||||
str = stringify(str)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
if (chars) {
|
||||
chars = escapeRegExp(stringify(chars))
|
||||
return str.replace(new RegExp(`[${chars}]+$`, 'g'), '')
|
||||
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)
|
||||
}
|
||||
return ''
|
||||
}
|
||||
return str.replace(/\s+$/, '')
|
||||
return str.trimEnd()
|
||||
}
|
||||
|
||||
export function split (this: FilterImpl, v: string, arg: string) {
|
||||
@@ -101,10 +111,13 @@ export function strip (this: FilterImpl, v: string, chars?: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
if (chars) {
|
||||
chars = escapeRegExp(stringify(chars))
|
||||
return str
|
||||
.replace(new RegExp(`^[${chars}]+`, 'g'), '')
|
||||
.replace(new RegExp(`[${chars}]+$`, 'g'), '')
|
||||
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++
|
||||
while (j >= i && set.has(str[j])) j--
|
||||
return str.slice(i, j + 1)
|
||||
}
|
||||
return str.trim()
|
||||
}
|
||||
@@ -123,36 +136,44 @@ export function capitalize (this: FilterImpl, str: string) {
|
||||
|
||||
export function replace (this: FilterImpl, v: string, pattern: string, replacement: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.split(stringify(pattern)).join(replacement)
|
||||
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)
|
||||
}
|
||||
|
||||
export function replace_first (this: FilterImpl, v: string, arg1: string, arg2: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
return str.replace(stringify(arg1), arg2)
|
||||
arg1 = stringify(arg1)
|
||||
arg2 = stringify(arg2)
|
||||
this.context.memoryLimit.use(str.length + arg1.length + arg2.length)
|
||||
return str.replace(arg1, () => arg2)
|
||||
}
|
||||
|
||||
export function replace_last (this: FilterImpl, v: string, arg1: string, arg2: string) {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
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
|
||||
const replacement = stringify(arg2)
|
||||
return str.substring(0, index) + replacement + str.substring(index + pattern.length)
|
||||
}
|
||||
|
||||
export function truncate (this: FilterImpl, v: string, l = 50, o = '...') {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
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
|
||||
}
|
||||
|
||||
export function truncatewords (this: FilterImpl, v: string, words = 15, o = '...') {
|
||||
const str = stringify(v)
|
||||
this.context.memoryLimit.use(str.length)
|
||||
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(' ')
|
||||
@@ -187,7 +208,8 @@ export function number_of_words (this: FilterImpl, input: string, mode?: 'cjk' |
|
||||
}
|
||||
|
||||
export function array_to_sentence_string (this: FilterImpl, array: unknown[], connector = 'and') {
|
||||
this.context.memoryLimit.use(array.length)
|
||||
connector = stringify(connector)
|
||||
this.context.memoryLimit.use(array.length + connector.length)
|
||||
switch (array.length) {
|
||||
case 0:
|
||||
return ''
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import * as fs from './fs-impl'
|
||||
import * as path from 'path'
|
||||
import { mkdtempSync, writeFileSync, symlinkSync, rmSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
|
||||
const { join } = path
|
||||
|
||||
describe('fs-impl', function () {
|
||||
describe('.resolve()', function () {
|
||||
@@ -50,4 +54,36 @@ describe('fs-impl', function () {
|
||||
expect(content).toContain('should read content if exists')
|
||||
})
|
||||
})
|
||||
describe('.contains()', () => {
|
||||
const canSymlink = process.platform !== 'win32'
|
||||
;(canSymlink ? it : it.skip)('should return false when path is a symlink to outside root', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'liquid-contains-'))
|
||||
const outside = join(tmpdir(), `secret-${Date.now()}.liquid`)
|
||||
writeFileSync(outside, 'x')
|
||||
const link = join(root, 'link.liquid')
|
||||
symlinkSync(outside, link)
|
||||
try {
|
||||
expect(await fs.contains(root, link)).toBe(false)
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
rmSync(outside, { force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
describe('.containsSync()', () => {
|
||||
const canSymlink = process.platform !== 'win32'
|
||||
;(canSymlink ? it : it.skip)('should return false when path is a symlink to outside root', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'liquid-contains-'))
|
||||
const outside = join(tmpdir(), `secret-${Date.now()}.liquid`)
|
||||
writeFileSync(outside, 'x')
|
||||
const link = join(root, 'link.liquid')
|
||||
symlinkSync(outside, link)
|
||||
try {
|
||||
expect(fs.containsSync(root, link)).toBe(false)
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
rmSync(outside, { force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+22
-5
@@ -1,6 +1,6 @@
|
||||
import { promisify } from '../util'
|
||||
import { sep, resolve as nodeResolve, extname, dirname as nodeDirname } from 'path'
|
||||
import { stat, statSync, readFile as nodeReadFile, readFileSync as nodeReadFileSync } from 'fs'
|
||||
import { stat, statSync, readFile as nodeReadFile, readFileSync as nodeReadFileSync, realpath, realpathSync } from 'fs'
|
||||
import { requireResolve } from './node-require'
|
||||
|
||||
type NodeReadFile = (file: string, encoding: string, cb: ((err: Error | null, result: string) => void)) => void
|
||||
@@ -41,10 +41,27 @@ export function fallback (file: string) {
|
||||
export function dirname (filepath: string) {
|
||||
return nodeDirname(filepath)
|
||||
}
|
||||
export function contains (root: string, file: string) {
|
||||
root = nodeResolve(root)
|
||||
root = root.endsWith(sep) ? root : root + sep
|
||||
return file.startsWith(root)
|
||||
const realpathAsync = promisify(realpath)
|
||||
|
||||
export async function contains (root: string, file: string) {
|
||||
try {
|
||||
const realRoot = await realpathAsync(root)
|
||||
const realFile = await realpathAsync(file)
|
||||
const prefix = realRoot.endsWith(sep) ? realRoot : realRoot + sep
|
||||
return realFile.startsWith(prefix)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
export function containsSync (root: string, file: string) {
|
||||
try {
|
||||
const realRoot = realpathSync(root)
|
||||
const realFile = realpathSync(file)
|
||||
const prefix = realRoot.endsWith(sep) ? realRoot : realRoot + sep
|
||||
return realFile.startsWith(prefix)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export { sep } from 'path'
|
||||
|
||||
+4
-2
@@ -9,8 +9,10 @@ export interface FS {
|
||||
readFileSync: (filepath: string) => string;
|
||||
/** resolve a file against directory, for given `ext` option */
|
||||
resolve: (dir: string, file: string, ext: string) => string;
|
||||
/** check if file is contained in `root`, always return `true` by default. Warning: not setting this could expose path traversal vulnerabilities. */
|
||||
contains?: (root: string, file: string) => boolean;
|
||||
/** check if file is contained in `root`. Node default fs uses realpath; if omitted, loader assumes contained. */
|
||||
contains?: (root: string, file: string) => Promise<boolean>;
|
||||
/** sync check if file is contained in `root`, allows both renderSync and render. */
|
||||
containsSync?: (root: string, file: string) => boolean;
|
||||
/** defaults to "/" */
|
||||
sep?: string;
|
||||
/** required for relative path resolving */
|
||||
|
||||
+29
-20
@@ -1,31 +1,40 @@
|
||||
import * as fs from './fs-impl'
|
||||
import { Loader } from './loader'
|
||||
import { resolve } from 'path'
|
||||
import { Loader, LookupType } from './loader'
|
||||
import { toValueSync } from '../util/async'
|
||||
|
||||
describe('fs/loader', function () {
|
||||
describe('.candidates()', function () {
|
||||
it('should resolve relatively', async function () {
|
||||
it('should resolve relatively', function () {
|
||||
const loader = new Loader({ relativeReference: true, fs, extname: '' } as any)
|
||||
const candidates = [...loader.candidates('./foo/bar', ['/root', '/root/foo'], '/root/current', true)]
|
||||
expect(candidates).toContain('/root/foo/bar')
|
||||
const candidates = [...loader.candidates('./foo/bar', ['/root', '/root/foo'], '/root/current')]
|
||||
expect(candidates).toContain(resolve('/root/foo/bar'))
|
||||
})
|
||||
it('should not include out of root candidates', async function () {
|
||||
const loader = new Loader({ relativeReference: true, fs, extname: '' } as any)
|
||||
const candidates = [...loader.candidates('../foo/bar', ['/root'], '/root/current', true)]
|
||||
expect(candidates).toHaveLength(0)
|
||||
})
|
||||
describe('.lookup()', function () {
|
||||
it('should not include out of root candidates', function () {
|
||||
const mockFs = { ...fs, existsSync: () => true, exists: async () => true }
|
||||
const loader = new Loader({ relativeReference: true, fs: mockFs, extname: '', partials: ['/root'] } as any)
|
||||
expect(() => toValueSync(loader.lookup('../foo/bar', LookupType.Partials, true, '/root/current')))
|
||||
.toThrow(/ENOENT/)
|
||||
})
|
||||
it('should treat root as a terminated path', async function () {
|
||||
const loader = new Loader({ relativeReference: true, fs, extname: '' } as any)
|
||||
const candidates = [...loader.candidates('../root-dir/bar', ['/root'], '/root/current', true)]
|
||||
expect(candidates).toHaveLength(0)
|
||||
it('should treat root as a terminated path', function () {
|
||||
const mockFs = { ...fs, existsSync: () => true, exists: async () => true }
|
||||
const loader = new Loader({ relativeReference: true, fs: mockFs, extname: '', partials: ['/root'] } as any)
|
||||
expect(() => toValueSync(loader.lookup('../root-dir/bar', LookupType.Partials, true, '/root/current')))
|
||||
.toThrow(/ENOENT/)
|
||||
})
|
||||
it('should default `.contains()` to () => true', async function () {
|
||||
const customFs = {
|
||||
...fs,
|
||||
contains: undefined
|
||||
}
|
||||
const loader = new Loader({ relativeReference: true, fs: customFs, extname: '' } as any)
|
||||
const candidates = [...loader.candidates('../foo/bar', ['/root'], '/root/current', true)]
|
||||
expect(candidates).toContain('/foo/bar')
|
||||
it('should use permissive contains when fs.contains is omitted', function () {
|
||||
const mockFs = { ...fs, existsSync: () => true, exists: async () => true, contains: undefined, containsSync: undefined }
|
||||
const loader = new Loader({ relativeReference: true, fs: mockFs, extname: '', partials: ['/root'] } as any)
|
||||
const result = toValueSync(loader.lookup('./foo/bar', LookupType.Partials, true, '/root/current'))
|
||||
expect(result).toBe(resolve('/root/foo/bar'))
|
||||
})
|
||||
it('should enforce containment for LookupType.Root', function () {
|
||||
const mockFs = { ...fs, existsSync: () => true, exists: async () => true }
|
||||
const loader = new Loader({ relativeReference: false, fs: mockFs, extname: '', root: ['/safe'] } as any)
|
||||
expect(() => toValueSync(loader.lookup('/etc/hosts', LookupType.Root, true)))
|
||||
.toThrow(/ENOENT/)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+26
-19
@@ -1,5 +1,5 @@
|
||||
import { FS } from './fs'
|
||||
import { assert, escapeRegex } from '../util'
|
||||
import { assert, LiquidAsync, toLiquidAsync } from '../util'
|
||||
|
||||
export interface LoaderOptions {
|
||||
fs: FS;
|
||||
@@ -17,48 +17,55 @@ export enum LookupType {
|
||||
export class Loader {
|
||||
public shouldLoadRelative: (referencedFile: string) => boolean
|
||||
private options: LoaderOptions
|
||||
private contains: (root: string, file: string) => boolean
|
||||
private contains: LiquidAsync<NonNullable<FS['containsSync']>>
|
||||
private exists: LiquidAsync<FS['existsSync']>
|
||||
|
||||
constructor (options: LoaderOptions) {
|
||||
this.options = options
|
||||
if (options.relativeReference) {
|
||||
const sep = options.fs.sep
|
||||
assert(sep, '`fs.sep` is required for relative reference')
|
||||
const rRelativePath = new RegExp(['.' + sep, '..' + sep, './', '../'].map(prefix => escapeRegex(prefix)).join('|'))
|
||||
this.shouldLoadRelative = (referencedFile: string) => rRelativePath.test(referencedFile)
|
||||
const prefixes = ['.' + sep, '..' + sep, './', '../']
|
||||
this.shouldLoadRelative = (referencedFile: string) => prefixes.some(prefix => referencedFile.startsWith(prefix))
|
||||
} else {
|
||||
this.shouldLoadRelative = (_referencedFile: string) => false
|
||||
}
|
||||
this.contains = this.options.fs.contains || (() => true)
|
||||
const fs = options.fs
|
||||
this.contains = toLiquidAsync(
|
||||
fs.contains?.bind(fs) || (async () => true),
|
||||
fs.containsSync?.bind(fs) || (() => true)
|
||||
)
|
||||
this.exists = toLiquidAsync(
|
||||
fs.exists?.bind(fs) || (async () => false),
|
||||
fs.existsSync?.bind(fs)
|
||||
)
|
||||
}
|
||||
|
||||
public * lookup (file: string, type: LookupType, sync?: boolean, currentFile?: string): Generator<unknown, string, string> {
|
||||
const { fs } = this.options
|
||||
const dirs = this.options[type]
|
||||
for (const filepath of this.candidates(file, dirs, currentFile, type !== LookupType.Root)) {
|
||||
if (sync ? fs.existsSync(filepath) : yield fs.exists(filepath)) return filepath
|
||||
for (const filepath of this.candidates(file, dirs, currentFile)) {
|
||||
let allowed = false
|
||||
for (const dir of dirs) {
|
||||
if (yield this.contains(!!sync, dir, filepath)) { allowed = true; break }
|
||||
}
|
||||
if (!allowed) continue
|
||||
if (yield this.exists(!!sync, filepath)) return filepath
|
||||
}
|
||||
throw this.lookupError(file, dirs)
|
||||
}
|
||||
|
||||
public * candidates (file: string, dirs: string[], currentFile?: string, enforceRoot?: boolean) {
|
||||
public * candidates (file: string, dirs: string[], currentFile?: string) {
|
||||
const { fs, extname } = this.options
|
||||
|
||||
if (this.shouldLoadRelative(file) && currentFile) {
|
||||
const referenced = fs.resolve(this.dirname(currentFile), file, extname)
|
||||
for (const dir of dirs) {
|
||||
if (!enforceRoot || this.contains(dir, referenced)) {
|
||||
// the relatively referenced file is within one of root dirs
|
||||
yield referenced
|
||||
break
|
||||
}
|
||||
}
|
||||
yield referenced
|
||||
}
|
||||
for (const dir of dirs) {
|
||||
const referenced = fs.resolve(dir, file, extname)
|
||||
if (!enforceRoot || this.contains(dir, referenced)) {
|
||||
yield referenced
|
||||
}
|
||||
yield referenced
|
||||
}
|
||||
|
||||
if (fs.fallback !== undefined) {
|
||||
const filepath = fs.fallback(file)
|
||||
if (filepath !== undefined) yield filepath
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user