Befor generating

This commit is contained in:
marys
2026-06-01 13:17:37 +02:00
parent 3383f4bf4a
commit 1aa1b5f625
6756 changed files with 649946 additions and 1 deletions
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright The Linux Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+108
View File
@@ -0,0 +1,108 @@
[![AsyncAPI React SDK](./assets/readme-banner.png)](https://www.asyncapi.com)
AsyncAPI React SDK is a set of components/functions to use React as render engine in the [Generator](https://github.com/asyncapi/generator).
<!-- toc is generated with GitHub Actions do not remove toc markers -->
<!-- toc -->
- [Installation](#installation)
- [How it works](#how-it-works)
* [The Transpile Process](#the-transpile-process)
* [The Rendering Process](#the-rendering-process)
+ [Requirements](#requirements)
- [The debug flag](#the-debug-flag)
- [Example](#example)
- [Resources](#resources)
- [Development](#development)
- [Contributing](#contributing)
<!-- tocstop -->
## Installation
Run this command to install the SDK in your project:
```bash
npm install --save @asyncapi/generator-react-sdk
```
## How it works
The process of creating content from React components consists of two main process: transpile and rendering.
### The Transpile Process
The SDK has a custom transpiler which ensures that any directory are transpiled using [Rollup](https://www.npmjs.com/package/rollup). Rollup helps bundling all dependencies and transpile them into CommonJS modules. This is required because this library will be used through NodeJS which does not understand these new modules natively and we do not want to limit the developer in which syntax they prefer nor how they want to separate code.
### The Rendering Process
SDK has its own reconciler for React components. It traverses through each element in the template structure and transforms it into a pure string. Additionally, prop `children` is also converted to a regular string and stored in the` childrenContent` prop, which is appended to each component. See [example](#example).
Restrictions:
- React hooks is not allowed.
- HTML tags at the moment is not supported.
- React internal components like Fragments, Suspense etc. are skipped.
#### Requirements
To render the transpiled template SDK requires:
* Node.js v12.16 and higher
## The debug flag
When rendering you have the option of passing a `debug` flag which does not remove the transpiled files after the rendering process is done.
## Example
```js
import { Text, Indent, IndentationTypes, render } from '@asyncapi/generator-react-sdk';
class ClassComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
// In `childrenContent` prop is stored `text wrapped by custom component\n\n`.
// The content of the `children` prop is transformed to string and saved to the `childrenContent` prop.
return this.props.childrenContent;
}
}
function FunctionComponent() {
return (
<Indent size={3} type={IndentationTypes.TABS}>
indented text
<ClassComponent>
<Text newLines={2}>
text wrapped by custom component
</Text>
</ClassComponent>
</Indent>
);
}
// content will be `\t\t\tindented text text wrapped by custom component\n\n`
const content = render(<FunctionComponent />);
```
## Resources
- [`template-for-generator-templates`](https://github.com/asyncapi/template-for-generator-templates) template showcases features of [the AsyncAPI Generator](https://github.com/asyncapi/generator), including the React renderer. It shows how to write templates, reusable parts (components), what are the recommended patterns. It has simple and complex examples of using `React`.
- [`markdown-template`](https://github.com/asyncapi/markdown-template) is written using React. It generates documentation into a Markdown file.
For more help join our [Slack](https://www.asyncapi.com/slack-invite/) workspace.
## Development
1. Setup project by installing dependencies `npm install`
2. Write code and tests.
3. Make sure all tests pass `npm test`
4. Make sure code is well formatted and secure `npm run lint`
## Contributing
Read [CONTRIBUTING](https://github.com/asyncapi/.github/blob/master/CONTRIBUTING.md) guide.
@@ -0,0 +1,35 @@
import PropTypes from 'prop-types';
import { FunctionComponent } from "../types";
export interface FileProps {
/**
* `name` prop describes the filename for which should be used when generating the file. If none is specified the filename for the template are used.
*/
name?: string;
/**
* `permissions` prop describes the permissions the file should be created with. This is interpreted as an octal number such as 0o777
*/
permissions?: number;
}
export declare const FilePropTypes: {
/**
* `name` prop describes the filename for which should be used when generating the file. If none is specified the filename for the template are used.
*/
name: PropTypes.Requireable<string>;
/**
* `permissions` prop describes the permissions the file should be created with. This is interpreted as an octal number such as 0o777
*/
permissions: PropTypes.Requireable<number>;
};
/**
* Component is used to describe to the generator that you want a file to be created and rendered based on the defined children.
*
* @component
* @example
* const name = "test.js"
* const permissions = 0o777
* return (
* <File name={name} permissions={permissions}>Test</File>
* )
*/
declare const File: FunctionComponent<FileProps>;
export default File;
@@ -0,0 +1,47 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FilePropTypes = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var prop_types_1 = __importDefault(require("prop-types"));
exports.FilePropTypes = {
/**
* `name` prop describes the filename for which should be used when generating the file. If none is specified the filename for the template are used.
*/
name: prop_types_1.default.string,
/**
* `permissions` prop describes the permissions the file should be created with. This is interpreted as an octal number such as 0o777
*/
permissions: prop_types_1.default.number,
};
/**
* Component is used to describe to the generator that you want a file to be created and rendered based on the defined children.
*
* @component
* @example
* const name = "test.js"
* const permissions = 0o777
* return (
* <File name={name} permissions={permissions}>Test</File>
* )
*/
var File = function (_a) {
var children = _a.children;
return jsx_runtime_1.jsx(jsx_runtime_1.Fragment, { children: children }, void 0);
};
File.propTypes = __assign({}, exports.FilePropTypes);
exports.default = File;
//# sourceMappingURL=File.js.map
@@ -0,0 +1 @@
{"version":3,"file":"File.js","sourceRoot":"","sources":["../../src/components/File.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,0DAAmC;AAetB,QAAA,aAAa,GAAG;IAC3B;;OAEG;IACH,IAAI,EAAE,oBAAS,CAAC,MAAM;IACtB;;OAEG;IACH,WAAW,EAAE,oBAAS,CAAC,MAAM;CAC9B,CAAC;AAEF;;;;;;;;;;GAUG;AACH,IAAM,IAAI,GAAiC,UAAC,EAAY;QAAV,QAAQ,cAAA;IACpD,OAAO,sDAAG,QAAQ,WAAI,CAAC;AACzB,CAAC,CAAC;AAEF,IAAI,CAAC,SAAS,gBACT,qBAAa,CACjB,CAAC;AACF,kBAAe,IAAI,CAAC"}
@@ -0,0 +1,38 @@
import PropTypes from 'prop-types';
import { IndentationTypes } from "../utils";
import { FunctionComponent } from "../types";
export interface IndentProps {
/**
* `size` prop expects a string which format should be a number which represent the number of `type`'s to indent each content. Default to no indentation.
*/
size?: number;
/**
* `type` prop expects a string, you can use the `IndentationTypes` enum, as either `TABS` or `SPACES`. The `type` defaults to `SPACES`.
*/
type?: IndentationTypes;
}
export declare const IndentPropTypes: {
/**
* `size` prop expects a string which format should be a number which represent the number of `type`'s to indent each content. Default to no indentation.
*/
size: PropTypes.Requireable<number>;
/**
* `type` prop expects a string, you can use the `IndentationTypes` enum, as either `TABS` or `SPACES`. The `type` defaults to `SPACES`.
*/
type: PropTypes.Requireable<IndentationTypes>;
};
/**
* Component is for wrapping multiple components and apply an indentation on those.
*
* It supports any form of nested components as well, meaning you can have as many nested `Indent` components as you would like.
*
* @component
* @example
* const size = 4
* const type = IndentationTypes.SPACES
* return (
* <Indent size={size} type={type}>test</Indent>
* )
*/
declare const Indent: FunctionComponent<IndentProps>;
export default Indent;
@@ -0,0 +1,50 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndentPropTypes = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var prop_types_1 = __importDefault(require("prop-types"));
var utils_1 = require("../utils");
exports.IndentPropTypes = {
/**
* `size` prop expects a string which format should be a number which represent the number of `type`'s to indent each content. Default to no indentation.
*/
size: prop_types_1.default.number,
/**
* `type` prop expects a string, you can use the `IndentationTypes` enum, as either `TABS` or `SPACES`. The `type` defaults to `SPACES`.
*/
type: prop_types_1.default.oneOf(Object.values(utils_1.IndentationTypes)),
};
/**
* Component is for wrapping multiple components and apply an indentation on those.
*
* It supports any form of nested components as well, meaning you can have as many nested `Indent` components as you would like.
*
* @component
* @example
* const size = 4
* const type = IndentationTypes.SPACES
* return (
* <Indent size={size} type={type}>test</Indent>
* )
*/
var Indent = function (_a) {
var _b = _a.size, size = _b === void 0 ? 0 : _b, _c = _a.type, type = _c === void 0 ? utils_1.IndentationTypes.SPACES : _c, childrenContent = _a.childrenContent;
return jsx_runtime_1.jsx(jsx_runtime_1.Fragment, { children: utils_1.withIndendation(childrenContent, size, type) }, void 0);
};
Indent.propTypes = __assign({}, exports.IndentPropTypes);
exports.default = Indent;
//# sourceMappingURL=Indent.js.map
@@ -0,0 +1 @@
{"version":3,"file":"Indent.js","sourceRoot":"","sources":["../../src/components/Indent.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,0DAAmC;AAEnC,kCAA6D;AAchD,QAAA,eAAe,GAAG;IAC7B;;OAEG;IACH,IAAI,EAAE,oBAAS,CAAC,MAAM;IACtB;;OAEG;IACH,IAAI,EAAE,oBAAS,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,wBAAgB,CAAC,CAAC;CACvD,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,IAAM,MAAM,GAAmC,UAAC,EAA6D;QAA3D,YAAQ,EAAR,IAAI,mBAAG,CAAC,KAAA,EAAE,YAA8B,EAA9B,IAAI,mBAAG,wBAAgB,CAAC,MAAM,KAAA,EAAE,eAAe,qBAAA;IACzG,OAAO,sDAAG,uBAAe,CAAC,eAAe,EAAE,IAAI,EAAE,IAAI,CAAC,WAAI,CAAC;AAC7D,CAAC,CAAC;AAEF,MAAM,CAAC,SAAS,gBACX,uBAAe,CACnB,CAAC;AACF,kBAAe,MAAM,CAAC"}
@@ -0,0 +1,45 @@
import PropTypes from 'prop-types';
import { IndentationTypes } from "../utils";
import { FunctionComponent } from "../types";
export interface TextProps {
/**
* `indent` prop represents the number of `type`'s to indent each content. Default to no indentation.
*/
indent?: number;
/**
* `type` prop expects a string, you can use the `IndentationTypes` enum, as either `TABS` or `SPACES`. The `type` defaults to `SPACES`.
*/
type?: IndentationTypes;
/**
* `newLines` prop represents the number of appended new lines. Default to one new line.
*/
newLines?: number;
}
export declare const TextPropTypes: {
/**
* `size` prop expects a string which format should be a number which represent the number of `type`'s to indent each content. Default to no indentation.
*/
size: PropTypes.Requireable<number>;
/**
* `type` prop expects a string, you can use the `IndentationTypes` enum, as either `TABS` or `SPACES`. The `type` defaults to `SPACES`.
*/
type: PropTypes.Requireable<IndentationTypes>;
/**
* `newLines` prop represents the number of appended new lines. Default to one new line.
*/
newLines: PropTypes.Requireable<number>;
};
/**
* Component is for defining a group of text which should be rendered on the same line.
*
* @component
* @example
* const indent = 4
* const type = IndentationTypes.SPACES
* const newLines = 2
* return (
* <Text indent={size} type={type} newLines={newLines}>Test</Text>
* )
*/
declare const Text: FunctionComponent<TextProps>;
export default Text;
@@ -0,0 +1,54 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextPropTypes = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var prop_types_1 = __importDefault(require("prop-types"));
var utils_1 = require("../utils");
exports.TextPropTypes = {
/**
* `size` prop expects a string which format should be a number which represent the number of `type`'s to indent each content. Default to no indentation.
*/
size: prop_types_1.default.number,
/**
* `type` prop expects a string, you can use the `IndentationTypes` enum, as either `TABS` or `SPACES`. The `type` defaults to `SPACES`.
*/
type: prop_types_1.default.oneOf(Object.values(utils_1.IndentationTypes)),
/**
* `newLines` prop represents the number of appended new lines. Default to one new line.
*/
newLines: prop_types_1.default.number,
};
/**
* Component is for defining a group of text which should be rendered on the same line.
*
* @component
* @example
* const indent = 4
* const type = IndentationTypes.SPACES
* const newLines = 2
* return (
* <Text indent={size} type={type} newLines={newLines}>Test</Text>
* )
*/
var Text = function (_a) {
var _b = _a.indent, indent = _b === void 0 ? 0 : _b, _c = _a.type, type = _c === void 0 ? utils_1.IndentationTypes.SPACES : _c, _d = _a.newLines, newLines = _d === void 0 ? 1 : _d, childrenContent = _a.childrenContent;
var contentWithLines = utils_1.withNewLines(childrenContent, newLines);
return jsx_runtime_1.jsx(jsx_runtime_1.Fragment, { children: utils_1.withIndendation(contentWithLines, indent, type) }, void 0);
};
Text.propTypes = __assign({}, exports.TextPropTypes);
exports.default = Text;
//# sourceMappingURL=Text.js.map
@@ -0,0 +1 @@
{"version":3,"file":"Text.js","sourceRoot":"","sources":["../../src/components/Text.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,0DAAmC;AAEnC,kCAA2E;AAkB9D,QAAA,aAAa,GAAG;IAC3B;;OAEG;IACH,IAAI,EAAE,oBAAS,CAAC,MAAM;IACtB;;OAEG;IACH,IAAI,EAAE,oBAAS,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,wBAAgB,CAAC,CAAC;IACtD;;OAEG;IACH,QAAQ,EAAE,oBAAS,CAAC,MAAM;CAC3B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,IAAM,IAAI,GAAiC,UAAC,EAA6E;QAA3E,cAAU,EAAV,MAAM,mBAAG,CAAC,KAAA,EAAE,YAA8B,EAA9B,IAAI,mBAAG,wBAAgB,CAAC,MAAM,KAAA,EAAE,gBAAY,EAAZ,QAAQ,mBAAG,CAAC,KAAA,EAAE,eAAe,qBAAA;IACrH,IAAM,gBAAgB,GAAG,oBAAY,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAC;IACjE,OAAO,sDAAG,uBAAe,CAAC,gBAAgB,EAAE,MAAM,EAAE,IAAI,CAAC,WAAI,CAAC;AAChE,CAAC,CAAC;AAEF,IAAI,CAAC,SAAS,gBACT,qBAAa,CACjB,CAAC;AACF,kBAAe,IAAI,CAAC"}
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,50 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var jsx_runtime_1 = require("react/jsx-runtime");
var utils_1 = require("../../utils");
var __1 = require("../../");
describe('<File />', function () {
test('Should always render as is with default ptops', function () {
var defaultProps = {};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.File, __assign({}, defaultProps, { children: "Test" }), void 0));
expect(wrapper).toEqual('Test');
});
test('Should alwyas render as is with props', function () {
var defaultProps = {
fileName: 'test.ts',
permissions: 511
};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.File, __assign({}, defaultProps, { children: "Test" }), void 0));
expect(wrapper).toEqual('Test');
});
test('Should always be able to render Indent', function () {
var defaultProps = {};
var indentProps = {
size: 4,
type: utils_1.IndentationTypes.SPACES
};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.File, __assign({}, defaultProps, { children: jsx_runtime_1.jsx(__1.Indent, __assign({}, indentProps, { children: "Test" }), void 0) }), void 0));
expect(wrapper).toEqual(' Test');
});
test('Should always be able to render Text', function () {
var defaultProps = {};
var textProps = {
indent: 4,
type: utils_1.IndentationTypes.SPACES
};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.File, __assign({}, defaultProps, { children: jsx_runtime_1.jsx(__1.Text, __assign({}, textProps, { children: "Test" }), void 0) }), void 0));
expect(wrapper).toEqual(' Test\n');
});
});
//# sourceMappingURL=File.spec.js.map
@@ -0,0 +1 @@
{"version":3,"file":"File.spec.js","sourceRoot":"","sources":["../../../src/components/__tests__/File.spec.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,qCAA+C;AAC/C,4BAAoD;AAEpD,QAAQ,CAAC,UAAU,EAAE;IACnB,IAAI,CAAC,+CAA+C,EAAE;QACpD,IAAM,YAAY,GAAG,EAAE,CAAC;QACxB,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,QAAI,eAAK,YAAY,gCAAa,CAAC,CAAC;QAC5D,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,uCAAuC,EAAE;QAC5C,IAAM,YAAY,GAAG;YACnB,QAAQ,EAAE,SAAS;YACnB,WAAW,EAAE,GAAK;SACnB,CAAC;QACF,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,QAAI,eAAK,YAAY,gCAAa,CAAC,CAAC;QAC5D,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,wCAAwC,EAAE;QAC7C,IAAM,YAAY,GAAG,EAAE,CAAC;QACxB,IAAM,WAAW,GAAG;YAClB,IAAI,EAAE,CAAC;YACP,IAAI,EAAE,wBAAgB,CAAC,MAAM;SAC9B,CAAC;QACF,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,QAAI,eAAK,YAAY,cAAE,kBAAC,UAAM,eAAK,WAAW,gCAAe,YAAO,CAAC,CAAC;QAC9F,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,sCAAsC,EAAE;QAC3C,IAAM,YAAY,GAAG,EAAE,CAAC;QACxB,IAAM,SAAS,GAAG;YAChB,MAAM,EAAE,CAAC;YACT,IAAI,EAAE,wBAAgB,CAAC,MAAM;SAC9B,CAAC;QACF,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,QAAI,eAAK,YAAY,cAAE,kBAAC,QAAI,eAAK,SAAS,gCAAa,YAAO,CAAC,CAAC;QACxF,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IACxC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,60 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var jsx_runtime_1 = require("react/jsx-runtime");
var utils_1 = require("../../utils");
var __1 = require("../..");
describe('<Indent />', function () {
test('Should always render as is with default props', function () {
var defaultProps = {};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.Indent, __assign({}, defaultProps, { children: "Test" }), void 0));
expect(wrapper).toEqual('Test');
});
test('Should always render indentation with spaces', function () {
var defaultProps = {
size: 4,
type: utils_1.IndentationTypes.SPACES
};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.Indent, __assign({}, defaultProps, { children: "Test" }), void 0));
expect(wrapper).toEqual(' Test');
});
test('Should always render indentation with tabs', function () {
var defaultProps = {
size: 2,
type: utils_1.IndentationTypes.TABS
};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.Indent, __assign({}, defaultProps, { children: "Test" }), void 0));
expect(wrapper).toEqual(' Test');
});
test('Should be able to make nest indentation', function () {
var defaultProps = {
size: 4,
type: utils_1.IndentationTypes.SPACES
};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.Indent, __assign({}, defaultProps, { children: jsx_runtime_1.jsx(__1.Indent, __assign({}, defaultProps, { size: 2 }, { children: "Test" }), void 0) }), void 0));
expect(wrapper).toEqual(' Test');
});
test('Should be able contain text component', function () {
var defaultProps = {
size: 4,
type: utils_1.IndentationTypes.SPACES
};
var defaultTextProps = {
indent: 4,
type: utils_1.IndentationTypes.SPACES
};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.Indent, __assign({}, defaultProps, { children: jsx_runtime_1.jsx(__1.Text, __assign({}, defaultTextProps, { children: "Test" }), void 0) }), void 0));
expect(wrapper).toEqual(' Test\n');
});
});
//# sourceMappingURL=Indent.spec.js.map
@@ -0,0 +1 @@
{"version":3,"file":"Indent.spec.js","sourceRoot":"","sources":["../../../src/components/__tests__/Indent.spec.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,qCAA+C;AAC/C,2BAA6C;AAE7C,QAAQ,CAAC,YAAY,EAAE;IACrB,IAAI,CAAC,+CAA+C,EAAE;QACpD,IAAM,YAAY,GAAG,EAAE,CAAC;QACxB,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,UAAM,eAAK,YAAY,gCAAe,CAAC,CAAC;QAChE,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,8CAA8C,EAAE;QACnD,IAAM,YAAY,GAAG;YACnB,IAAI,EAAE,CAAC;YACP,IAAI,EAAE,wBAAgB,CAAC,MAAM;SAC9B,CAAC;QACF,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,UAAM,eAAK,YAAY,gCAAe,CAAC,CAAC;QAChE,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,4CAA4C,EAAE;QACjD,IAAM,YAAY,GAAG;YACnB,IAAI,EAAE,CAAC;YACP,IAAI,EAAE,wBAAgB,CAAC,IAAI;SAC5B,CAAC;QACF,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,UAAM,eAAK,YAAY,gCAAe,CAAC,CAAC;QAChE,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,yCAAyC,EAAE;QAC9C,IAAM,YAAY,GAAG;YACnB,IAAI,EAAE,CAAC;YACP,IAAI,EAAE,wBAAgB,CAAC,MAAM;SAC9B,CAAC;QACF,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,UAAM,eAAK,YAAY,cAAE,kBAAC,UAAM,eAAK,YAAY,IAAE,IAAI,EAAE,CAAC,kCAAe,YAAS,CAAC,CAAC;QAC5G,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IACxC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,uCAAuC,EAAE;QAC5C,IAAM,YAAY,GAAG;YACnB,IAAI,EAAE,CAAC;YACP,IAAI,EAAE,wBAAgB,CAAC,MAAM;SAC9B,CAAC;QACF,IAAM,gBAAgB,GAAG;YACvB,MAAM,EAAE,CAAC;YACT,IAAI,EAAE,wBAAgB,CAAC,MAAM;SAC9B,CAAC;QACF,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,UAAM,eAAK,YAAY,cAAE,kBAAC,QAAI,eAAK,gBAAgB,gCAAa,YAAS,CAAC,CAAC;QACnG,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAC5C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,45 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var jsx_runtime_1 = require("react/jsx-runtime");
var utils_1 = require("../../utils");
var __1 = require("../..");
describe('<Text />', function () {
test('Should always render as is text with default props', function () {
var defaultProps = {};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.Text, __assign({}, defaultProps, { children: "Test" }), void 0));
expect(wrapper).toEqual('Test\n');
});
test('Should always render indentation with spaces', function () {
var defaultProps = {
indent: 4,
type: utils_1.IndentationTypes.SPACES
};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.Text, __assign({}, defaultProps, { children: "Test" }), void 0));
expect(wrapper).toEqual(' Test\n');
});
test('Should always render indentation with tabs', function () {
var defaultProps = {
indent: 2,
type: utils_1.IndentationTypes.TABS
};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.Text, __assign({}, defaultProps, { children: "Test" }), void 0));
expect(wrapper).toEqual(' Test\n');
});
test('Should be able to render nest texts', function () {
var defaultProps = {};
var wrapper = __1.render(jsx_runtime_1.jsx(__1.Text, __assign({}, defaultProps, { children: jsx_runtime_1.jsx(__1.Text, __assign({}, defaultProps, { children: "Test" }), void 0) }), void 0));
expect(wrapper).toEqual('Test\n\n');
});
});
//# sourceMappingURL=Text.spec.js.map
@@ -0,0 +1 @@
{"version":3,"file":"Text.spec.js","sourceRoot":"","sources":["../../../src/components/__tests__/Text.spec.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,qCAA+C;AAC/C,2BAAqC;AAErC,QAAQ,CAAC,UAAU,EAAE;IACnB,IAAI,CAAC,oDAAoD,EAAE;QACzD,IAAM,YAAY,GAAG,EAAE,CAAC;QACxB,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,QAAI,eAAK,YAAY,gCAAa,CAAC,CAAC;QAC5D,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,8CAA8C,EAAE;QACnD,IAAM,YAAY,GAAG;YACnB,MAAM,EAAE,CAAC;YACT,IAAI,EAAE,wBAAgB,CAAC,MAAM;SAC9B,CAAC;QACF,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,QAAI,eAAK,YAAY,gCAAa,CAAC,CAAC;QAC5D,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IACxC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,4CAA4C,EAAE;QACjD,IAAM,YAAY,GAAG;YACnB,MAAM,EAAE,CAAC;YACT,IAAI,EAAE,wBAAgB,CAAC,IAAI;SAC5B,CAAC;QACF,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,QAAI,eAAK,YAAY,gCAAa,CAAC,CAAC;QAC5D,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,qCAAqC,EAAE;QAC1C,IAAM,YAAY,GAAG,EAAE,CAAC;QACxB,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,QAAI,eAAK,YAAY,cAAE,kBAAC,QAAI,eAAK,YAAY,gCAAa,YAAO,CAAC,CAAC;QAC3F,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,6 @@
export { default as File } from "./File";
export type { FileProps } from "./File";
export { default as Text } from "./Text";
export type { TextProps } from "./Text";
export { default as Indent } from "./Indent";
export type { IndentProps } from "./Indent";
@@ -0,0 +1,13 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Indent = exports.Text = exports.File = void 0;
var File_1 = require("./File");
Object.defineProperty(exports, "File", { enumerable: true, get: function () { return __importDefault(File_1).default; } });
var Text_1 = require("./Text");
Object.defineProperty(exports, "Text", { enumerable: true, get: function () { return __importDefault(Text_1).default; } });
var Indent_1 = require("./Indent");
Object.defineProperty(exports, "Indent", { enumerable: true, get: function () { return __importDefault(Indent_1).default; } });
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/components/index.ts"],"names":[],"mappings":";;;;;;AAAA,+BAAyC;AAAhC,6GAAA,OAAO,OAAQ;AAGxB,+BAAyC;AAAhC,6GAAA,OAAO,OAAQ;AAGxB,mCAA6C;AAApC,iHAAA,OAAO,OAAU"}
@@ -0,0 +1,5 @@
export * from "./components";
export * from "./renderer";
export * from "./transpiler";
export * from "./types";
export { IndentationTypes, withIndendation, withNewLines } from "./utils";
@@ -0,0 +1,22 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.withNewLines = exports.withIndendation = exports.IndentationTypes = void 0;
__exportStar(require("./components"), exports);
__exportStar(require("./renderer"), exports);
__exportStar(require("./transpiler"), exports);
__exportStar(require("./types"), exports);
var utils_1 = require("./utils");
Object.defineProperty(exports, "IndentationTypes", { enumerable: true, get: function () { return utils_1.IndentationTypes; } });
Object.defineProperty(exports, "withIndendation", { enumerable: true, get: function () { return utils_1.withIndendation; } });
Object.defineProperty(exports, "withNewLines", { enumerable: true, get: function () { return utils_1.withNewLines; } });
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,+CAA6B;AAC7B,6CAA2B;AAC3B,+CAA6B;AAC7B,0CAAwB;AACxB,iCAA0E;AAAjE,yGAAA,gBAAgB,OAAA;AAAE,wGAAA,eAAe,OAAA;AAAE,qGAAA,YAAY,OAAA"}
@@ -0,0 +1,3 @@
declare function _exports(): Promise<React.FunctionComponentElement<import("../../..").PropsWithChildrenContent<import("../../../components").FileProps>>>;
export = _exports;
import React = require("react");
@@ -0,0 +1,48 @@
"use strict";
/* eslint-disable */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var React = require('react');
var File = require('../../../components').File;
module.exports = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, React.createElement(File, { name: 'file.html' }, ['Content'])];
});
});
};
//# sourceMappingURL=async-template.js.map
@@ -0,0 +1 @@
{"version":3,"file":"async-template.js","sourceRoot":"","sources":["../../../../src/renderer/__tests__/file-tests/async-template.js"],"names":[],"mappings":";AAAA,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpB,IAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AACvB,IAAA,IAAI,GAAK,OAAO,CAAC,qBAAqB,CAAC,KAAnC,CAAoC;AAEhD,MAAM,CAAC,OAAO,GAAG;;;YACf,sBAAO,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,EAAC;;;CACtE,CAAC"}
@@ -0,0 +1,3 @@
declare function _exports(): (React.FunctionComponentElement<import("../../..").PropsWithChildrenContent<import("../../../components").FileProps>> | undefined)[];
export = _exports;
import React = require("react");
@@ -0,0 +1,12 @@
"use strict";
/* eslint-disable */
var React = require('react');
var File = require('../../../components').File;
module.exports = function () {
return [
React.createElement(File, { name: 'file1.html' }, ['Content1']),
undefined,
React.createElement(File, { name: 'file2.html' }, ['Content2'])
];
};
//# sourceMappingURL=file-templates.js.map
@@ -0,0 +1 @@
{"version":3,"file":"file-templates.js","sourceRoot":"","sources":["../../../../src/renderer/__tests__/file-tests/file-templates.js"],"names":[],"mappings":";AAAA,oBAAoB;AAEpB,IAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AACvB,IAAA,IAAI,GAAK,OAAO,CAAC,qBAAqB,CAAC,KAAnC,CAAoC;AAEhD,MAAM,CAAC,OAAO,GAAG;IACf,OAAO;QACL,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC;QAC/D,SAAS;QACT,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC;KAChE,CAAC;AACJ,CAAC,CAAC"}
@@ -0,0 +1,3 @@
declare function _exports(): React.FunctionComponentElement<import("../../..").PropsWithChildrenContent<import("../../../components").FileProps>>;
export = _exports;
import React = require("react");
@@ -0,0 +1,8 @@
"use strict";
/* eslint-disable */
var React = require('react');
var File = require('../../../components').File;
module.exports = function () {
return React.createElement(File, { name: 'file.html' }, ['Content']);
};
//# sourceMappingURL=single-template.js.map
@@ -0,0 +1 @@
{"version":3,"file":"single-template.js","sourceRoot":"","sources":["../../../../src/renderer/__tests__/file-tests/single-template.js"],"names":[],"mappings":";AAAA,oBAAoB;AAEpB,IAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AACvB,IAAA,IAAI,GAAK,OAAO,CAAC,qBAAqB,CAAC,KAAnC,CAAoC;AAEhD,MAAM,CAAC,OAAO,GAAG;IACf,OAAO,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;AACvE,CAAC,CAAC"}
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,165 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var jsx_runtime_1 = require("react/jsx-runtime");
var react_1 = __importDefault(require("react"));
var __1 = require("../..");
describe('Renderer', function () {
test('should render works when element is string', function () {
var content = __1.render("Test 1");
expect(content).toEqual("Test 1");
});
test('should render works when element is a Funcion Component', function () {
function Test() {
return jsx_runtime_1.jsx(jsx_runtime_1.Fragment, { children: "Test 2" }, void 0);
}
var content = __1.render(jsx_runtime_1.jsx(Test, {}, void 0));
expect(content).toEqual("Test 2");
});
test('should render works when element is a Class Component', function () {
var Test = /** @class */ (function (_super) {
__extends(Test, _super);
function Test(props) {
return _super.call(this, props) || this;
}
Test.prototype.render = function () {
return jsx_runtime_1.jsx(jsx_runtime_1.Fragment, { children: "Test 3" }, void 0);
};
return Test;
}(react_1.default.Component));
var content = __1.render(jsx_runtime_1.jsx(Test, {}, void 0));
expect(content).toEqual("Test 3");
});
test('should render works with nested hierarchy', function () {
function NestedComponent() {
return jsx_runtime_1.jsx(jsx_runtime_1.Fragment, { children: "Nested Component" }, void 0);
}
function FunctionComponent() {
return jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: ["Function Component ", jsx_runtime_1.jsx(NestedComponent, {}, void 0), "\n"] }, void 0);
}
var ClassComponent = /** @class */ (function (_super) {
__extends(ClassComponent, _super);
function ClassComponent(props) {
return _super.call(this, props) || this;
}
ClassComponent.prototype.render = function () {
return jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: ["Class Component", "\n"] }, void 0);
};
return ClassComponent;
}(react_1.default.Component));
var content = __1.render(jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: ["some inlined text", "\n", jsx_runtime_1.jsx(FunctionComponent, {}, void 0),
jsx_runtime_1.jsx(ClassComponent, {}, void 0)] }, void 0));
expect(content).toEqual("some inlined text\nFunction Component Nested Component\nClass Component\n");
});
test('should render works with props', function () {
function Test(_a) {
var someProp = _a.someProp;
if (!someProp) {
return jsx_runtime_1.jsx(Test, { someProp: "Nested prop" }, void 0);
}
return jsx_runtime_1.jsx(jsx_runtime_1.Fragment, { children: someProp }, void 0);
}
var content = __1.render(jsx_runtime_1.jsx(Test, {}, void 0));
expect(content).toEqual("Nested prop");
});
test('should render works with null as returned value', function () {
function Test() {
return null;
}
var content = __1.render(jsx_runtime_1.jsx(Test, {}, void 0));
expect(content).toEqual("");
});
test('should render works nested null value', function () {
function NullComponent() {
return null;
}
function NestedComponent() {
return (jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: [jsx_runtime_1.jsx(NullComponent, {}, void 0), "some text"] }, void 0));
}
function Component() {
return (jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: [jsx_runtime_1.jsx(NullComponent, {}, void 0),
jsx_runtime_1.jsx(NestedComponent, {}, void 0),
jsx_runtime_1.jsx(NullComponent, {}, void 0)] }, void 0));
}
var content = __1.render(jsx_runtime_1.jsx(Component, {}, void 0));
expect(content).toEqual("some text");
});
test('should works with array as returned value', function () {
function Component(_a) {
var text = _a.text;
return jsx_runtime_1.jsx(jsx_runtime_1.Fragment, { children: text }, void 0);
}
function Test() {
return [
jsx_runtime_1.jsx(Component, { text: 'some' }, void 0),
jsx_runtime_1.jsx(Component, { text: ' text' }, void 0),
jsx_runtime_1.jsx(Component, { text: ' is rendered' }, void 0),
];
}
var content = __1.render(jsx_runtime_1.jsx(Test, {}, void 0));
expect(content).toEqual("some text is rendered");
});
test('should throws error due to using React hooks', function () {
function Component() {
var _a = react_1.default.useState(), someState = _a[0], setSomeState = _a[1];
return null;
}
var error = undefined;
try {
__1.render(jsx_runtime_1.jsx(Component, {}, void 0));
}
catch (err) {
error = err;
}
// check substring of the desired error
expect(error.message).toContain('Invalid hook call.');
});
test('should skips internal React components', function () {
function Component() {
return (jsx_runtime_1.jsx(react_1.default.Suspense, __assign({ fallback: '...loading' }, { children: "some text" }), void 0));
}
var content = __1.render(jsx_runtime_1.jsx(Component, {}, void 0));
expect(content).toEqual("some text");
});
test('should throws error due to using HTML tags', function () {
function Component() {
return (jsx_runtime_1.jsx("div", { children: "some text" }, void 0));
}
var error = undefined;
try {
__1.render(jsx_runtime_1.jsx(Component, {}, void 0));
}
catch (err) {
error = err;
}
// check substring of the desired error
expect(error.message).toEqual('HTML tags is not supported yet.');
});
});
//# sourceMappingURL=renderer.spec.js.map
@@ -0,0 +1 @@
{"version":3,"file":"renderer.spec.js","sourceRoot":"","sources":["../../../src/renderer/__tests__/renderer.spec.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gDAA0B;AAC1B,2BAA+B;AAE/B,QAAQ,CAAC,UAAU,EAAE;IACnB,IAAI,CAAC,4CAA4C,EAAE;QACjD,IAAM,OAAO,GAAG,UAAM,CAAC,QAAQ,CAAC,CAAC;QACjC,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,yDAAyD,EAAE;QAC9D,SAAS,IAAI;YACX,OAAO,yEAAW,CAAA;QACpB,CAAC;QAED,IAAM,OAAO,GAAG,UAAM,CAAC,kBAAC,IAAI,aAAG,CAAC,CAAC;QACjC,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,uDAAuD,EAAE;QAC5D;YAAmB,wBAAe;YAChC,cAAY,KAAU;uBAAI,kBAAM,KAAK,CAAC;YAAC,CAAC;YAExC,qBAAM,G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iter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var path_1 = __importDefault(require("path"));
var template_1 = require("../template");
describe('renderTemplate', function () {
test('should render a single File template', function () { return __awaiter(void 0, void 0, void 0, function () {
var filePath, renderedContent;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
filePath = path_1.default.resolve(__dirname, './file-tests/single-template.js');
return [4 /*yield*/, template_1.renderTemplate(filePath, {})];
case 1:
renderedContent = _a.sent();
expect(typeof renderedContent).toEqual('object');
expect(renderedContent.content).toEqual('Content');
expect(renderedContent.metadata.fileName).toEqual('file.html');
return [2 /*return*/];
}
});
}); });
test('should render an array of File templates', function () { return __awaiter(void 0, void 0, void 0, function () {
var filePath, renderedContent;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
filePath = path_1.default.resolve(__dirname, './file-tests/file-templates.js');
return [4 /*yield*/, template_1.renderTemplate(filePath, {})];
case 1:
renderedContent = _a.sent();
expect(Array.isArray(renderedContent)).toEqual(true);
expect(typeof renderedContent[0]).toEqual('object');
expect(renderedContent[0].content).toEqual('Content1');
expect(renderedContent[0].metadata.fileName).toEqual('file1.html');
expect(typeof renderedContent[1]).toEqual('object');
expect(renderedContent[1].content).toEqual('Content2');
expect(renderedContent[1].metadata.fileName).toEqual('file2.html');
return [2 /*return*/];
}
});
}); });
test('should render a single async File template', function () { return __awaiter(void 0, void 0, void 0, function () {
var filePath, renderedContent;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
filePath = path_1.default.resolve(__dirname, './file-tests/async-template.js');
return [4 /*yield*/, template_1.renderTemplate(filePath, {})];
case 1:
renderedContent = _a.sent();
expect(typeof renderedContent).toEqual('object');
expect(renderedContent.content).toEqual('Content');
expect(renderedContent.metadata.fileName).toEqual('file.html');
return [2 /*return*/];
}
});
}); });
});
//# sourceMappingURL=template.spec.js.map
@@ -0,0 +1 @@
{"version":3,"file":"template.spec.js","sourceRoot":"","sources":["../../../src/renderer/__tests__/template.spec.ts"],"names":[],"mappings":";;;;;;;;;;;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AAC,OAAO,CAAC,QAAQ,CAAC,CAAC;oBACpD,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;oBACvD,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;;;;SACpE,CAAC,CAAC;IAEH,IAAI,CAAC,4CAA4C,EAAE;;;;;oBAC3C,QAAQ,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,gCAAgC,CAAC,CAAC;oBACnD,qBAAM,yBAAc,CAAC,QAAQ,EAAE,EAAS,CAAC,EAAA;;oBAA3D,eAAe,GAAG,SAAiE;oBAEzF,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;oBACjD,MAAM,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;oBACnD,MAAM,CAAC,eAAe,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;;;;SAChE,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,2 @@
export * from "./renderer";
export * from "./template";
@@ -0,0 +1,15 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./renderer"), exports);
__exportStar(require("./template"), exports);
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/renderer/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,6CAA2B;AAC3B,6CAA2B"}
@@ -0,0 +1,13 @@
/// <reference types="react" />
/**
* Renders given component to string
*
* @param {ReactNode} component a given component to rendering
* @example
* function Component({ textProp }) {
* return <>{textProp}</>
* }
* render(<Component textProp="someText" />)
* @returns {string}
*/
export declare function render(component: React.ReactNode): string;
@@ -0,0 +1,87 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.render = void 0;
/**
* Normalizes given props with render children to string and save value to `childrenContent` prop
* @private
* @param {Any} props
* @returns {Any} normalized props.
*/
function normalizeProps(props) {
return __assign(__assign({}, props), { childrenContent: render(props.children) });
}
/**
* Executes a `render` method on a given component (in the case of a class component)
* or executes the component itself (a functional component) to get pure string or complex value for the next operations
* @private
* @param {React.ReactElement} element a given component or complex form
* @returns {(React.ReactElement | string)}
*/
function createElement(element) {
if (!element) {
return "";
}
var typeOf = typeof element.type;
if (typeOf === 'string') {
// HTML (also not standard) tags case
throw new Error("HTML tags is not supported yet.");
}
else if (typeOf === 'symbol') {
// internal React types like Fragments, Portal etc. We skip them.
return render(element.props.children);
}
else if (typeOf === 'function') {
// custom components case
var type = element.type;
var prototype = type.prototype;
// Class component case
if (prototype && typeof prototype.isReactComponent === "object") {
var clazzComp = new type(normalizeProps(element.props));
return createElement(clazzComp.render());
}
// Function component case
return createElement(type(normalizeProps(element.props)));
}
return render(element) || "";
}
/**
* Renders given component to string
*
* @param {ReactNode} component a given component to rendering
* @example
* function Component({ textProp }) {
* return <>{textProp}</>
* }
* render(<Component textProp="someText" />)
* @returns {string}
*/
function render(component) {
var content = "";
var typeOf = typeof component;
if (typeOf === 'string') {
content += component;
}
else if (Array.isArray(component)) {
content += component.map(function (child) {
var childValue = createElement(child);
return render(childValue);
}).join("");
}
else if (typeOf === "object") {
content += createElement(component);
}
return content;
}
exports.render = render;
//# sourceMappingURL=renderer.js.map
@@ -0,0 +1 @@
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["../../src/renderer/renderer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAEA;;;;;GAKG;AACH,SAAS,cAAc,CAAU,KAAU;IACzC,6BACK,KAAK,KACR,eAAe,EAAE,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IACxC;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,OAA2B;IAChD,IAAI,CAAC,OAAO,EAAE;QACZ,OAAO,EAAE,CAAC;KACX;IACD,IAAM,MAAM,GAAG,OAAO,OAAO,CAAC,IAAI,CAAC;IAEnC,IAAI,MAAM,KAAK,QAAQ,EAAE;QACvB,qCAAqC;QACrC,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;KACpD;SAAM,IAAI,MAAM,KAAK,QAAQ,EAAE;QAC9B,iEAAiE;QACjE,OAAO,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;KACvC;SAAM,IAAI,MAAM,KAAK,UAAU,EAAE;QAChC,yBAAyB;QACzB,IAAM,IAAI,GAAG,OAAO,CAAC,IAAW,CAAC;QACjC,IAAM,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QAEjC,uBAAuB;QACvB,IAAI,SAAS,IAAI,OAAO,SAAS,CAAC,gBAAgB,KAAK,QAAQ,EAAE;YAC/D,IAAM,SAAS,GAAG,IAAI,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;YAC1D,OAAO,aAAa,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC;SAC1C;QACD,0BAA0B;QAC1B,OAAO,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC3D;IAED,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;AAC/B,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,MAAM,CAAC,SAA0B;IAC/C,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,IAAM,MAAM,GAAG,OAAO,SAAS,CAAC;IAChC,IAAI,MAAM,KAAK,QAAQ,EAAE;QACvB,OAAO,IAAI,SAAS,CAAC;KACtB;SAAM,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE;QACnC,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,UAAA,KAAK;YAC5B,IAAM,UAAU,GAAG,aAAa,CAAC,KAA2B,CAAC,CAAC;YAC9D,OAAO,MAAM,CAAC,UAAU,CAAC,CAAC;QAC5B,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;KACb;SAAM,IAAI,MAAM,KAAK,QAAQ,EAAE;QAC9B,OAAO,IAAI,aAAa,CAAC,SAA+B,CAAC,CAAC;KAC3D;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAdD,wBAcC"}
@@ -0,0 +1,7 @@
import { TemplateContext, TemplateRenderResult } from "../types";
/**
* render a file with react. This function automatically transforms jsx to js before importing the component.
*
* @param filepath the path to file to render
*/
export declare function renderTemplate(filepath: string, context: TemplateContext): Promise<TemplateRenderResult[] | TemplateRenderResult | undefined>;
@@ -0,0 +1,136 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderTemplate = void 0;
var renderer_1 = require("./renderer");
var utils_1 = require("../utils");
/**
* render a file with react. This function automatically transforms jsx to js before importing the component.
*
* @param filepath the path to file to render
*/
function renderTemplate(filepath, context) {
return __awaiter(this, void 0, void 0, function () {
var data, component, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!utils_1.isJsFile(filepath)) {
return [2 /*return*/, undefined];
}
data = undefined;
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 5]);
return [4 /*yield*/, importComponent(filepath)];
case 2:
component = _a.sent();
if (component === undefined) {
return [2 /*return*/, undefined];
}
return [4 /*yield*/, component(context)];
case 3:
data = _a.sent();
return [3 /*break*/, 5];
case 4:
err_1 = _a.sent();
throw err_1;
case 5:
// undefined, null etc. cases
if (!data) {
return [2 /*return*/, undefined];
}
if (Array.isArray(data)) {
return [2 /*return*/, data.map(function (file) { return file && renderFile(file); }).filter(Boolean)];
}
return [2 /*return*/, renderFile(data)];
}
});
});
}
exports.renderTemplate = renderTemplate;
/**
* Imports a given file and return the imported component
*
* @private
* @param filepath to import
*/
function importComponent(filepath) {
return new Promise(function (resolve, reject) {
try {
// we should import component only in NodeJS
if (require === undefined)
resolve(undefined);
// remove from cache imported file
delete require.cache[require.resolve(filepath)];
var component = require(filepath);
if (typeof component === "function")
resolve(component);
if (typeof component.default === "function")
resolve(component.default);
resolve(undefined);
}
catch (err) {
reject(err);
}
});
}
/**
* Render a single File component.
*
* @private
* @param {React.ReactElement} file to import
*/
function renderFile(file) {
if (typeof file !== "object") {
return undefined;
}
var type = file.type, _a = file.props, props = _a === void 0 ? {} : _a;
// if no File component is found as root, don't render it.
if (typeof type !== "function" || type.name !== "File") {
return undefined;
}
return {
content: renderer_1.render(props.children),
metadata: {
fileName: props.name,
permissions: props.permissions,
}
};
}
//# sourceMappingURL=template.js.map
@@ -0,0 +1 @@
{"version":3,"file":"template.js","sourceRoot":"","sources":["../../src/renderer/template.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,uCAAoC;AACpC,kCAAoC;AAGpC;;;;GAIG;AACH,SAAsB,cAAc,CAAC,QAAgB,EAAE,OAAwB;;;;;;oBAC7E,IAAI,CAAC,gBAAQ,CAAC,QAAQ,CAAC,EAAE;wBACvB,sBAAO,SAAS,EAAC;qBAClB;oBAEG,IAAI,GAAG,SAAS,CAAC;;;;oBAED,qBAAM,eAAe,CAAC,QAAQ,CAAC,EAAA;;oBAA3C,SAAS,GAAG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G;AACH,SAAS,UAAU,CAAC,IAAwB;IAC1C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,OAAO,SAAS,CAAC;KAClB;IACO,IAAA,IAAI,GAAiB,IAAI,KAArB,EAAE,KAAe,IAAI,MAAT,EAAV,KAAK,mBAAG,EAAE,KAAA,CAAU;IAElC,0DAA0D;IAC1D,IAAI,OAAO,IAAI,KAAK,UAAU,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE;QACtD,OAAO,SAAS,CAAC;KAClB;IAED,OAAO;QACL,OAAO,EAAE,iBAAM,CAAC,KAAK,CAAC,QAAQ,CAAC;QAC/B,QAAQ,EAAE;YACR,QAAQ,EAAE,KAAK,CAAC,IAAI;YACpB,WAAW,EAAE,KAAK,CAAC,WAAW;SAC/B;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,256 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = __importDefault(require("fs"));
var path_1 = __importDefault(require("path"));
var util_1 = require("util");
var transpiler_1 = require("../transpiler");
var renderer_1 = require("../../renderer");
var readFile = util_1.promisify(fs_1.default.readFile);
describe('Transpiler', function () {
var testFiles = path_1.default.resolve(__dirname, './testfiles');
var outputFiles = path_1.default.resolve(__dirname, './__transpiled_testfiles');
beforeAll(function (done) { return __awaiter(void 0, void 0, void 0, function () {
var e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, transpiler_1.transpileFiles(testFiles, outputFiles, {
recursive: true
})];
case 1:
_a.sent();
done();
return [3 /*break*/, 3];
case 2:
e_1 = _a.sent();
console.log(e_1);
done(e_1);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); });
describe('should transpile CommonJS files', function () {
describe('with a simple setup', function () {
var commonjs_testFile = path_1.default.resolve(outputFiles, './CommonJS/simple.js');
var commonjs_testFileMap = path_1.default.resolve(outputFiles, './CommonJS/simple.js.map');
test('and import correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
var content, mapContent, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, readFile(commonjs_testFile, 'utf8')];
case 1:
content = _b.sent();
expect(switchToUnixLinebreaks(content)).toMatchSnapshot();
return [4 /*yield*/, readFile(commonjs_testFileMap, 'utf8')];
case 2:
mapContent = _b.sent();
expect(switchToUnixLinebreaks(mapContent)).toMatchSnapshot();
_a = expect;
return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require(commonjs_testFile)); })];
case 3:
_a.apply(void 0, [_b.sent()]).toBeDefined();
return [2 /*return*/];
}
});
}); });
test('and render correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
var content;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, renderer_1.renderTemplate(commonjs_testFile, { asyncapi: {}, originalAsyncAPI: "", params: {} })];
case 1:
content = _b.sent();
expect((_a = content) === null || _a === void 0 ? void 0 : _a.content).toBe("hello Test");
return [2 /*return*/];
}
});
}); });
});
});
describe('should transpile ES5 files', function () {
describe('with a simple setup', function () {
var es5_testFile = path_1.default.resolve(outputFiles, './ES5/simple.js');
var es5_testFileMap = path_1.default.resolve(outputFiles, './ES5/simple.js.map');
test('and import correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
var content, mapContent, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, readFile(es5_testFile, 'utf8')];
case 1:
content = _b.sent();
expect(switchToUnixLinebreaks(content)).toMatchSnapshot();
return [4 /*yield*/, readFile(es5_testFileMap, 'utf8')];
case 2:
mapContent = _b.sent();
expect(switchToUnixLinebreaks(mapContent)).toMatchSnapshot();
_a = expect;
return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require(es5_testFile)); })];
case 3:
_a.apply(void 0, [_b.sent()]).toBeDefined();
return [2 /*return*/];
}
});
}); });
test('and render correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
var content;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, renderer_1.renderTemplate(es5_testFile, { asyncapi: {}, originalAsyncAPI: "", params: {} })];
case 1:
content = _b.sent();
expect((_a = content) === null || _a === void 0 ? void 0 : _a.content).toBe("hello Test");
return [2 /*return*/];
}
});
}); });
});
});
describe('should transpile ES6 files', function () {
describe('with a simple setup', function () {
var es6_testFile = path_1.default.resolve(outputFiles, './ES6/simple.js');
var es6_testFileMap = path_1.default.resolve(outputFiles, './ES6/simple.js.map');
test('and import correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
var content, mapContent, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, readFile(es6_testFile, 'utf8')];
case 1:
content = _b.sent();
expect(switchToUnixLinebreaks(content)).toMatchSnapshot();
return [4 /*yield*/, readFile(es6_testFileMap, 'utf8')];
case 2:
mapContent = _b.sent();
expect(switchToUnixLinebreaks(mapContent)).toMatchSnapshot();
_a = expect;
return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require(es6_testFile)); })];
case 3:
_a.apply(void 0, [_b.sent()]).toBeDefined();
return [2 /*return*/];
}
});
}); });
test('and render correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
var content;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, renderer_1.renderTemplate(es6_testFile, { asyncapi: {}, originalAsyncAPI: "", params: {} })];
case 1:
content = _b.sent();
expect((_a = content) === null || _a === void 0 ? void 0 : _a.content).toBe("hello Test");
return [2 /*return*/];
}
});
}); });
});
});
describe('should keep names of files, even if special chars', function () {
describe('with a simple setup', function () {
var special_testFile = path_1.default.resolve(outputFiles, './SpecialChars/$$simple$$.js');
var special_testFileMap = path_1.default.resolve(outputFiles, './SpecialChars/$$simple$$.js.map');
test('and import correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
var content, mapContent, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, readFile(special_testFile, 'utf8')];
case 1:
content = _b.sent();
expect(switchToUnixLinebreaks(content)).toMatchSnapshot();
return [4 /*yield*/, readFile(special_testFileMap, 'utf8')];
case 2:
mapContent = _b.sent();
expect(switchToUnixLinebreaks(mapContent)).toMatchSnapshot();
_a = expect;
return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require(special_testFile)); })];
case 3:
_a.apply(void 0, [_b.sent()]).toBeDefined();
return [2 /*return*/];
}
});
}); });
test('and render correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
var content;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, renderer_1.renderTemplate(special_testFile, { asyncapi: {}, originalAsyncAPI: "", params: {} })];
case 1:
content = _b.sent();
expect((_a = content) === null || _a === void 0 ? void 0 : _a.content).toBe("hello Test");
return [2 /*return*/];
}
});
}); });
});
});
});
/*
It is a helper required for snapshot testing on windows. It can't be solved by editor configuration and the end line setting because snapshots are generated not created in the editor.
We need to remove `\r` from files transpiled on windows before we can match them with the snapshot generated on unix
*/
function switchToUnixLinebreaks(str) {
return str.replace(/\\r/g, "");
}
//# sourceMappingURL=transpiler.spec.js.map
@@ -0,0 +1 @@
{"version":3,"file":"transpiler.spec.js","sourceRoot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,MAAM,OAAE,OAAgC,0CAAE,OAAO,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;;;;iBACvE,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH;;;EAGE;AACF,SAAS,sBAAsB,CAAC,GAAW;IACzC,OAAO,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAA;AAChC,CAAC"}
@@ -0,0 +1 @@
export * from "./transpiler";
@@ -0,0 +1,14 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./transpiler"), exports);
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/transpiler/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,+CAA6B"}
@@ -0,0 +1,9 @@
import { TranspileFilesOptions } from '../types';
/**
* Transpile files in a given directory (and sub directory if recursive option are passed) and write it to an output directory, if no errors are thrown it completed successfully.
*
* @param directory to transpile.
* @param outputDir to write the transpiled files to.
* @param options any extra options that should be passed.
*/
export declare function transpileFiles(directory: string, outputDir: string, options?: TranspileFilesOptions): Promise<void>;
@@ -0,0 +1,121 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transpileFiles = void 0;
var path_1 = __importDefault(require("path"));
var rollup_1 = require("rollup");
var plugin_babel_1 = __importDefault(require("@rollup/plugin-babel"));
var utils_1 = require("../utils");
var ROOT_DIR = path_1.default.resolve(__dirname, '../..');
/**
* Transpile files in a given directory (and sub directory if recursive option are passed) and write it to an output directory, if no errors are thrown it completed successfully.
*
* @param directory to transpile.
* @param outputDir to write the transpiled files to.
* @param options any extra options that should be passed.
*/
function transpileFiles(directory, outputDir, options) {
return __awaiter(this, void 0, void 0, function () {
var _a, files, dirs, bundles, _i, dirs_1, subdir, subdirPath;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, utils_1.getStatsInDir(directory)];
case 1:
_a = _b.sent(), files = _a.files, dirs = _a.dirs;
if (!files.length) return [3 /*break*/, 4];
return [4 /*yield*/, rollup_1.rollup({
input: files,
onwarn: function () { },
plugins: [
plugin_babel_1.default({
cwd: ROOT_DIR,
babelHelpers: "bundled",
plugins: [
"source-map-support",
],
presets: [
["@babel/preset-env", {
targets: { node: "12.16" },
}],
["@babel/preset-react", {
runtime: "automatic",
}],
],
})
],
})];
case 2:
bundles = _b.sent();
return [4 /*yield*/, bundles.write({
format: "commonjs",
sourcemap: true,
dir: outputDir,
exports: "auto",
paths: {
'react/jsx-runtime': 'react/cjs/react-jsx-runtime.production.min',
},
sanitizeFileName: false,
})];
case 3:
_b.sent();
_b.label = 4;
case 4:
if (!((options === null || options === void 0 ? void 0 : options.recursive) === true && dirs.length > 0)) return [3 /*break*/, 8];
_i = 0, dirs_1 = dirs;
_b.label = 5;
case 5:
if (!(_i < dirs_1.length)) return [3 /*break*/, 8];
subdir = dirs_1[_i];
subdirPath = path_1.default.parse(subdir);
return [4 /*yield*/, transpileFiles(subdir, path_1.default.resolve(outputDir, subdirPath.base), options)];
case 6:
_b.sent();
_b.label = 7;
case 7:
_i++;
return [3 /*break*/, 5];
case 8: return [2 /*return*/];
}
});
});
}
exports.transpileFiles = transpileFiles;
//# sourceMappingURL=transpiler.js.map
@@ -0,0 +1 @@
{"version":3,"file":"transpiler.js","sourceRoot":"","sources":["../../src/transpiler/transpiler.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;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BAA8C;0BACrB,EAAJ,aAAI;;;yBAAJ,CAAA,kBAAI,CAAA;oBAAd,MAAM;oBACP,UAAU,GAAG,cAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;oBACtC,qBAAM,cAAc,CAAC,MAAM,EAAE,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,UAAU,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,EAAA;;oBAA/E,SAA+E,CAAC;;;oBAF/D,IAAI,CAAA;;;;;;CAKhC;AAlDD,wCAkDC"}
@@ -0,0 +1,39 @@
import React from "react";
import { AsyncAPIDocument } from "@asyncapi/parser";
export declare type PropsWithChildrenContent<P> = P & {
childrenContent?: string;
};
export declare type FC<P = {}> = FunctionComponent<P>;
export declare type FunctionComponent<P = {}> = React.FunctionComponent<PropsWithChildrenContent<P>>;
export declare class Component<P = {}> extends React.Component<PropsWithChildrenContent<P>> {
}
/**
* Shape of the context passed to template
*/
export interface TemplateContext<P = Record<string, any>> {
asyncapi: AsyncAPIDocument;
params: P;
originalAsyncAPI: string;
[key: string]: any;
}
/**
* Signature for template function
*/
export declare type TemplateFunction<R = React.ReactElement | undefined> = (context: TemplateContext) => R | Promise<R>;
/**
* Options for transpiling files.
*/
export declare type TranspileFilesOptions = {
/**
* Should all files in a directory including those in subdirectories be included
*/
recursive?: boolean;
};
export declare type TemplateRenderMetadata = {
fileName?: string;
permissions?: string;
};
export declare type TemplateRenderResult = {
metadata: TemplateRenderMetadata;
content: string;
};
@@ -0,0 +1,29 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Component = void 0;
var react_1 = __importDefault(require("react"));
var Component = /** @class */ (function (_super) {
__extends(Component, _super);
function Component() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Component;
}(react_1.default.Component));
exports.Component = Component;
//# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,gDAA0B;AAS1B;IAAuC,6BAA4C;IAAnF;;IAAqF,CAAC;IAAD,gBAAC;AAAD,CAAC,AAAtF,CAAuC,eAAK,CAAC,SAAS,GAAgC;AAAzE,8BAAS"}
@@ -0,0 +1,13 @@
declare class GetFilesResponse {
files: string[];
dirs: string[];
constructor(files: string[], dirs: string[]);
}
/**
* Function which finds all the files and dirs in folders
* @private
* @param dir directory to find files and dirs in.
* @param includeSubDirs should the function iterate through subdirectories to search for files and dirs?
*/
export declare function getStatsInDir(dir: string): Promise<GetFilesResponse>;
export {};
@@ -0,0 +1,103 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStatsInDir = void 0;
var path_1 = __importDefault(require("path"));
var fs_1 = __importDefault(require("fs"));
var util_1 = require("util");
var _1 = require(".");
var readdir = util_1.promisify(fs_1.default.readdir);
var stat = util_1.promisify(fs_1.default.stat);
var GetFilesResponse = /** @class */ (function () {
function GetFilesResponse(files, dirs) {
this.files = files;
this.dirs = dirs;
}
return GetFilesResponse;
}());
/**
* Function which finds all the files and dirs in folders
* @private
* @param dir directory to find files and dirs in.
* @param includeSubDirs should the function iterate through subdirectories to search for files and dirs?
*/
function getStatsInDir(dir) {
return __awaiter(this, void 0, void 0, function () {
var allFiles, files, dirs, _i, allFiles_1, filename, res, stats, resolveFilenameCallback;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, readdir(dir)];
case 1:
allFiles = _a.sent();
files = [];
dirs = [];
_i = 0, allFiles_1 = allFiles;
_a.label = 2;
case 2:
if (!(_i < allFiles_1.length)) return [3 /*break*/, 5];
filename = allFiles_1[_i];
res = path_1.default.resolve(dir, filename);
return [4 /*yield*/, stat(res)];
case 3:
stats = _a.sent();
if (stats.isDirectory()) {
dirs.push(res);
}
else if (_1.isJsFile(filename)) {
files.push(res);
}
_a.label = 4;
case 4:
_i++;
return [3 /*break*/, 2];
case 5:
resolveFilenameCallback = function (filename) {
return path_1.default.resolve(dir, filename);
};
files = files.map(resolveFilenameCallback);
dirs = dirs.map(resolveFilenameCallback);
return [2 /*return*/, new GetFilesResponse(files, dirs)];
}
});
});
}
exports.getStatsInDir = getStatsInDir;
//# sourceMappingURL=getStatsInDir.js.map
@@ -0,0 +1 @@
{"version":3,"file":"getStatsInDir.js","sourceRoot":"","sources":["../../src/utils/getStatsInDir.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8CAAwB;AACxB,0CAAoB;AACpB,6BAAiC;AACjC,sBAA6B;AAE7B,IAAM,OAAO,GAAG,gBAAS,CAAC,YAAE,CAAC,OAAO,CAAC,CAAC;AACtC,IAAM,IAAI,GAAG,gBAAS,CAAC,YAAE,CAAC,IAAI,CAAC,CAAC;AAEhC;IAGI,0BAAa,KAAe,EAAE,IAAc;QACxC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACrB,CAAC;IACL,uBAAC;AAAD,CAAC,AAPD,IAOC;AAED;;;;;GAKG;AACH,SAAsB,aAAa,CAAC,GAAW;;;;;wBAC1B,qBAAM,OAAO,CAAC,GAAG,CAAC,EAAA;;oBAA7B,QAAQ,GAAG,SAAkB;oBAC/B,KAAK,GAAa,EAAE,CAAC;oBACrB,IAAI,GAAa,EAAE,CAAC;0BACO,EAAR,qBAAQ;;;yBAAR,CAAA,sBAAQ,CAAA;oBAApB,QAAQ;oBACT,GAAG,GAAG,cAAI,CAAC,OAAO,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;oBAC1B,qBAAM,IAAI,CAAC,GAAG,CAAC,EAAA;;oBAAvB,KAAK,GAAG,SAAe;oBAC7B,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE;wBACrB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;qBACjB;yBAAM,IAAI,WAAQ,CAAC,QAAQ,CAAC,EAAE;wBAC3B,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;qBACnB;;;oBAPkB,IAAQ,CAAA;;;oBASzB,uBAAuB,GAAG,UAAC,QAAgB;wBAC7C,OAAO,cAAI,CAAC,OAAO,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;oBACvC,CAAC,CAAA;oBACD,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;oBAC3C,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;oBACzC,sBAAO,IAAI,gBAAgB,CAAC,KAAK,EAAE,IAAI,CAAC,EAAC;;;;CAC5C;AAnBD,sCAmBC"}
@@ -0,0 +1,4 @@
export * from "./getStatsInDir";
export * from "./isJsFile";
export * from "./withIndendation";
export * from "./withNewLines";
@@ -0,0 +1,17 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./getStatsInDir"), exports);
__exportStar(require("./isJsFile"), exports);
__exportStar(require("./withIndendation"), exports);
__exportStar(require("./withNewLines"), exports);
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,kDAAgC;AAChC,6CAA2B;AAC3B,oDAAkC;AAClC,iDAA+B"}
@@ -0,0 +1,7 @@
/**
* Function which checks if file is JS file
* @private
* @param {string} filename
* @returns {boolean}
*/
export declare function isJsFile(filename?: string): boolean;
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isJsFile = void 0;
var ALLOWED_EXTS = ['js', 'jsx', 'cjs'];
/**
* Function which checks if file is JS file
* @private
* @param {string} filename
* @returns {boolean}
*/
function isJsFile(filename) {
if (filename === void 0) { filename = ''; }
var ext = filename.split('.').pop() || '';
return ALLOWED_EXTS.includes(ext);
}
exports.isJsFile = isJsFile;
//# sourceMappingURL=isJsFile.js.map
@@ -0,0 +1 @@
{"version":3,"file":"isJsFile.js","sourceRoot":"","sources":["../../src/utils/isJsFile.ts"],"names":[],"mappings":";;;AAAA,IAAM,YAAY,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;AAE1C;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,QAAqB;IAArB,yBAAA,EAAA,aAAqB;IAC5C,IAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC;IAC5C,OAAO,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACpC,CAAC;AAHD,4BAGC"}
@@ -0,0 +1,20 @@
/**
* Type of indentation to use
* @readonly
* @enum {string}
* @property {string} TABS - indicate to use tabs as separator
* @property {string} SPACES - indicate to use spaces as separator
*/
export declare enum IndentationTypes {
TABS = "tabs",
SPACES = "spaces"
}
/**
* Ensures indentations are prepended to content.
* @private
* @param {string} content to prepend the indentation
* @param {number} size the number of indendations to use
* @param {IndentationTypes} type the type of indendations to use. SPACES by default.
* @returns {string}
*/
export declare function withIndendation(content: string | undefined, size: number, type?: IndentationTypes): string;
@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.withIndendation = exports.IndentationTypes = void 0;
/**
* Type of indentation to use
* @readonly
* @enum {string}
* @property {string} TABS - indicate to use tabs as separator
* @property {string} SPACES - indicate to use spaces as separator
*/
var IndentationTypes;
(function (IndentationTypes) {
IndentationTypes["TABS"] = "tabs";
IndentationTypes["SPACES"] = "spaces";
})(IndentationTypes = exports.IndentationTypes || (exports.IndentationTypes = {}));
/**
* Ensures indentations are prepended to content.
* @private
* @param {string} content to prepend the indentation
* @param {number} size the number of indendations to use
* @param {IndentationTypes} type the type of indendations to use. SPACES by default.
* @returns {string}
*/
function withIndendation(content, size, type) {
if (content === void 0) { content = ''; }
if (type === void 0) { type = IndentationTypes.SPACES; }
if (size < 1) {
return content;
}
// if the content includes new lines ensure that they have the added indentation as well.
if (content.includes('\n')) {
var newLineArray = content.split('\n');
return newLineArray.reduce(function (accumulator, value) {
var newValue = value.trim() === '' ? value : "" + getIndentation(size, type) + value;
return accumulator === "" ? newValue : accumulator + "\n" + newValue;
}, "");
}
return "" + getIndentation(size, type) + content;
}
exports.withIndendation = withIndendation;
/**
* Get the indendation string based on how many and which type of indentation are requested.
* @private
* @param {number} size the number of indendations to use
* @param {IndentationTypes} type the type of indendations to use. SPACES by default.
* @returns {string}
*/
function getIndentation(size, type) {
if (size === void 0) { size = 0; }
if (type === void 0) { type = IndentationTypes.SPACES; }
var whitespaceChar = type === IndentationTypes.SPACES ? ' ' : '\t';
return Array(size).fill(whitespaceChar).join("");
}
//# sourceMappingURL=withIndendation.js.map
@@ -0,0 +1 @@
{"version":3,"file":"withIndendation.js","sourceRoot":"","sources":["../../src/utils/withIndendation.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1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I,CAAC,EAAE,CAAC,CAAC;AACnD,CAAC"}
@@ -0,0 +1,8 @@
/**
* Prepend given number of the new lines to content.
* @private
* @param {string} content
* @param {number} number
* @returns {string}
*/
export declare function withNewLines(content?: string, number?: number): string;
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.withNewLines = void 0;
/**
* Prepend given number of the new lines to content.
* @private
* @param {string} content
* @param {number} number
* @returns {string}
*/
function withNewLines(content, number) {
if (content === void 0) { content = ''; }
if (number === void 0) { number = 0; }
var newLines = Array(number).fill('\n').join('');
return content + newLines;
}
exports.withNewLines = withNewLines;
//# sourceMappingURL=withNewLines.js.map
@@ -0,0 +1 @@
{"version":3,"file":"withNewLines.js","sourceRoot":"","sources":["../../src/utils/withNewLines.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,SAAgB,YAAY,CAAC,OAAoB,EAAE,MAAkB;IAAxC,wBAAA,EAAA,YAAoB;IAAE,uBAAA,EAAA,UAAkB;IACnE,IAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACnD,OAAO,OAAO,GAAG,QAAQ,CAAC;AAC5B,CAAC;AAHD,oCAGC"}
@@ -0,0 +1 @@
../semver/bin/semver
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,19 @@
# @babel/core
> Babel compiler core.
See our website [@babel/core](https://babeljs.io/docs/en/babel-core) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen) associated with this package.
## Install
Using npm:
```sh
npm install --save-dev @babel/core
```
or using yarn:
```sh
yarn add @babel/core --dev
```
@@ -0,0 +1,327 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.makeWeakCache = makeWeakCache;
exports.makeWeakCacheSync = makeWeakCacheSync;
exports.makeStrongCache = makeStrongCache;
exports.makeStrongCacheSync = makeStrongCacheSync;
exports.assertSimpleType = assertSimpleType;
function _gensync() {
const data = _interopRequireDefault(require("gensync"));
_gensync = function () {
return data;
};
return data;
}
var _async = require("../gensync-utils/async");
var _util = require("./util");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const synchronize = gen => {
return (0, _gensync().default)(gen).sync;
};
function* genTrue(data) {
return true;
}
function makeWeakCache(handler) {
return makeCachedFunction(WeakMap, handler);
}
function makeWeakCacheSync(handler) {
return synchronize(makeWeakCache(handler));
}
function makeStrongCache(handler) {
return makeCachedFunction(Map, handler);
}
function makeStrongCacheSync(handler) {
return synchronize(makeStrongCache(handler));
}
function makeCachedFunction(CallCache, handler) {
const callCacheSync = new CallCache();
const callCacheAsync = new CallCache();
const futureCache = new CallCache();
return function* cachedFunction(arg, data) {
const asyncContext = yield* (0, _async.isAsync)();
const callCache = asyncContext ? callCacheAsync : callCacheSync;
const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data);
if (cached.valid) return cached.value;
const cache = new CacheConfigurator(data);
const handlerResult = handler(arg, cache);
let finishLock;
let value;
if ((0, _util.isIterableIterator)(handlerResult)) {
const gen = handlerResult;
value = yield* (0, _async.onFirstPause)(gen, () => {
finishLock = setupAsyncLocks(cache, futureCache, arg);
});
} else {
value = handlerResult;
}
updateFunctionCache(callCache, cache, arg, value);
if (finishLock) {
futureCache.delete(arg);
finishLock.release(value);
}
return value;
};
}
function* getCachedValue(cache, arg, data) {
const cachedValue = cache.get(arg);
if (cachedValue) {
for (const {
value,
valid
} of cachedValue) {
if (yield* valid(data)) return {
valid: true,
value
};
}
}
return {
valid: false,
value: null
};
}
function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) {
const cached = yield* getCachedValue(callCache, arg, data);
if (cached.valid) {
return cached;
}
if (asyncContext) {
const cached = yield* getCachedValue(futureCache, arg, data);
if (cached.valid) {
const value = yield* (0, _async.waitFor)(cached.value.promise);
return {
valid: true,
value
};
}
}
return {
valid: false,
value: null
};
}
function setupAsyncLocks(config, futureCache, arg) {
const finishLock = new Lock();
updateFunctionCache(futureCache, config, arg, finishLock);
return finishLock;
}
function updateFunctionCache(cache, config, arg, value) {
if (!config.configured()) config.forever();
let cachedValue = cache.get(arg);
config.deactivate();
switch (config.mode()) {
case "forever":
cachedValue = [{
value,
valid: genTrue
}];
cache.set(arg, cachedValue);
break;
case "invalidate":
cachedValue = [{
value,
valid: config.validator()
}];
cache.set(arg, cachedValue);
break;
case "valid":
if (cachedValue) {
cachedValue.push({
value,
valid: config.validator()
});
} else {
cachedValue = [{
value,
valid: config.validator()
}];
cache.set(arg, cachedValue);
}
}
}
class CacheConfigurator {
constructor(data) {
this._active = true;
this._never = false;
this._forever = false;
this._invalidate = false;
this._configured = false;
this._pairs = [];
this._data = void 0;
this._data = data;
}
simple() {
return makeSimpleConfigurator(this);
}
mode() {
if (this._never) return "never";
if (this._forever) return "forever";
if (this._invalidate) return "invalidate";
return "valid";
}
forever() {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._never) {
throw new Error("Caching has already been configured with .never()");
}
this._forever = true;
this._configured = true;
}
never() {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._forever) {
throw new Error("Caching has already been configured with .forever()");
}
this._never = true;
this._configured = true;
}
using(handler) {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._never || this._forever) {
throw new Error("Caching has already been configured with .never or .forever()");
}
this._configured = true;
const key = handler(this._data);
const fn = (0, _async.maybeAsync)(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`);
if ((0, _async.isThenable)(key)) {
return key.then(key => {
this._pairs.push([key, fn]);
return key;
});
}
this._pairs.push([key, fn]);
return key;
}
invalidate(handler) {
this._invalidate = true;
return this.using(handler);
}
validator() {
const pairs = this._pairs;
return function* (data) {
for (const [key, fn] of pairs) {
if (key !== (yield* fn(data))) return false;
}
return true;
};
}
deactivate() {
this._active = false;
}
configured() {
return this._configured;
}
}
function makeSimpleConfigurator(cache) {
function cacheFn(val) {
if (typeof val === "boolean") {
if (val) cache.forever();else cache.never();
return;
}
return cache.using(() => assertSimpleType(val()));
}
cacheFn.forever = () => cache.forever();
cacheFn.never = () => cache.never();
cacheFn.using = cb => cache.using(() => assertSimpleType(cb()));
cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb()));
return cacheFn;
}
function assertSimpleType(value) {
if ((0, _async.isThenable)(value)) {
throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`);
}
if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") {
throw new Error("Cache keys must be either string, boolean, number, null, or undefined.");
}
return value;
}
class Lock {
constructor() {
this.released = false;
this.promise = void 0;
this._resolve = void 0;
this.promise = new Promise(resolve => {
this._resolve = resolve;
});
}
release(value) {
this.released = true;
this._resolve(value);
}
}
@@ -0,0 +1,552 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildPresetChain = buildPresetChain;
exports.buildRootChain = buildRootChain;
exports.buildPresetChainWalker = void 0;
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _debug() {
const data = _interopRequireDefault(require("debug"));
_debug = function () {
return data;
};
return data;
}
var _options = require("./validation/options");
var _patternToRegex = _interopRequireDefault(require("./pattern-to-regex"));
var _printer = require("./printer");
var _files = require("./files");
var _caching = require("./caching");
var _configDescriptors = require("./config-descriptors");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const debug = (0, _debug().default)("babel:config:config-chain");
function* buildPresetChain(arg, context) {
const chain = yield* buildPresetChainWalker(arg, context);
if (!chain) return null;
return {
plugins: dedupDescriptors(chain.plugins),
presets: dedupDescriptors(chain.presets),
options: chain.options.map(o => normalizeOptions(o)),
files: new Set()
};
}
const buildPresetChainWalker = makeChainWalker({
root: preset => loadPresetDescriptors(preset),
env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName),
overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index),
overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName),
createLogger: () => () => {}
});
exports.buildPresetChainWalker = buildPresetChainWalker;
const loadPresetDescriptors = (0, _caching.makeWeakCacheSync)(preset => buildRootDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors));
const loadPresetEnvDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(envName => buildEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, envName)));
const loadPresetOverridesDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(index => buildOverrideDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index)));
const loadPresetOverridesEnvDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(index => (0, _caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index, envName))));
function* buildRootChain(opts, context) {
let configReport, babelRcReport;
const programmaticLogger = new _printer.ConfigPrinter();
const programmaticChain = yield* loadProgrammaticChain({
options: opts,
dirname: context.cwd
}, context, undefined, programmaticLogger);
if (!programmaticChain) return null;
const programmaticReport = programmaticLogger.output();
let configFile;
if (typeof opts.configFile === "string") {
configFile = yield* (0, _files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller);
} else if (opts.configFile !== false) {
configFile = yield* (0, _files.findRootConfig)(context.root, context.envName, context.caller);
}
let {
babelrc,
babelrcRoots
} = opts;
let babelrcRootsDirectory = context.cwd;
const configFileChain = emptyChain();
const configFileLogger = new _printer.ConfigPrinter();
if (configFile) {
const validatedFile = validateConfigFile(configFile);
const result = yield* loadFileChain(validatedFile, context, undefined, configFileLogger);
if (!result) return null;
configReport = configFileLogger.output();
if (babelrc === undefined) {
babelrc = validatedFile.options.babelrc;
}
if (babelrcRoots === undefined) {
babelrcRootsDirectory = validatedFile.dirname;
babelrcRoots = validatedFile.options.babelrcRoots;
}
mergeChain(configFileChain, result);
}
const pkgData = typeof context.filename === "string" ? yield* (0, _files.findPackageData)(context.filename) : null;
let ignoreFile, babelrcFile;
let isIgnored = false;
const fileChain = emptyChain();
if ((babelrc === true || babelrc === undefined) && pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) {
({
ignore: ignoreFile,
config: babelrcFile
} = yield* (0, _files.findRelativeConfig)(pkgData, context.envName, context.caller));
if (ignoreFile) {
fileChain.files.add(ignoreFile.filepath);
}
if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) {
isIgnored = true;
}
if (babelrcFile && !isIgnored) {
const validatedFile = validateBabelrcFile(babelrcFile);
const babelrcLogger = new _printer.ConfigPrinter();
const result = yield* loadFileChain(validatedFile, context, undefined, babelrcLogger);
if (!result) {
isIgnored = true;
} else {
babelRcReport = babelrcLogger.output();
mergeChain(fileChain, result);
}
}
if (babelrcFile && isIgnored) {
fileChain.files.add(babelrcFile.filepath);
}
}
if (context.showConfig) {
console.log(`Babel configs on "${context.filename}" (ascending priority):\n` + [configReport, babelRcReport, programmaticReport].filter(x => !!x).join("\n\n"));
return null;
}
const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain);
return {
plugins: isIgnored ? [] : dedupDescriptors(chain.plugins),
presets: isIgnored ? [] : dedupDescriptors(chain.presets),
options: isIgnored ? [] : chain.options.map(o => normalizeOptions(o)),
fileHandling: isIgnored ? "ignored" : "transpile",
ignore: ignoreFile || undefined,
babelrc: babelrcFile || undefined,
config: configFile || undefined,
files: chain.files
};
}
function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) {
if (typeof babelrcRoots === "boolean") return babelrcRoots;
const absoluteRoot = context.root;
if (babelrcRoots === undefined) {
return pkgData.directories.indexOf(absoluteRoot) !== -1;
}
let babelrcPatterns = babelrcRoots;
if (!Array.isArray(babelrcPatterns)) babelrcPatterns = [babelrcPatterns];
babelrcPatterns = babelrcPatterns.map(pat => {
return typeof pat === "string" ? _path().default.resolve(babelrcRootsDirectory, pat) : pat;
});
if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) {
return pkgData.directories.indexOf(absoluteRoot) !== -1;
}
return babelrcPatterns.some(pat => {
if (typeof pat === "string") {
pat = (0, _patternToRegex.default)(pat, babelrcRootsDirectory);
}
return pkgData.directories.some(directory => {
return matchPattern(pat, babelrcRootsDirectory, directory, context);
});
});
}
const validateConfigFile = (0, _caching.makeWeakCacheSync)(file => ({
filepath: file.filepath,
dirname: file.dirname,
options: (0, _options.validate)("configfile", file.options)
}));
const validateBabelrcFile = (0, _caching.makeWeakCacheSync)(file => ({
filepath: file.filepath,
dirname: file.dirname,
options: (0, _options.validate)("babelrcfile", file.options)
}));
const validateExtendFile = (0, _caching.makeWeakCacheSync)(file => ({
filepath: file.filepath,
dirname: file.dirname,
options: (0, _options.validate)("extendsfile", file.options)
}));
const loadProgrammaticChain = makeChainWalker({
root: input => buildRootDescriptors(input, "base", _configDescriptors.createCachedDescriptors),
env: (input, envName) => buildEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, envName),
overrides: (input, index) => buildOverrideDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index),
overridesEnv: (input, index, envName) => buildOverrideEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index, envName),
createLogger: (input, context, baseLogger) => buildProgrammaticLogger(input, context, baseLogger)
});
const loadFileChainWalker = makeChainWalker({
root: file => loadFileDescriptors(file),
env: (file, envName) => loadFileEnvDescriptors(file)(envName),
overrides: (file, index) => loadFileOverridesDescriptors(file)(index),
overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName),
createLogger: (file, context, baseLogger) => buildFileLogger(file.filepath, context, baseLogger)
});
function* loadFileChain(input, context, files, baseLogger) {
const chain = yield* loadFileChainWalker(input, context, files, baseLogger);
if (chain) {
chain.files.add(input.filepath);
}
return chain;
}
const loadFileDescriptors = (0, _caching.makeWeakCacheSync)(file => buildRootDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors));
const loadFileEnvDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(envName => buildEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, envName)));
const loadFileOverridesDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(index => buildOverrideDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index)));
const loadFileOverridesEnvDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(index => (0, _caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index, envName))));
function buildFileLogger(filepath, context, baseLogger) {
if (!baseLogger) {
return () => {};
}
return baseLogger.configure(context.showConfig, _printer.ChainFormatter.Config, {
filepath
});
}
function buildRootDescriptors({
dirname,
options
}, alias, descriptors) {
return descriptors(dirname, options, alias);
}
function buildProgrammaticLogger(_, context, baseLogger) {
var _context$caller;
if (!baseLogger) {
return () => {};
}
return baseLogger.configure(context.showConfig, _printer.ChainFormatter.Programmatic, {
callerName: (_context$caller = context.caller) == null ? void 0 : _context$caller.name
});
}
function buildEnvDescriptors({
dirname,
options
}, alias, descriptors, envName) {
const opts = options.env && options.env[envName];
return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null;
}
function buildOverrideDescriptors({
dirname,
options
}, alias, descriptors, index) {
const opts = options.overrides && options.overrides[index];
if (!opts) throw new Error("Assertion failure - missing override");
return descriptors(dirname, opts, `${alias}.overrides[${index}]`);
}
function buildOverrideEnvDescriptors({
dirname,
options
}, alias, descriptors, index, envName) {
const override = options.overrides && options.overrides[index];
if (!override) throw new Error("Assertion failure - missing override");
const opts = override.env && override.env[envName];
return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null;
}
function makeChainWalker({
root,
env,
overrides,
overridesEnv,
createLogger
}) {
return function* (input, context, files = new Set(), baseLogger) {
const {
dirname
} = input;
const flattenedConfigs = [];
const rootOpts = root(input);
if (configIsApplicable(rootOpts, dirname, context)) {
flattenedConfigs.push({
config: rootOpts,
envName: undefined,
index: undefined
});
const envOpts = env(input, context.envName);
if (envOpts && configIsApplicable(envOpts, dirname, context)) {
flattenedConfigs.push({
config: envOpts,
envName: context.envName,
index: undefined
});
}
(rootOpts.options.overrides || []).forEach((_, index) => {
const overrideOps = overrides(input, index);
if (configIsApplicable(overrideOps, dirname, context)) {
flattenedConfigs.push({
config: overrideOps,
index,
envName: undefined
});
const overrideEnvOpts = overridesEnv(input, index, context.envName);
if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) {
flattenedConfigs.push({
config: overrideEnvOpts,
index,
envName: context.envName
});
}
}
});
}
if (flattenedConfigs.some(({
config: {
options: {
ignore,
only
}
}
}) => shouldIgnore(context, ignore, only, dirname))) {
return null;
}
const chain = emptyChain();
const logger = createLogger(input, context, baseLogger);
for (const {
config,
index,
envName
} of flattenedConfigs) {
if (!(yield* mergeExtendsChain(chain, config.options, dirname, context, files, baseLogger))) {
return null;
}
logger(config, index, envName);
mergeChainOpts(chain, config);
}
return chain;
};
}
function* mergeExtendsChain(chain, opts, dirname, context, files, baseLogger) {
if (opts.extends === undefined) return true;
const file = yield* (0, _files.loadConfig)(opts.extends, dirname, context.envName, context.caller);
if (files.has(file)) {
throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files, file => ` - ${file.filepath}`).join("\n"));
}
files.add(file);
const fileChain = yield* loadFileChain(validateExtendFile(file), context, files, baseLogger);
files.delete(file);
if (!fileChain) return false;
mergeChain(chain, fileChain);
return true;
}
function mergeChain(target, source) {
target.options.push(...source.options);
target.plugins.push(...source.plugins);
target.presets.push(...source.presets);
for (const file of source.files) {
target.files.add(file);
}
return target;
}
function mergeChainOpts(target, {
options,
plugins,
presets
}) {
target.options.push(options);
target.plugins.push(...plugins());
target.presets.push(...presets());
return target;
}
function emptyChain() {
return {
options: [],
presets: [],
plugins: [],
files: new Set()
};
}
function normalizeOptions(opts) {
const options = Object.assign({}, opts);
delete options.extends;
delete options.env;
delete options.overrides;
delete options.plugins;
delete options.presets;
delete options.passPerPreset;
delete options.ignore;
delete options.only;
delete options.test;
delete options.include;
delete options.exclude;
if (Object.prototype.hasOwnProperty.call(options, "sourceMap")) {
options.sourceMaps = options.sourceMap;
delete options.sourceMap;
}
return options;
}
function dedupDescriptors(items) {
const map = new Map();
const descriptors = [];
for (const item of items) {
if (typeof item.value === "function") {
const fnKey = item.value;
let nameMap = map.get(fnKey);
if (!nameMap) {
nameMap = new Map();
map.set(fnKey, nameMap);
}
let desc = nameMap.get(item.name);
if (!desc) {
desc = {
value: item
};
descriptors.push(desc);
if (!item.ownPass) nameMap.set(item.name, desc);
} else {
desc.value = item;
}
} else {
descriptors.push({
value: item
});
}
}
return descriptors.reduce((acc, desc) => {
acc.push(desc.value);
return acc;
}, []);
}
function configIsApplicable({
options
}, dirname, context) {
return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname));
}
function configFieldIsApplicable(context, test, dirname) {
const patterns = Array.isArray(test) ? test : [test];
return matchesPatterns(context, patterns, dirname);
}
function shouldIgnore(context, ignore, only, dirname) {
if (ignore && matchesPatterns(context, ignore, dirname)) {
var _context$filename;
const message = `No config is applied to "${(_context$filename = context.filename) != null ? _context$filename : "(unknown)"}" because it matches one of \`ignore: ${JSON.stringify(ignore)}\` from "${dirname}"`;
debug(message);
if (context.showConfig) {
console.log(message);
}
return true;
}
if (only && !matchesPatterns(context, only, dirname)) {
var _context$filename2;
const message = `No config is applied to "${(_context$filename2 = context.filename) != null ? _context$filename2 : "(unknown)"}" because it fails to match one of \`only: ${JSON.stringify(only)}\` from "${dirname}"`;
debug(message);
if (context.showConfig) {
console.log(message);
}
return true;
}
return false;
}
function matchesPatterns(context, patterns, dirname) {
return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context));
}
function matchPattern(pattern, dirname, pathToTest, context) {
if (typeof pattern === "function") {
return !!pattern(pathToTest, {
dirname,
envName: context.envName,
caller: context.caller
});
}
if (typeof pathToTest !== "string") {
throw new Error(`Configuration contains string/RegExp pattern, but no filename was passed to Babel`);
}
if (typeof pattern === "string") {
pattern = (0, _patternToRegex.default)(pattern, dirname);
}
return pattern.test(pathToTest);
}
@@ -0,0 +1,211 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createCachedDescriptors = createCachedDescriptors;
exports.createUncachedDescriptors = createUncachedDescriptors;
exports.createDescriptor = createDescriptor;
var _files = require("./files");
var _item = require("./item");
var _caching = require("./caching");
function isEqualDescriptor(a, b) {
return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && (a.file && a.file.request) === (b.file && b.file.request) && (a.file && a.file.resolved) === (b.file && b.file.resolved);
}
function createCachedDescriptors(dirname, options, alias) {
const {
plugins,
presets,
passPerPreset
} = options;
return {
options,
plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => [],
presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => []
};
}
function createUncachedDescriptors(dirname, options, alias) {
let plugins;
let presets;
return {
options,
plugins: () => {
if (!plugins) {
plugins = createPluginDescriptors(options.plugins || [], dirname, alias);
}
return plugins;
},
presets: () => {
if (!presets) {
presets = createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset);
}
return presets;
}
};
}
const PRESET_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPresetDescriptors = (0, _caching.makeWeakCacheSync)((items, cache) => {
const dirname = cache.using(dir => dir);
return (0, _caching.makeStrongCacheSync)(alias => (0, _caching.makeStrongCacheSync)(passPerPreset => createPresetDescriptors(items, dirname, alias, passPerPreset).map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc))));
});
const PLUGIN_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPluginDescriptors = (0, _caching.makeWeakCacheSync)((items, cache) => {
const dirname = cache.using(dir => dir);
return (0, _caching.makeStrongCacheSync)(alias => createPluginDescriptors(items, dirname, alias).map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc)));
});
const DEFAULT_OPTIONS = {};
function loadCachedDescriptor(cache, desc) {
const {
value,
options = DEFAULT_OPTIONS
} = desc;
if (options === false) return desc;
let cacheByOptions = cache.get(value);
if (!cacheByOptions) {
cacheByOptions = new WeakMap();
cache.set(value, cacheByOptions);
}
let possibilities = cacheByOptions.get(options);
if (!possibilities) {
possibilities = [];
cacheByOptions.set(options, possibilities);
}
if (possibilities.indexOf(desc) === -1) {
const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc));
if (matches.length > 0) {
return matches[0];
}
possibilities.push(desc);
}
return desc;
}
function createPresetDescriptors(items, dirname, alias, passPerPreset) {
return createDescriptors("preset", items, dirname, alias, passPerPreset);
}
function createPluginDescriptors(items, dirname, alias) {
return createDescriptors("plugin", items, dirname, alias);
}
function createDescriptors(type, items, dirname, alias, ownPass) {
const descriptors = items.map((item, index) => createDescriptor(item, dirname, {
type,
alias: `${alias}$${index}`,
ownPass: !!ownPass
}));
assertNoDuplicates(descriptors);
return descriptors;
}
function createDescriptor(pair, dirname, {
type,
alias,
ownPass
}) {
const desc = (0, _item.getItemDescriptor)(pair);
if (desc) {
return desc;
}
let name;
let options;
let value = pair;
if (Array.isArray(value)) {
if (value.length === 3) {
[value, options, name] = value;
} else {
[value, options] = value;
}
}
let file = undefined;
let filepath = null;
if (typeof value === "string") {
if (typeof type !== "string") {
throw new Error("To resolve a string-based item, the type of item must be given");
}
const resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset;
const request = value;
({
filepath,
value
} = resolver(value, dirname));
file = {
request,
resolved: filepath
};
}
if (!value) {
throw new Error(`Unexpected falsy value: ${String(value)}`);
}
if (typeof value === "object" && value.__esModule) {
if (value.default) {
value = value.default;
} else {
throw new Error("Must export a default export when using ES6 modules.");
}
}
if (typeof value !== "object" && typeof value !== "function") {
throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`);
}
if (filepath !== null && typeof value === "object" && value) {
throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`);
}
return {
name,
alias: filepath || alias,
value,
options,
dirname,
ownPass,
file
};
}
function assertNoDuplicates(items) {
const map = new Map();
for (const item of items) {
if (typeof item.value !== "function") continue;
let nameMap = map.get(item.value);
if (!nameMap) {
nameMap = new Set();
map.set(item.value, nameMap);
}
if (nameMap.has(item.name)) {
const conflicts = items.filter(i => i.value === item.value);
throw new Error([`Duplicate plugin/preset detected.`, `If you'd like to use two separate instances of a plugin,`, `they need separate names, e.g.`, ``, ` plugins: [`, ` ['some-plugin', {}],`, ` ['some-plugin', {}, 'some unique name'],`, ` ]`, ``, `Duplicates detected are:`, `${JSON.stringify(conflicts, null, 2)}`].join("\n"));
}
nameMap.add(item.name);
}
}
@@ -0,0 +1,335 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findConfigUpwards = findConfigUpwards;
exports.findRelativeConfig = findRelativeConfig;
exports.findRootConfig = findRootConfig;
exports.loadConfig = loadConfig;
exports.resolveShowConfigPath = resolveShowConfigPath;
exports.ROOT_CONFIG_FILENAMES = void 0;
function _debug() {
const data = _interopRequireDefault(require("debug"));
_debug = function () {
return data;
};
return data;
}
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _json() {
const data = _interopRequireDefault(require("json5"));
_json = function () {
return data;
};
return data;
}
function _gensync() {
const data = _interopRequireDefault(require("gensync"));
_gensync = function () {
return data;
};
return data;
}
var _caching = require("../caching");
var _configApi = _interopRequireDefault(require("../helpers/config-api"));
var _utils = require("./utils");
var _moduleTypes = _interopRequireDefault(require("./module-types"));
var _patternToRegex = _interopRequireDefault(require("../pattern-to-regex"));
var fs = _interopRequireWildcard(require("../../gensync-utils/fs"));
var _resolve = _interopRequireDefault(require("../../gensync-utils/resolve"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const debug = (0, _debug().default)("babel:config:loading:files:configuration");
const ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json"];
exports.ROOT_CONFIG_FILENAMES = ROOT_CONFIG_FILENAMES;
const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json"];
const BABELIGNORE_FILENAME = ".babelignore";
function* findConfigUpwards(rootDir) {
let dirname = rootDir;
while (true) {
for (const filename of ROOT_CONFIG_FILENAMES) {
if (yield* fs.exists(_path().default.join(dirname, filename))) {
return dirname;
}
}
const nextDir = _path().default.dirname(dirname);
if (dirname === nextDir) break;
dirname = nextDir;
}
return null;
}
function* findRelativeConfig(packageData, envName, caller) {
let config = null;
let ignore = null;
const dirname = _path().default.dirname(packageData.filepath);
for (const loc of packageData.directories) {
if (!config) {
var _packageData$pkg;
config = yield* loadOneConfig(RELATIVE_CONFIG_FILENAMES, loc, envName, caller, ((_packageData$pkg = packageData.pkg) == null ? void 0 : _packageData$pkg.dirname) === loc ? packageToBabelConfig(packageData.pkg) : null);
}
if (!ignore) {
const ignoreLoc = _path().default.join(loc, BABELIGNORE_FILENAME);
ignore = yield* readIgnoreConfig(ignoreLoc);
if (ignore) {
debug("Found ignore %o from %o.", ignore.filepath, dirname);
}
}
}
return {
config,
ignore
};
}
function findRootConfig(dirname, envName, caller) {
return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller);
}
function* loadOneConfig(names, dirname, envName, caller, previousConfig = null) {
const configs = yield* _gensync().default.all(names.map(filename => readConfig(_path().default.join(dirname, filename), envName, caller)));
const config = configs.reduce((previousConfig, config) => {
if (config && previousConfig) {
throw new Error(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().default.basename(previousConfig.filepath)}\n` + ` - ${config.filepath}\n` + `from ${dirname}`);
}
return config || previousConfig;
}, previousConfig);
if (config) {
debug("Found configuration %o from %o.", config.filepath, dirname);
}
return config;
}
function* loadConfig(name, dirname, envName, caller) {
const filepath = yield* (0, _resolve.default)(name, {
basedir: dirname
});
const conf = yield* readConfig(filepath, envName, caller);
if (!conf) {
throw new Error(`Config file ${filepath} contains no configuration data`);
}
debug("Loaded config %o from %o.", name, dirname);
return conf;
}
function readConfig(filepath, envName, caller) {
const ext = _path().default.extname(filepath);
return ext === ".js" || ext === ".cjs" || ext === ".mjs" ? readConfigJS(filepath, {
envName,
caller
}) : readConfigJSON5(filepath);
}
const LOADING_CONFIGS = new Set();
const readConfigJS = (0, _caching.makeStrongCache)(function* readConfigJS(filepath, cache) {
if (!fs.exists.sync(filepath)) {
cache.forever();
return null;
}
if (LOADING_CONFIGS.has(filepath)) {
cache.never();
debug("Auto-ignoring usage of config %o.", filepath);
return {
filepath,
dirname: _path().default.dirname(filepath),
options: {}
};
}
let options;
try {
LOADING_CONFIGS.add(filepath);
options = yield* (0, _moduleTypes.default)(filepath, "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously.");
} catch (err) {
err.message = `${filepath}: Error while loading config - ${err.message}`;
throw err;
} finally {
LOADING_CONFIGS.delete(filepath);
}
let assertCache = false;
if (typeof options === "function") {
yield* [];
options = options((0, _configApi.default)(cache));
assertCache = true;
}
if (!options || typeof options !== "object" || Array.isArray(options)) {
throw new Error(`${filepath}: Configuration should be an exported JavaScript object.`);
}
if (typeof options.then === "function") {
throw new Error(`You appear to be using an async configuration, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously return your config.`);
}
if (assertCache && !cache.configured()) throwConfigError();
return {
filepath,
dirname: _path().default.dirname(filepath),
options
};
});
const packageToBabelConfig = (0, _caching.makeWeakCacheSync)(file => {
const babel = file.options["babel"];
if (typeof babel === "undefined") return null;
if (typeof babel !== "object" || Array.isArray(babel) || babel === null) {
throw new Error(`${file.filepath}: .babel property must be an object`);
}
return {
filepath: file.filepath,
dirname: file.dirname,
options: babel
};
});
const readConfigJSON5 = (0, _utils.makeStaticFileCache)((filepath, content) => {
let options;
try {
options = _json().default.parse(content);
} catch (err) {
err.message = `${filepath}: Error while parsing config - ${err.message}`;
throw err;
}
if (!options) throw new Error(`${filepath}: No config detected`);
if (typeof options !== "object") {
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
}
if (Array.isArray(options)) {
throw new Error(`${filepath}: Expected config object but found array`);
}
return {
filepath,
dirname: _path().default.dirname(filepath),
options
};
});
const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => {
const ignoreDir = _path().default.dirname(filepath);
const ignorePatterns = content.split("\n").map(line => line.replace(/#(.*?)$/, "").trim()).filter(line => !!line);
for (const pattern of ignorePatterns) {
if (pattern[0] === "!") {
throw new Error(`Negation of file paths is not supported.`);
}
}
return {
filepath,
dirname: _path().default.dirname(filepath),
ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir))
};
});
function* resolveShowConfigPath(dirname) {
const targetPath = process.env.BABEL_SHOW_CONFIG_FOR;
if (targetPath != null) {
const absolutePath = _path().default.resolve(dirname, targetPath);
const stats = yield* fs.stat(absolutePath);
if (!stats.isFile()) {
throw new Error(`${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`);
}
return absolutePath;
}
return null;
}
function throwConfigError() {
throw new Error(`\
Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured
for various types of caching, using the first param of their handler functions:
module.exports = function(api) {
// The API exposes the following:
// Cache the returned value forever and don't call this function again.
api.cache(true);
// Don't cache at all. Not recommended because it will be very slow.
api.cache(false);
// Cached based on the value of some function. If this function returns a value different from
// a previously-encountered value, the plugins will re-evaluate.
var env = api.cache(() => process.env.NODE_ENV);
// If testing for a specific env, we recommend specifics to avoid instantiating a plugin for
// any possible NODE_ENV value that might come up during plugin execution.
var isProd = api.cache(() => process.env.NODE_ENV === "production");
// .cache(fn) will perform a linear search though instances to find the matching plugin based
// based on previous instantiated plugins. If you want to recreate the plugin and discard the
// previous instance whenever something changes, you may use:
var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production");
// Note, we also expose the following more-verbose versions of the above examples:
api.cache.forever(); // api.cache(true)
api.cache.never(); // api.cache(false)
api.cache.using(fn); // api.cache(fn)
// Return the value that will be cached.
return { };
};`);
}
@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = import_;
function import_(filepath) {
return import(filepath);
}
@@ -0,0 +1,68 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findConfigUpwards = findConfigUpwards;
exports.findPackageData = findPackageData;
exports.findRelativeConfig = findRelativeConfig;
exports.findRootConfig = findRootConfig;
exports.loadConfig = loadConfig;
exports.resolveShowConfigPath = resolveShowConfigPath;
exports.resolvePlugin = resolvePlugin;
exports.resolvePreset = resolvePreset;
exports.loadPlugin = loadPlugin;
exports.loadPreset = loadPreset;
exports.ROOT_CONFIG_FILENAMES = void 0;
function* findConfigUpwards(rootDir) {
return null;
}
function* findPackageData(filepath) {
return {
filepath,
directories: [],
pkg: null,
isPackage: false
};
}
function* findRelativeConfig(pkgData, envName, caller) {
return {
pkg: null,
config: null,
ignore: null
};
}
function* findRootConfig(dirname, envName, caller) {
return null;
}
function* loadConfig(name, dirname, envName, caller) {
throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);
}
function* resolveShowConfigPath(dirname) {
return null;
}
const ROOT_CONFIG_FILENAMES = [];
exports.ROOT_CONFIG_FILENAMES = ROOT_CONFIG_FILENAMES;
function resolvePlugin(name, dirname) {
return null;
}
function resolvePreset(name, dirname) {
return null;
}
function loadPlugin(name, dirname) {
throw new Error(`Cannot load plugin ${name} relative to ${dirname} in a browser`);
}
function loadPreset(name, dirname) {
throw new Error(`Cannot load preset ${name} relative to ${dirname} in a browser`);
}
@@ -0,0 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "findPackageData", {
enumerable: true,
get: function () {
return _package.findPackageData;
}
});
Object.defineProperty(exports, "findConfigUpwards", {
enumerable: true,
get: function () {
return _configuration.findConfigUpwards;
}
});
Object.defineProperty(exports, "findRelativeConfig", {
enumerable: true,
get: function () {
return _configuration.findRelativeConfig;
}
});
Object.defineProperty(exports, "findRootConfig", {
enumerable: true,
get: function () {
return _configuration.findRootConfig;
}
});
Object.defineProperty(exports, "loadConfig", {
enumerable: true,
get: function () {
return _configuration.loadConfig;
}
});
Object.defineProperty(exports, "resolveShowConfigPath", {
enumerable: true,
get: function () {
return _configuration.resolveShowConfigPath;
}
});
Object.defineProperty(exports, "ROOT_CONFIG_FILENAMES", {
enumerable: true,
get: function () {
return _configuration.ROOT_CONFIG_FILENAMES;
}
});
Object.defineProperty(exports, "resolvePlugin", {
enumerable: true,
get: function () {
return _plugins.resolvePlugin;
}
});
Object.defineProperty(exports, "resolvePreset", {
enumerable: true,
get: function () {
return _plugins.resolvePreset;
}
});
Object.defineProperty(exports, "loadPlugin", {
enumerable: true,
get: function () {
return _plugins.loadPlugin;
}
});
Object.defineProperty(exports, "loadPreset", {
enumerable: true,
get: function () {
return _plugins.loadPreset;
}
});
var _package = require("./package");
var _configuration = require("./configuration");
var _plugins = require("./plugins");
({});
@@ -0,0 +1,96 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loadCjsOrMjsDefault;
var _async = require("../../gensync-utils/async");
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _url() {
const data = require("url");
_url = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
let import_;
try {
import_ = require("./import").default;
} catch (_unused) {}
function* loadCjsOrMjsDefault(filepath, asyncError) {
switch (guessJSModuleType(filepath)) {
case "cjs":
return loadCjsDefault(filepath);
case "unknown":
try {
return loadCjsDefault(filepath);
} catch (e) {
if (e.code !== "ERR_REQUIRE_ESM") throw e;
}
case "mjs":
if (yield* (0, _async.isAsync)()) {
return yield* (0, _async.waitFor)(loadMjsDefault(filepath));
}
throw new Error(asyncError);
}
}
function guessJSModuleType(filename) {
switch (_path().default.extname(filename)) {
case ".cjs":
return "cjs";
case ".mjs":
return "mjs";
default:
return "unknown";
}
}
function loadCjsDefault(filepath) {
const module = require(filepath);
return (module == null ? void 0 : module.__esModule) ? module.default || undefined : module;
}
function loadMjsDefault(_x) {
return _loadMjsDefault.apply(this, arguments);
}
function _loadMjsDefault() {
_loadMjsDefault = _asyncToGenerator(function* (filepath) {
if (!import_) {
throw new Error("Internal error: Native ECMAScript modules aren't supported" + " by this platform.\n");
}
const module = yield import_((0, _url().pathToFileURL)(filepath));
return module.default;
});
return _loadMjsDefault.apply(this, arguments);
}
@@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findPackageData = findPackageData;
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const PACKAGE_FILENAME = "package.json";
function* findPackageData(filepath) {
let pkg = null;
const directories = [];
let isPackage = true;
let dirname = _path().default.dirname(filepath);
while (!pkg && _path().default.basename(dirname) !== "node_modules") {
directories.push(dirname);
pkg = yield* readConfigPackage(_path().default.join(dirname, PACKAGE_FILENAME));
const nextLoc = _path().default.dirname(dirname);
if (dirname === nextLoc) {
isPackage = false;
break;
}
dirname = nextLoc;
}
return {
filepath,
directories,
pkg,
isPackage
};
}
const readConfigPackage = (0, _utils.makeStaticFileCache)((filepath, content) => {
let options;
try {
options = JSON.parse(content);
} catch (err) {
err.message = `${filepath}: Error while parsing JSON - ${err.message}`;
throw err;
}
if (!options) throw new Error(`${filepath}: No config detected`);
if (typeof options !== "object") {
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
}
if (Array.isArray(options)) {
throw new Error(`${filepath}: Expected config object but found array`);
}
return {
filepath,
dirname: _path().default.dirname(filepath),
options
};
});
@@ -0,0 +1,169 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.resolvePlugin = resolvePlugin;
exports.resolvePreset = resolvePreset;
exports.loadPlugin = loadPlugin;
exports.loadPreset = loadPreset;
function _debug() {
const data = _interopRequireDefault(require("debug"));
_debug = function () {
return data;
};
return data;
}
function _resolve() {
const data = _interopRequireDefault(require("resolve"));
_resolve = function () {
return data;
};
return data;
}
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const debug = (0, _debug().default)("babel:config:loading:files:plugins");
const EXACT_RE = /^module:/;
const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/;
const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/;
const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
function resolvePlugin(name, dirname) {
return resolveStandardizedName("plugin", name, dirname);
}
function resolvePreset(name, dirname) {
return resolveStandardizedName("preset", name, dirname);
}
function loadPlugin(name, dirname) {
const filepath = resolvePlugin(name, dirname);
if (!filepath) {
throw new Error(`Plugin ${name} not found relative to ${dirname}`);
}
const value = requireModule("plugin", filepath);
debug("Loaded plugin %o from %o.", name, dirname);
return {
filepath,
value
};
}
function loadPreset(name, dirname) {
const filepath = resolvePreset(name, dirname);
if (!filepath) {
throw new Error(`Preset ${name} not found relative to ${dirname}`);
}
const value = requireModule("preset", filepath);
debug("Loaded preset %o from %o.", name, dirname);
return {
filepath,
value
};
}
function standardizeName(type, name) {
if (_path().default.isAbsolute(name)) return name;
const isPreset = type === "preset";
return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, "");
}
function resolveStandardizedName(type, name, dirname = process.cwd()) {
const standardizedName = standardizeName(type, name);
try {
return _resolve().default.sync(standardizedName, {
basedir: dirname
});
} catch (e) {
if (e.code !== "MODULE_NOT_FOUND") throw e;
if (standardizedName !== name) {
let resolvedOriginal = false;
try {
_resolve().default.sync(name, {
basedir: dirname
});
resolvedOriginal = true;
} catch (_unused) {}
if (resolvedOriginal) {
e.message += `\n- If you want to resolve "${name}", use "module:${name}"`;
}
}
let resolvedBabel = false;
try {
_resolve().default.sync(standardizeName(type, "@babel/" + name), {
basedir: dirname
});
resolvedBabel = true;
} catch (_unused2) {}
if (resolvedBabel) {
e.message += `\n- Did you mean "@babel/${name}"?`;
}
let resolvedOppositeType = false;
const oppositeType = type === "preset" ? "plugin" : "preset";
try {
_resolve().default.sync(standardizeName(oppositeType, name), {
basedir: dirname
});
resolvedOppositeType = true;
} catch (_unused3) {}
if (resolvedOppositeType) {
e.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`;
}
throw e;
}
}
const LOADING_MODULES = new Set();
function requireModule(type, name) {
if (LOADING_MODULES.has(name)) {
throw new Error(`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.');
}
try {
LOADING_MODULES.add(name);
return require(name);
} finally {
LOADING_MODULES.delete(name);
}
}
@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.makeStaticFileCache = makeStaticFileCache;
var _caching = require("../caching");
var fs = _interopRequireWildcard(require("../../gensync-utils/fs"));
function _fs2() {
const data = _interopRequireDefault(require("fs"));
_fs2 = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function makeStaticFileCache(fn) {
return (0, _caching.makeStrongCache)(function* (filepath, cache) {
const cached = cache.invalidate(() => fileMtime(filepath));
if (cached === null) {
return null;
}
return fn(filepath, yield* fs.readFile(filepath, "utf8"));
});
}
function fileMtime(filepath) {
try {
return +_fs2().default.statSync(filepath).mtime;
} catch (e) {
if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e;
}
return null;
}
@@ -0,0 +1,329 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _gensync() {
const data = _interopRequireDefault(require("gensync"));
_gensync = function () {
return data;
};
return data;
}
var _async = require("../gensync-utils/async");
var _util = require("./util");
var context = _interopRequireWildcard(require("../index"));
var _plugin = _interopRequireDefault(require("./plugin"));
var _item = require("./item");
var _configChain = require("./config-chain");
function _traverse() {
const data = _interopRequireDefault(require("@babel/traverse"));
_traverse = function () {
return data;
};
return data;
}
var _caching = require("./caching");
var _options = require("./validation/options");
var _plugins = require("./validation/plugins");
var _configApi = _interopRequireDefault(require("./helpers/config-api"));
var _partial = _interopRequireDefault(require("./partial"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = (0, _gensync().default)(function* loadFullConfig(inputOpts) {
const result = yield* (0, _partial.default)(inputOpts);
if (!result) {
return null;
}
const {
options,
context,
fileHandling
} = result;
if (fileHandling === "ignored") {
return null;
}
const optionDefaults = {};
const {
plugins,
presets
} = options;
if (!plugins || !presets) {
throw new Error("Assertion failure - plugins and presets exist");
}
const toDescriptor = item => {
const desc = (0, _item.getItemDescriptor)(item);
if (!desc) {
throw new Error("Assertion failure - must be config item");
}
return desc;
};
const presetsDescriptors = presets.map(toDescriptor);
const initialPluginsDescriptors = plugins.map(toDescriptor);
const pluginDescriptorsByPass = [[]];
const passes = [];
const ignored = yield* enhanceError(context, function* recursePresetDescriptors(rawPresets, pluginDescriptorsPass) {
const presets = [];
for (let i = 0; i < rawPresets.length; i++) {
const descriptor = rawPresets[i];
if (descriptor.options !== false) {
try {
if (descriptor.ownPass) {
presets.push({
preset: yield* loadPresetDescriptor(descriptor, context),
pass: []
});
} else {
presets.unshift({
preset: yield* loadPresetDescriptor(descriptor, context),
pass: pluginDescriptorsPass
});
}
} catch (e) {
if (e.code === "BABEL_UNKNOWN_OPTION") {
(0, _options.checkNoUnwrappedItemOptionPairs)(rawPresets, i, "preset", e);
}
throw e;
}
}
}
if (presets.length > 0) {
pluginDescriptorsByPass.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass));
for (const {
preset,
pass
} of presets) {
if (!preset) return true;
pass.push(...preset.plugins);
const ignored = yield* recursePresetDescriptors(preset.presets, pass);
if (ignored) return true;
preset.options.forEach(opts => {
(0, _util.mergeOptions)(optionDefaults, opts);
});
}
}
})(presetsDescriptors, pluginDescriptorsByPass[0]);
if (ignored) return null;
const opts = optionDefaults;
(0, _util.mergeOptions)(opts, options);
yield* enhanceError(context, function* loadPluginDescriptors() {
pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors);
for (const descs of pluginDescriptorsByPass) {
const pass = [];
passes.push(pass);
for (let i = 0; i < descs.length; i++) {
const descriptor = descs[i];
if (descriptor.options !== false) {
try {
pass.push(yield* loadPluginDescriptor(descriptor, context));
} catch (e) {
if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") {
(0, _options.checkNoUnwrappedItemOptionPairs)(descs, i, "plugin", e);
}
throw e;
}
}
}
}
})();
opts.plugins = passes[0];
opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({
plugins
}));
opts.passPerPreset = opts.presets.length > 0;
return {
options: opts,
passes: passes
};
});
exports.default = _default;
function enhanceError(context, fn) {
return function* (arg1, arg2) {
try {
return yield* fn(arg1, arg2);
} catch (e) {
if (!/^\[BABEL\]/.test(e.message)) {
e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`;
}
throw e;
}
};
}
const loadDescriptor = (0, _caching.makeWeakCache)(function* ({
value,
options,
dirname,
alias
}, cache) {
if (options === false) throw new Error("Assertion failure");
options = options || {};
let item = value;
if (typeof value === "function") {
const api = Object.assign({}, context, (0, _configApi.default)(cache));
try {
item = value(api, options, dirname);
} catch (e) {
if (alias) {
e.message += ` (While processing: ${JSON.stringify(alias)})`;
}
throw e;
}
}
if (!item || typeof item !== "object") {
throw new Error("Plugin/Preset did not return an object.");
}
if (typeof item.then === "function") {
yield* [];
throw new Error(`You appear to be using an async plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`);
}
return {
value: item,
options,
dirname,
alias
};
});
function* loadPluginDescriptor(descriptor, context) {
if (descriptor.value instanceof _plugin.default) {
if (descriptor.options) {
throw new Error("Passed options to an existing Plugin instance will not work.");
}
return descriptor.value;
}
return yield* instantiatePlugin(yield* loadDescriptor(descriptor, context), context);
}
const instantiatePlugin = (0, _caching.makeWeakCache)(function* ({
value,
options,
dirname,
alias
}, cache) {
const pluginObj = (0, _plugins.validatePluginObject)(value);
const plugin = Object.assign({}, pluginObj);
if (plugin.visitor) {
plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor));
}
if (plugin.inherits) {
const inheritsDescriptor = {
name: undefined,
alias: `${alias}$inherits`,
value: plugin.inherits,
options,
dirname
};
const inherits = yield* (0, _async.forwardAsync)(loadPluginDescriptor, run => {
return cache.invalidate(data => run(inheritsDescriptor, data));
});
plugin.pre = chain(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post);
plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions);
plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]);
}
return new _plugin.default(plugin, options, alias);
});
const validateIfOptionNeedsFilename = (options, descriptor) => {
if (options.test || options.include || options.exclude) {
const formattedPresetName = descriptor.name ? `"${descriptor.name}"` : "/* your preset */";
throw new Error([`Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`, `\`\`\``, `babel.transform(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`, `\`\`\``, `See https://babeljs.io/docs/en/options#filename for more information.`].join("\n"));
}
};
const validatePreset = (preset, context, descriptor) => {
if (!context.filename) {
const {
options
} = preset;
validateIfOptionNeedsFilename(options, descriptor);
if (options.overrides) {
options.overrides.forEach(overrideOptions => validateIfOptionNeedsFilename(overrideOptions, descriptor));
}
}
};
function* loadPresetDescriptor(descriptor, context) {
const preset = instantiatePreset(yield* loadDescriptor(descriptor, context));
validatePreset(preset, context, descriptor);
return yield* (0, _configChain.buildPresetChain)(preset, context);
}
const instantiatePreset = (0, _caching.makeWeakCacheSync)(({
value,
dirname,
alias
}) => {
return {
options: (0, _options.validate)("preset", value),
alias,
dirname
};
});
function chain(a, b) {
const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0];
return function (...args) {
for (const fn of fns) {
fn.apply(this, args);
}
};
}
@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = makeAPI;
function _semver() {
const data = _interopRequireDefault(require("semver"));
_semver = function () {
return data;
};
return data;
}
var _ = require("../../");
var _caching = require("../caching");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function makeAPI(cache) {
const env = value => cache.using(data => {
if (typeof value === "undefined") return data.envName;
if (typeof value === "function") {
return (0, _caching.assertSimpleType)(value(data.envName));
}
if (!Array.isArray(value)) value = [value];
return value.some(entry => {
if (typeof entry !== "string") {
throw new Error("Unexpected non-string value");
}
return entry === data.envName;
});
});
const caller = cb => cache.using(data => (0, _caching.assertSimpleType)(cb(data.caller)));
return {
version: _.version,
cache: cache.simple(),
env,
async: () => false,
caller,
assertVersion
};
}
function assertVersion(range) {
if (typeof range === "number") {
if (!Number.isInteger(range)) {
throw new Error("Expected string or integer value.");
}
range = `^${range}.0.0-0`;
}
if (typeof range !== "string") {
throw new Error("Expected string or integer value.");
}
if (_semver().default.satisfies(_.version, range)) return;
const limit = Error.stackTraceLimit;
if (typeof limit === "number" && limit < 25) {
Error.stackTraceLimit = 25;
}
const err = new Error(`Requires Babel "${range}", but was loaded with "${_.version}". ` + `If you are sure you have a compatible version of @babel/core, ` + `it is likely that something in your build process is loading the ` + `wrong version. Inspect the stack trace of this error to look for ` + `the first entry that doesn't mention "@babel/core" or "babel-core" ` + `to see what is calling Babel.`);
if (typeof limit === "number") {
Error.stackTraceLimit = limit;
}
throw Object.assign(err, {
code: "BABEL_VERSION_UNSUPPORTED",
version: _.version,
range
});
}
@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getEnv = getEnv;
function getEnv(defaultValue = "development") {
return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;
}
@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function () {
return _full.default;
}
});
exports.loadOptionsAsync = exports.loadOptionsSync = exports.loadOptions = exports.loadPartialConfigAsync = exports.loadPartialConfigSync = exports.loadPartialConfig = void 0;
function _gensync() {
const data = _interopRequireDefault(require("gensync"));
_gensync = function () {
return data;
};
return data;
}
var _full = _interopRequireDefault(require("./full"));
var _partial = require("./partial");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const loadOptionsRunner = (0, _gensync().default)(function* (opts) {
var _config$options;
const config = yield* (0, _full.default)(opts);
return (_config$options = config == null ? void 0 : config.options) != null ? _config$options : null;
});
const maybeErrback = runner => (opts, callback) => {
if (callback === undefined && typeof opts === "function") {
callback = opts;
opts = undefined;
}
return callback ? runner.errback(opts, callback) : runner.sync(opts);
};
const loadPartialConfig = maybeErrback(_partial.loadPartialConfig);
exports.loadPartialConfig = loadPartialConfig;
const loadPartialConfigSync = _partial.loadPartialConfig.sync;
exports.loadPartialConfigSync = loadPartialConfigSync;
const loadPartialConfigAsync = _partial.loadPartialConfig.async;
exports.loadPartialConfigAsync = loadPartialConfigAsync;
const loadOptions = maybeErrback(loadOptionsRunner);
exports.loadOptions = loadOptions;
const loadOptionsSync = loadOptionsRunner.sync;
exports.loadOptionsSync = loadOptionsSync;
const loadOptionsAsync = loadOptionsRunner.async;
exports.loadOptionsAsync = loadOptionsAsync;
@@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createItemFromDescriptor = createItemFromDescriptor;
exports.createConfigItem = createConfigItem;
exports.getItemDescriptor = getItemDescriptor;
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
var _configDescriptors = require("./config-descriptors");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function createItemFromDescriptor(desc) {
return new ConfigItem(desc);
}
function createConfigItem(value, {
dirname = ".",
type
} = {}) {
const descriptor = (0, _configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), {
type,
alias: "programmatic item"
});
return createItemFromDescriptor(descriptor);
}
function getItemDescriptor(item) {
if (item == null ? void 0 : item[CONFIG_ITEM_BRAND]) {
return item._descriptor;
}
return undefined;
}
const CONFIG_ITEM_BRAND = Symbol.for("@babel/core@7 - ConfigItem");
class ConfigItem {
constructor(descriptor) {
this._descriptor = void 0;
this[CONFIG_ITEM_BRAND] = true;
this.value = void 0;
this.options = void 0;
this.dirname = void 0;
this.name = void 0;
this.file = void 0;
this._descriptor = descriptor;
Object.defineProperty(this, "_descriptor", {
enumerable: false
});
Object.defineProperty(this, CONFIG_ITEM_BRAND, {
enumerable: false
});
this.value = this._descriptor.value;
this.options = this._descriptor.options;
this.dirname = this._descriptor.dirname;
this.name = this._descriptor.name;
this.file = this._descriptor.file ? {
request: this._descriptor.file.request,
resolved: this._descriptor.file.resolved
} : undefined;
Object.freeze(this);
}
}
Object.freeze(ConfigItem.prototype);
@@ -0,0 +1,187 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loadPrivatePartialConfig;
exports.loadPartialConfig = void 0;
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _gensync() {
const data = _interopRequireDefault(require("gensync"));
_gensync = function () {
return data;
};
return data;
}
var _plugin = _interopRequireDefault(require("./plugin"));
var _util = require("./util");
var _item = require("./item");
var _configChain = require("./config-chain");
var _environment = require("./helpers/environment");
var _options = require("./validation/options");
var _files = require("./files");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function* resolveRootMode(rootDir, rootMode) {
switch (rootMode) {
case "root":
return rootDir;
case "upward-optional":
{
const upwardRootDir = yield* (0, _files.findConfigUpwards)(rootDir);
return upwardRootDir === null ? rootDir : upwardRootDir;
}
case "upward":
{
const upwardRootDir = yield* (0, _files.findConfigUpwards)(rootDir);
if (upwardRootDir !== null) return upwardRootDir;
throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}".\n` + `One of the following config files must be in the directory tree: ` + `"${_files.ROOT_CONFIG_FILENAMES.join(", ")}".`), {
code: "BABEL_ROOT_NOT_FOUND",
dirname: rootDir
});
}
default:
throw new Error(`Assertion failure - unknown rootMode value.`);
}
}
function* loadPrivatePartialConfig(inputOpts) {
if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) {
throw new Error("Babel options must be an object, null, or undefined");
}
const args = inputOpts ? (0, _options.validate)("arguments", inputOpts) : {};
const {
envName = (0, _environment.getEnv)(),
cwd = ".",
root: rootDir = ".",
rootMode = "root",
caller,
cloneInputAst = true
} = args;
const absoluteCwd = _path().default.resolve(cwd);
const absoluteRootDir = yield* resolveRootMode(_path().default.resolve(absoluteCwd, rootDir), rootMode);
const filename = typeof args.filename === "string" ? _path().default.resolve(cwd, args.filename) : undefined;
const showConfigPath = yield* (0, _files.resolveShowConfigPath)(absoluteCwd);
const context = {
filename,
cwd: absoluteCwd,
root: absoluteRootDir,
envName,
caller,
showConfig: showConfigPath === filename
};
const configChain = yield* (0, _configChain.buildRootChain)(args, context);
if (!configChain) return null;
const options = {};
configChain.options.forEach(opts => {
(0, _util.mergeOptions)(options, opts);
});
options.cloneInputAst = cloneInputAst;
options.babelrc = false;
options.configFile = false;
options.passPerPreset = false;
options.envName = context.envName;
options.cwd = context.cwd;
options.root = context.root;
options.filename = typeof context.filename === "string" ? context.filename : undefined;
options.plugins = configChain.plugins.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor));
options.presets = configChain.presets.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor));
return {
options,
context,
fileHandling: configChain.fileHandling,
ignore: configChain.ignore,
babelrc: configChain.babelrc,
config: configChain.config,
files: configChain.files
};
}
const loadPartialConfig = (0, _gensync().default)(function* (opts) {
let showIgnoredFiles = false;
if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) {
var _opts = opts;
({
showIgnoredFiles
} = _opts);
opts = _objectWithoutPropertiesLoose(_opts, ["showIgnoredFiles"]);
_opts;
}
const result = yield* loadPrivatePartialConfig(opts);
if (!result) return null;
const {
options,
babelrc,
ignore,
config,
fileHandling,
files
} = result;
if (fileHandling === "ignored" && !showIgnoredFiles) {
return null;
}
(options.plugins || []).forEach(item => {
if (item.value instanceof _plugin.default) {
throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()");
}
});
return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined, fileHandling, files);
});
exports.loadPartialConfig = loadPartialConfig;
class PartialConfig {
constructor(options, babelrc, ignore, config, fileHandling, files) {
this.options = void 0;
this.babelrc = void 0;
this.babelignore = void 0;
this.config = void 0;
this.fileHandling = void 0;
this.files = void 0;
this.options = options;
this.babelignore = ignore;
this.babelrc = babelrc;
this.config = config;
this.fileHandling = fileHandling;
this.files = files;
Object.freeze(this);
}
hasFilesystemConfig() {
return this.babelrc !== undefined || this.config !== undefined;
}
}
Object.freeze(PartialConfig.prototype);
@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pathToPattern;
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _escapeRegExp() {
const data = _interopRequireDefault(require("lodash/escapeRegExp"));
_escapeRegExp = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const sep = `\\${_path().default.sep}`;
const endSep = `(?:${sep}|$)`;
const substitution = `[^${sep}]+`;
const starPat = `(?:${substitution}${sep})`;
const starPatLast = `(?:${substitution}${endSep})`;
const starStarPat = `${starPat}*?`;
const starStarPatLast = `${starPat}*?${starPatLast}?`;
function pathToPattern(pattern, dirname) {
const parts = _path().default.resolve(dirname, pattern).split(_path().default.sep);
return new RegExp(["^", ...parts.map((part, i) => {
const last = i === parts.length - 1;
if (part === "**") return last ? starStarPatLast : starStarPat;
if (part === "*") return last ? starPatLast : starPat;
if (part.indexOf("*.") === 0) {
return substitution + (0, _escapeRegExp().default)(part.slice(1)) + (last ? endSep : sep);
}
return (0, _escapeRegExp().default)(part) + (last ? endSep : sep);
})].join(""));
}
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class Plugin {
constructor(plugin, options, key) {
this.key = void 0;
this.manipulateOptions = void 0;
this.post = void 0;
this.pre = void 0;
this.visitor = void 0;
this.parserOverride = void 0;
this.generatorOverride = void 0;
this.options = void 0;
this.key = plugin.name || key;
this.manipulateOptions = plugin.manipulateOptions;
this.post = plugin.post;
this.pre = plugin.pre;
this.visitor = plugin.visitor || {};
this.parserOverride = plugin.parserOverride;
this.generatorOverride = plugin.generatorOverride;
this.options = options;
}
}
exports.default = Plugin;

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