UNPKG

1.79 kBJavaScriptView Raw
1/*
2 * Copyright 2018 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13const fs = require('fs-extra');
14const path = require('path');
15const Compiler = require('@adobe/htlengine/src/compiler/Compiler');
16const Asset = require('parcel-bundler/src/Asset');
17
18/**
19 * Parcel asset that compiles the HTL script into a javascript function.
20 */
21class HTLAsset extends Asset {
22 constructor(name, options) {
23 super(name, options);
24 this.type = 'js';
25 }
26
27 // eslint-disable-next-line class-methods-use-this
28 async parse(code) {
29 const template = await fs.readFile(path.resolve(__dirname, 'engine', 'RuntimeTemplate.js'), 'utf-8');
30 const compiler = new Compiler()
31 .withOutputDirectory('')
32 .includeRuntime(true)
33 .withRuntimeVar('content')
34 .withRuntimeVar('request')
35 .withRuntimeGlobalName('payload')
36 .withCodeTemplate(template)
37 .withSourceMap(true);
38
39 return compiler.compile(code);
40 }
41
42 generate() {
43 const { template, sourceMap } = this.ast;
44 if (sourceMap) {
45 sourceMap.sources = [this.relativeName];
46 sourceMap.sourcesContent = [this.contents];
47 }
48 return [{
49 type: 'helix-js',
50 value: template,
51 sourceMap,
52 }];
53 }
54}
55
56module.exports = HTLAsset;