Added ts2fable to npm

This commit is contained in:
Pedro Pinto committed 2020-05-26 21:14:59 -04:00
1 parent d82ea532d8
commit f68dcf6fc4
181 files changed
+641254

No files matched your search

Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../ts2fable/dist/ts2fable.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../typescript/bin/tsc
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../typescript/bin/tsserver
Binary file not shown.
+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 {yyyy} {name of copyright owner}
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.
+107
View File
@@ -0,0 +1,107 @@
# **ts2fable** [![npm version](https://badge.fury.io/js/ts2fable.svg)](https://www.npmjs.com/package/ts2fable)
[Fable](https://github.com/fable-compiler/Fable) parser for [TypeScript declaration files](https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html).
## Usage
Install it with yarn or npm. With yarn it is:
```
yarn global add ts2fable
```
With npm it is:
```
npm install -g ts2fable
```
Run the `ts2fable` command on a TypeScript file and also specify the F# output file. The F# namespace in taken from the output filename. In this example, it is `Yargs`.
```
yarn add @types/yargs --dev
ts2fable node_modules/@types/yargs/index.d.ts src/Yargs.fs
```
You can also use `--export`(or `-e`) option to collect from multiple `tsfiles`
In below sample: All the **related ts files** in npm packages **uifabric** and **office-ui-fabric-react** will be compiled to `OfficeReact.fs` as a [bundle](https://github.com/fable-compiler/ts2fable-exports/blob/master/OfficeReact.fs)
```
ts2fable node_modules/office-ui-fabric-react/lib/index.d.ts test-compile/OfficeReact.fs -e uifabric office-ui-fabric-react
```
You can find more information about how to interact with JavaScript
from F# [here](https://github.com/fable-compiler/Fable/blob/master/docs/source/docs/interacting.md).
Please note the parser is not perfect and some tweaking by hand may be needed. Please submit bugs as [issues on GitHub](https://github.com/fable-compiler/ts2fable/issues).
## Contributing
Succesfull [builds](https://ci.appveyor.com/project/fable-compiler/ts2fable/history) on the master branch are uploaded and tagged as `next`. You can help us test these builds by installing them with:
```
yarn global add ts2fable@next
```
### Running code from source
**Windows**:
- `git clone https://github.com/fable-compiler/ts2fable`
- Install all dependencies: `fake.cmd run build.fsx`
**Unix**:
- `git clone https://github.com/fable-compiler/ts2fable`
- `./fake.sh run build.fsx`
**Common to all OS**
- In vscode, press `Ctrl+Shift+P` > Run Task > WatchTest
- Add your test in `test/fsFileTests.fs` and prefix it with mocha `only` (See below sample)
Sample Test:
```fsharp
only "duplicated variable exports" <| fun _ ->
let tsPaths = ["node_modules/reactxp/dist/web/ReactXP.d.ts"]
let fsPath = "test-compile/ReactXP.fs"
testFsFiles tsPaths fsPath <| fun fsFiles ->
fsFiles
|> getTopVarialbles
|> List.countBy(fun vb -> vb.Name)
|> List.forall(fun (_,l) -> l = 1)
|> equal true
```
- Press F5 to debug this test
## Conventions
Some JavaScript/TypeScript features have no direct translation to F#. Here is
a list of common workarounds adopted by the parser to solve these problems:
* **Erased unions**: TypeScript union types work differently from F# and its only
purpose is to specify the types allowed for a function argument. In F# they are
translated as _erased unions_: they're checked at compiled time but they'll be
removed from the generated JS code.
```fsharp
type CanvasRenderingContext2D =
abstract fillStyle: U3<string, CanvasGradient, CanvasPattern> with get, set
let ctx: CanvasRenderingContext2D = failwith "dummy"
ctx.fillStyle <- U3.Case1 "#FF0000"
```
* **Constructor functions**: In JS any function can become a constructor just by
calling it with the `new` keyword. In the parsed files, interfaces with this
capability will have a `Create` method attached:
```fsharp
type CanvasRenderingContext2DType =
abstract prototype: CanvasRenderingContext2D with get, set
[<Emit("new $0($1...)")>] abstract Create: unit -> CanvasRenderingContext2D
```
* **Callable interfaces**: In the same way, JS functions are just objects which
means applying arguments directly to any object is legal in JS. To convey, the
parser attaches an `Invoke` method to callable interfaces:
```fsharp
type Express =
inherit Application
abstract version: string with get, set
abstract application: obj with get, set
[<Emit("$0($1...)")>] abstract Invoke: unit -> Application
```
+160
View File
@@ -0,0 +1,160 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.map = map;
exports.mapIndexed = mapIndexed;
exports.indexed = indexed;
exports.addRangeInPlace = addRangeInPlace;
exports.copyTo = copyTo;
exports.partition = partition;
exports.permute = permute;
exports.removeInPlace = removeInPlace;
exports.setSlice = setSlice;
exports.sortInPlaceBy = sortInPlaceBy;
exports.unzip = unzip;
exports.unzip3 = unzip3;
exports.chunkBySize = chunkBySize;
exports.getSubArray = getSubArray;
exports.fill = fill;
exports.splitAt = splitAt;
function map(f, source, TargetCons) {
const target = new TargetCons(source.length);
for (let i = 0; i < source.length; i++) {
target[i] = f(source[i]);
}
return target;
}
function mapIndexed(f, source, TargetCons) {
const target = new TargetCons(source.length);
for (let i = 0; i < source.length; i++) {
target[i] = f(i, source[i]);
}
return target;
}
function indexed(source) {
return mapIndexed((i, x) => [i, x], source, Array);
}
function addRangeInPlace(range, xs) {
const iter = range[Symbol.iterator]();
let cur = iter.next();
while (!cur.done) {
xs.push(cur.value);
cur = iter.next();
}
}
function copyTo(source, sourceIndex, target, targetIndex, count) {
while (count--) {
target[targetIndex++] = source[sourceIndex++];
}
}
function partition(f, xs) {
const ys = [];
const zs = [];
let j = 0;
let k = 0;
for (let i = 0; i < xs.length; i++) {
if (f(xs[i])) {
ys[j++] = xs[i];
} else {
zs[k++] = xs[i];
}
}
return [ys, zs];
}
function permute(f, xs) {
// Keep the type of the array
const ys = xs.map(() => null);
const checkFlags = new Array(xs.length);
for (let i = 0; i < xs.length; i++) {
const j = f(i);
if (j < 0 || j >= xs.length) {
throw new Error("Not a valid permutation");
}
ys[j] = xs[i];
checkFlags[j] = 1;
}
for (let i = 0; i < xs.length; i++) {
if (checkFlags[i] !== 1) {
throw new Error("Not a valid permutation");
}
}
return ys;
}
function removeInPlace(item, xs) {
const i = xs.indexOf(item);
if (i > -1) {
xs.splice(i, 1);
return true;
}
return false;
}
function setSlice(target, lower, upper, source) {
const length = (upper || target.length - 1) - lower;
if (ArrayBuffer.isView(target) && source.length <= length) {
target.set(source, lower);
} else {
for (let i = lower | 0, j = 0; j <= length; i++, j++) {
target[i] = source[j];
}
}
}
function sortInPlaceBy(f, xs, dir = 1) {
return xs.sort((x, y) => {
x = f(x);
y = f(y);
return (x < y ? -1 : x === y ? 0 : 1) * dir;
});
}
function unzip(xs) {
const bs = new Array(xs.length);
const cs = new Array(xs.length);
for (let i = 0; i < xs.length; i++) {
bs[i] = xs[i][0];
cs[i] = xs[i][1];
}
return [bs, cs];
}
function unzip3(xs) {
const bs = new Array(xs.length);
const cs = new Array(xs.length);
const ds = new Array(xs.length);
for (let i = 0; i < xs.length; i++) {
bs[i] = xs[i][0];
cs[i] = xs[i][1];
ds[i] = xs[i][2];
}
return [bs, cs, ds];
}
function chunkBySize(size, xs) {
if (size < 1) {
throw new Error("The input must be positive. parameter name: chunkSize");
}
if (xs.length === 0) {
return [[]];
}
const result = [];
// add each chunk to the result
for (let x = 0; x < Math.ceil(xs.length / size); x++) {
const start = x * size;
const end = start + size;
result.push(xs.slice(start, end));
}
return result;
}
function getSubArray(xs, startIndex, count) {
return xs.slice(startIndex, startIndex + count);
}
function fill(target, targetIndex, count, value) {
target.fill(value, targetIndex, targetIndex + count);
}
function splitAt(index, xs) {
if (index < 0) {
throw new Error("The input must be non-negative.");
}
if (index > xs.length) {
throw new Error("The input sequence has an insufficient number of elements.");
}
return [xs.slice(0, index), xs.slice(index)];
}
+40
View File
@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fromEqualityComparer = fromEqualityComparer;
var _Symbol = require("./Symbol");
var _Symbol2 = _interopRequireDefault(_Symbol);
var _Util = require("./Util");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class Comparer {
constructor(f) {
this.Compare = f || _Util.compare;
}
[_Symbol2.default.reflection]() {
return { interfaces: ["System.IComparer"] };
}
}
exports.default = Comparer;
function fromEqualityComparer(comparer) {
// Sometimes IEqualityComparer also implements IComparer
if (typeof comparer.Compare === "function") {
return new Comparer(comparer.Compare);
} else {
return new Comparer((x, y) => {
const xhash = comparer.GetHashCode(x);
const yhash = comparer.GetHashCode(y);
if (xhash === yhash) {
return comparer.Equals(x, y) ? 0 : -1;
} else {
return xhash < yhash ? -1 : 1;
}
});
}
}
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = CurriedLambda;
function CurriedLambda(f, expectedArgsLength) {
if (f.curried === true) {
return f;
}
const curriedFn = (...args) => {
const args2 = args.map(x => typeof x === "function" ? CurriedLambda(x) : x);
const actualArgsLength = Math.max(args2.length, 1);
expectedArgsLength = Math.max(expectedArgsLength || f.length, 1);
if (actualArgsLength >= expectedArgsLength) {
const restArgs = args2.splice(expectedArgsLength);
const res = f(...args2);
if (typeof res === "function") {
const newLambda = CurriedLambda(res);
return restArgs.length === 0 ? newLambda : newLambda(...restArgs);
} else {
return res;
}
} else {
return CurriedLambda((...args3) => {
return f(...args2.concat(args3));
}, expectedArgsLength - actualArgsLength);
}
};
curriedFn.curried = true;
return curriedFn;
}
+368
View File
@@ -0,0 +1,368 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.padWithZeros = padWithZeros;
exports.offsetToString = offsetToString;
exports.toHalfUTCString = toHalfUTCString;
exports.toStringWithOffset = toStringWithOffset;
exports.toStringWithKind = toStringWithKind;
exports.toString = toString;
exports.default = DateTime;
exports.minValue = minValue;
exports.maxValue = maxValue;
exports.parseRaw = parseRaw;
exports.parse = parse;
exports.tryParse = tryParse;
exports.offset = offset;
exports.create = create;
exports.now = now;
exports.utcNow = utcNow;
exports.today = today;
exports.isLeapYear = isLeapYear;
exports.daysInMonth = daysInMonth;
exports.toUniversalTime = toUniversalTime;
exports.toLocalTime = toLocalTime;
exports.timeOfDay = timeOfDay;
exports.date = date;
exports.day = day;
exports.hour = hour;
exports.millisecond = millisecond;
exports.minute = minute;
exports.month = month;
exports.second = second;
exports.year = year;
exports.dayOfWeek = dayOfWeek;
exports.dayOfYear = dayOfYear;
exports.add = add;
exports.addDays = addDays;
exports.addHours = addHours;
exports.addMinutes = addMinutes;
exports.addSeconds = addSeconds;
exports.addMilliseconds = addMilliseconds;
exports.addYears = addYears;
exports.addMonths = addMonths;
exports.subtract = subtract;
exports.toLongDateString = toLongDateString;
exports.toShortDateString = toShortDateString;
exports.toLongTimeString = toLongTimeString;
exports.toShortTimeString = toShortTimeString;
exports.equals = equals;
exports.compare = compare;
exports.op_Addition = op_Addition;
exports.op_Subtraction = op_Subtraction;
exports.isDaylightSavingTime = isDaylightSavingTime;
const offsetRegex = exports.offsetRegex = /(?:Z|[+-](\d{2}):?(\d{2})?)$/;
function padWithZeros(i, length) {
let str = i.toString(10);
while (str.length < length) {
str = "0" + str;
}
return str;
}
function offsetToString(offset) {
const isMinus = offset < 0;
offset = Math.abs(offset);
const hours = ~~(offset / 3600000);
const minutes = offset % 3600000 / 60000;
return (isMinus ? "-" : "+") + padWithZeros(hours, 2) + ":" + padWithZeros(minutes, 2);
}
function toHalfUTCString(date, half) {
const str = date.toISOString();
return half === "first" ? str.substring(0, str.indexOf("T")) : str.substring(str.indexOf("T") + 1, str.length - 1);
}
function toISOString(d, utc) {
if (utc) {
return d.toISOString();
} else {
// JS Date is always local
const printOffset = d.kind == null ? true : d.kind === 2 /* Local */;
return padWithZeros(d.getFullYear(), 4) + "-" + padWithZeros(d.getMonth() + 1, 2) + "-" + padWithZeros(d.getDate(), 2) + "T" + padWithZeros(d.getHours(), 2) + ":" + padWithZeros(d.getMinutes(), 2) + ":" + padWithZeros(d.getSeconds(), 2) + "." + padWithZeros(d.getMilliseconds(), 3) + (printOffset ? offsetToString(d.getTimezoneOffset() * -60000) : "");
}
}
function toISOStringWithOffset(dateWithOffset, offset) {
const str = dateWithOffset.toISOString();
return str.substring(0, str.length - 1) + offsetToString(offset);
}
function toStringWithCustomFormat(date, format, utc) {
return format.replace(/(\w)\1*/g, match => {
let rep = match;
switch (match.substring(0, 1)) {
case "y":
const y = utc ? date.getUTCFullYear() : date.getFullYear();
rep = match.length < 4 ? y % 100 : y;
break;
case "M":
rep = (utc ? date.getUTCMonth() : date.getMonth()) + 1;
break;
case "d":
rep = utc ? date.getUTCDate() : date.getDate();
break;
case "H":
rep = utc ? date.getUTCHours() : date.getHours();
break;
case "h":
const h = utc ? date.getUTCHours() : date.getHours();
rep = h > 12 ? h % 12 : h;
break;
case "m":
rep = utc ? date.getUTCMinutes() : date.getMinutes();
break;
case "s":
rep = utc ? date.getUTCSeconds() : date.getSeconds();
break;
}
if (rep !== match && rep < 10 && match.length > 1) {
rep = "0" + rep;
}
return rep;
});
}
function toStringWithOffset(date, format) {
const d = new Date(date.getTime() + date.offset);
if (!format) {
return d.toISOString().replace(/\.\d+/, "").replace(/[A-Z]|\.\d+/g, " ") + offsetToString(date.offset);
} else if (format.length === 1) {
switch (format) {
case "D":
case "d":
return toHalfUTCString(d, "first");
case "T":
case "t":
return toHalfUTCString(d, "second");
case "O":
case "o":
return toISOStringWithOffset(d, date.offset);
default:
throw new Error("Unrecognized Date print format");
}
} else {
return toStringWithCustomFormat(d, format, true);
}
}
function toStringWithKind(date, format) {
const utc = date.kind === 1 /* UTC */;
if (!format) {
return utc ? date.toUTCString() : date.toLocaleString();
} else if (format.length === 1) {
switch (format) {
case "D":
case "d":
return utc ? toHalfUTCString(date, "first") : date.toLocaleDateString();
case "T":
case "t":
return utc ? toHalfUTCString(date, "second") : date.toLocaleTimeString();
case "O":
case "o":
return toISOString(date, utc);
default:
throw new Error("Unrecognized Date print format");
}
} else {
return toStringWithCustomFormat(date, format, utc);
}
}
function toString(date, format) {
return date.offset != null ? toStringWithOffset(date, format) : toStringWithKind(date, format);
}
function DateTime(value, kind) {
kind = kind == null ? 0 /* Unspecified */ : kind;
const d = new Date(value);
d.kind = kind | 0;
return d;
}
function minValue() {
// This is "0001-01-01T00:00:00.000Z", actual JS min value is -8640000000000000
return DateTime(-62135596800000, 0 /* Unspecified */);
}
function maxValue() {
// This is "9999-12-31T23:59:59.999Z", actual JS max value is 8640000000000000
return DateTime(253402300799999, 0 /* Unspecified */);
}
function parseRaw(str) {
let date = new Date(str);
if (isNaN(date.getTime())) {
// Check if this is a time-only string, which JS Date parsing cannot handle (see #1045)
if (/^(?:[01]?\d|2[0-3]):(?:[0-5]?\d)(?::[0-5]?\d(?:\.\d+)?)?(?:\s*[AaPp][Mm])?$/.test(str)) {
const d = new Date();
date = new Date(d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate() + " " + str);
} else {
throw new Error("The string is not a valid Date.");
}
}
return date;
}
function parse(str, detectUTC = false) {
const date = parseRaw(str);
const offset = offsetRegex.exec(str);
// .NET always parses DateTime as Local if there's offset info (even "Z")
// Newtonsoft.Json uses UTC if the offset is "Z"
const kind = offset != null ? detectUTC && offset[0] === "Z" ? 1 /* UTC */ : 2 /* Local */ : 0 /* Unspecified */;
return DateTime(date.getTime(), kind);
}
function tryParse(v) {
try {
return [true, parse(v)];
} catch (_err) {
return [false, minValue()];
}
}
function offset(date) {
const date1 = date;
return typeof date1.offset === "number" ? date1.offset : date.kind === 1 /* UTC */
? 0 : date.getTimezoneOffset() * -60000;
}
function create(year, month, day, h = 0, m = 0, s = 0, ms = 0, kind) {
const dateValue = kind === 1 /* UTC */
? Date.UTC(year, month - 1, day, h, m, s, ms) : new Date(year, month - 1, day, h, m, s, ms).getTime();
if (isNaN(dateValue)) {
throw new Error("The parameters describe an unrepresentable Date.");
}
const date = DateTime(dateValue, kind);
if (year <= 99) {
date.setFullYear(year, month - 1, day);
}
return date;
}
function now() {
return DateTime(Date.now(), 2 /* Local */);
}
function utcNow() {
return DateTime(Date.now(), 1 /* UTC */);
}
function today() {
return date(now());
}
function isLeapYear(year) {
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
}
function daysInMonth(year, month) {
return month === 2 ? isLeapYear(year) ? 29 : 28 : month >= 8 ? month % 2 === 0 ? 31 : 30 : month % 2 === 0 ? 30 : 31;
}
function toUniversalTime(date) {
return date.kind === 1 /* UTC */ ? date : DateTime(date.getTime(), 1 /* UTC */);
}
function toLocalTime(date) {
return date.kind === 2 /* Local */ ? date : DateTime(date.getTime(), 2 /* Local */);
}
function timeOfDay(d) {
return hour(d) * 3600000 + minute(d) * 60000 + second(d) * 1000 + millisecond(d);
}
function date(d) {
return create(year(d), month(d), day(d), 0, 0, 0, 0, d.kind);
}
function day(d) {
return d.kind === 1 /* UTC */ ? d.getUTCDate() : d.getDate();
}
function hour(d) {
return d.kind === 1 /* UTC */ ? d.getUTCHours() : d.getHours();
}
function millisecond(d) {
return d.kind === 1 /* UTC */ ? d.getUTCMilliseconds() : d.getMilliseconds();
}
function minute(d) {
return d.kind === 1 /* UTC */ ? d.getUTCMinutes() : d.getMinutes();
}
function month(d) {
return (d.kind === 1 /* UTC */ ? d.getUTCMonth() : d.getMonth()) + 1;
}
function second(d) {
return d.kind === 1 /* UTC */ ? d.getUTCSeconds() : d.getSeconds();
}
function year(d) {
return d.kind === 1 /* UTC */ ? d.getUTCFullYear() : d.getFullYear();
}
function dayOfWeek(d) {
return d.kind === 1 /* UTC */ ? d.getUTCDay() : d.getDay();
}
function dayOfYear(d) {
const _year = year(d);
const _month = month(d);
let _day = day(d);
for (let i = 1; i < _month; i++) {
_day += daysInMonth(_year, i);
}
return _day;
}
function add(d, ts) {
return DateTime(d.getTime() + ts, d.kind);
}
function addDays(d, v) {
return DateTime(d.getTime() + v * 86400000, d.kind);
}
function addHours(d, v) {
return DateTime(d.getTime() + v * 3600000, d.kind);
}
function addMinutes(d, v) {
return DateTime(d.getTime() + v * 60000, d.kind);
}
function addSeconds(d, v) {
return DateTime(d.getTime() + v * 1000, d.kind);
}
function addMilliseconds(d, v) {
return DateTime(d.getTime() + v, d.kind);
}
function addYears(d, v) {
const newMonth = month(d);
const newYear = year(d) + v;
const _daysInMonth = daysInMonth(newYear, newMonth);
const newDay = Math.min(_daysInMonth, day(d));
return create(newYear, newMonth, newDay, hour(d), minute(d), second(d), millisecond(d), d.kind);
}
function addMonths(d, v) {
let newMonth = month(d) + v;
let newMonth_ = 0;
let yearOffset = 0;
if (newMonth > 12) {
newMonth_ = newMonth % 12;
yearOffset = Math.floor(newMonth / 12);
newMonth = newMonth_;
} else if (newMonth < 1) {
newMonth_ = 12 + newMonth % 12;
yearOffset = Math.floor(newMonth / 12) + (newMonth_ === 12 ? -1 : 0);
newMonth = newMonth_;
}
const newYear = year(d) + yearOffset;
const _daysInMonth = daysInMonth(newYear, newMonth);
const newDay = Math.min(_daysInMonth, day(d));
return create(newYear, newMonth, newDay, hour(d), minute(d), second(d), millisecond(d), d.kind);
}
function subtract(d, that) {
return typeof that === "number" ? DateTime(d.getTime() - that, d.kind) : d.getTime() - that.getTime();
}
function toLongDateString(d) {
return d.toDateString();
}
function toShortDateString(d) {
return d.toLocaleDateString();
}
function toLongTimeString(d) {
return d.toLocaleTimeString();
}
function toShortTimeString(d) {
return d.toLocaleTimeString().replace(/:\d\d(?!:)/, "");
}
function equals(d1, d2) {
return d1.getTime() === d2.getTime();
}
function compare(x, y) {
const xtime = x.getTime();
const ytime = y.getTime();
return xtime === ytime ? 0 : xtime < ytime ? -1 : 1;
}
const compareTo = exports.compareTo = compare;
function op_Addition(x, y) {
return add(x, y);
}
function op_Subtraction(x, y) {
return subtract(x, y);
}
function isDaylightSavingTime(x) {
const jan = new Date(x.getFullYear(), 0, 1);
const jul = new Date(x.getFullYear(), 6, 1);
return isDST(jan.getTimezoneOffset(), jul.getTimezoneOffset(), x.getTimezoneOffset());
}
function isDST(janOffset, julOffset, tOffset) {
return Math.min(janOffset, julOffset) === tOffset;
}
+226
View File
@@ -0,0 +1,226 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.compareTo = undefined;
exports.default = DateTimeOffset;
exports.fromDate = fromDate;
exports.minValue = minValue;
exports.maxValue = maxValue;
exports.parse = parse;
exports.tryParse = tryParse;
exports.create = create;
exports.now = now;
exports.utcNow = utcNow;
exports.toUniversalTime = toUniversalTime;
exports.toLocalTime = toLocalTime;
exports.timeOfDay = timeOfDay;
exports.date = date;
exports.day = day;
exports.hour = hour;
exports.millisecond = millisecond;
exports.minute = minute;
exports.month = month;
exports.second = second;
exports.year = year;
exports.dayOfWeek = dayOfWeek;
exports.dayOfYear = dayOfYear;
exports.add = add;
exports.addDays = addDays;
exports.addHours = addHours;
exports.addMinutes = addMinutes;
exports.addSeconds = addSeconds;
exports.addMilliseconds = addMilliseconds;
exports.addYears = addYears;
exports.addMonths = addMonths;
exports.subtract = subtract;
exports.equals = equals;
exports.equalsExact = equalsExact;
exports.compare = compare;
exports.op_Addition = op_Addition;
exports.op_Subtraction = op_Subtraction;
var _Date = require("./Date");
function DateTimeOffset(value, offset) {
const d = new Date(value);
d.offset = offset != null ? offset : new Date().getTimezoneOffset() * -60000;
return d;
}
function fromDate(date, offset) {
const isUtc = date.kind === 1 /* UTC */;
const offset2 = isUtc ? 0 : date.getTimezoneOffset() * -60000;
if (offset != null && offset !== offset2) {
throw new Error(isUtc ? "The UTC Offset for Utc DateTime instances must be 0." : "The UTC Offset of the local dateTime parameter does not match the offset argument.");
}
return DateTimeOffset(date.getTime(), offset2);
}
function minValue() {
// This is "0001-01-01T00:00:00.000Z", actual JS min value is -8640000000000000
return DateTimeOffset(-62135596800000, 0);
}
function maxValue() {
// This is "9999-12-31T23:59:59.999Z", actual JS max value is 8640000000000000
return DateTimeOffset(253402300799999, 0);
}
function parse(str) {
const date = (0, _Date.parseRaw)(str);
const offsetMatch = _Date.offsetRegex.exec(str);
const offset = offsetMatch == null ? date.getTimezoneOffset() * -60000 : offsetMatch[0] === "Z" ? 0 : parseInt(offsetMatch[1], 10) * 3600000 + parseInt(offsetMatch[2], 10) * 60000;
return DateTimeOffset(date.getTime(), offset);
}
function tryParse(v) {
try {
return [true, parse(v)];
} catch (_err) {
return [false, minValue()];
}
}
function create(year, month, day, h, m, s, ms, offset) {
if (offset == null) {
offset = ms;
ms = 0;
}
if (offset !== 0) {
if (offset % 60000 !== 0) {
throw new Error("Offset must be specified in whole minutes");
}
if (~~(offset / 3600000) > 14) {
throw new Error("Offset must be within plus or minus 14 hour");
}
}
let date;
if (offset === 0) {
date = new Date(Date.UTC(year, month - 1, day, h, m, s, ms));
if (year <= 99) {
date.setFullYear(year, month - 1, day);
}
} else {
const str = (0, _Date.padWithZeros)(year, 4) + "-" + (0, _Date.padWithZeros)(month, 2) + "-" + (0, _Date.padWithZeros)(day, 2) + "T" + (0, _Date.padWithZeros)(h, 2) + ":" + (0, _Date.padWithZeros)(m, 2) + ":" + (0, _Date.padWithZeros)(s, 2) + "." + (0, _Date.padWithZeros)(ms, 3) + (0, _Date.offsetToString)(offset);
date = new Date(str);
}
const dateValue = date.getTime();
if (isNaN(dateValue)) {
throw new Error("The parameters describe an unrepresentable Date");
}
return DateTimeOffset(dateValue, offset);
}
function now() {
const date = new Date();
return DateTimeOffset(date.getTime(), date.getTimezoneOffset() * -60000);
}
function utcNow() {
return DateTimeOffset(Date.now(), 0);
}
function toUniversalTime(date) {
return DateTimeOffset(date.getTime(), 0);
}
function toLocalTime(date) {
return DateTimeOffset(date.getTime(), date.getTimezoneOffset() * -60000);
}
function timeOfDay(d) {
const d2 = new Date(d.getTime() + d.offset);
return d2.getUTCHours() * 3600000 + d2.getUTCMinutes() * 60000 + d2.getUTCSeconds() * 1000 + d2.getUTCMilliseconds();
}
function date(d) {
const d2 = new Date(d.getTime() + d.offset);
return (0, _Date.create)(d2.getUTCFullYear(), d2.getUTCMonth() + 1, d2.getUTCDate(), 0, 0, 0, 0);
}
function day(d) {
return new Date(d.getTime() + d.offset).getUTCDate();
}
function hour(d) {
return new Date(d.getTime() + d.offset).getUTCHours();
}
function millisecond(d) {
return new Date(d.getTime() + d.offset).getUTCMilliseconds();
}
function minute(d) {
return new Date(d.getTime() + d.offset).getUTCMinutes();
}
function month(d) {
return new Date(d.getTime() + d.offset).getUTCMonth() + 1;
}
function second(d) {
return new Date(d.getTime() + d.offset).getUTCSeconds();
}
function year(d) {
return new Date(d.getTime() + d.offset).getUTCFullYear();
}
function dayOfWeek(d) {
return new Date(d.getTime() + d.offset).getUTCDay();
}
function dayOfYear(d) {
const d2 = new Date(d.getTime() + d.offset);
const _year = d2.getUTCFullYear();
const _month = d2.getUTCMonth() + 1;
let _day = d2.getUTCDate();
for (let i = 1; i < _month; i++) {
_day += (0, _Date.daysInMonth)(_year, i);
}
return _day;
}
function add(d, ts) {
return DateTimeOffset(d.getTime() + ts, d.offset);
}
function addDays(d, v) {
return DateTimeOffset(d.getTime() + v * 86400000, d.offset);
}
function addHours(d, v) {
return DateTimeOffset(d.getTime() + v * 3600000, d.offset);
}
function addMinutes(d, v) {
return DateTimeOffset(d.getTime() + v * 60000, d.offset);
}
function addSeconds(d, v) {
return DateTimeOffset(d.getTime() + v * 1000, d.offset);
}
function addMilliseconds(d, v) {
return DateTimeOffset(d.getTime() + v, d.offset);
}
function addYears(d, v) {
const newMonth = d.getUTCMonth() + 1;
const newYear = d.getUTCFullYear() + v;
const _daysInMonth = (0, _Date.daysInMonth)(newYear, newMonth);
const newDay = Math.min(_daysInMonth, d.getUTCDate());
return create(newYear, newMonth, newDay, d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds(), d.offset);
}
function addMonths(d, v) {
const d2 = new Date(d.getTime() + d.offset);
let newMonth = d2.getUTCMonth() + 1 + v;
let newMonth_ = 0;
let yearOffset = 0;
if (newMonth > 12) {
newMonth_ = newMonth % 12;
yearOffset = Math.floor(newMonth / 12);
newMonth = newMonth_;
} else if (newMonth < 1) {
newMonth_ = 12 + newMonth % 12;
yearOffset = Math.floor(newMonth / 12) + (newMonth_ === 12 ? -1 : 0);
newMonth = newMonth_;
}
const newYear = d2.getUTCFullYear() + yearOffset;
const _daysInMonth = (0, _Date.daysInMonth)(newYear, newMonth);
const newDay = Math.min(_daysInMonth, d2.getUTCDate());
return create(newYear, newMonth, newDay, d2.getUTCHours(), d2.getUTCMinutes(), d2.getUTCSeconds(), d2.getUTCMilliseconds(), d.offset);
}
function subtract(d, that) {
return typeof that === "number" ? DateTimeOffset(d.getTime() - that, d.offset) : d.getTime() - that.getTime();
}
function equals(d1, d2) {
return d1.getTime() === d2.getTime();
}
function equalsExact(d1, d2) {
return d1.getTime() === d2.getTime() && d1.offset === d2.offset;
}
function compare(d1, d2) {
return (0, _Date.compare)(d1, d2);
}
const compareTo = exports.compareTo = compare;
function op_Addition(x, y) {
return add(x, y);
}
function op_Subtraction(x, y) {
return subtract(x, y);
}
+66
View File
@@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isValid = isValid;
exports.tryParse = tryParse;
exports.parse = parse;
const parseRadix = /^\s*([\+\-])?(0[xob])?([0-9a-fA-F]+)\s*$/;
const invalidRadix2 = /[^01]/;
const invalidRadix8 = /[^0-7]/;
const invalidRadix10 = /[^0-9]/;
function isValid(s, radix) {
const res = parseRadix.exec(s);
if (res != null) {
if (radix == null) {
switch (res[2]) {
case "0b":
radix = 2;
break;
case "0o":
radix = 8;
break;
case "0x":
radix = 16;
break;
default:
radix = 10;
break;
}
}
switch (radix) {
case 2:
return invalidRadix2.test(res[3]) ? null : [res, 2];
case 8:
return invalidRadix8.test(res[3]) ? null : [res, 8];
case 10:
return invalidRadix10.test(res[3]) ? null : [res, 10];
case 16:
return [res, 16];
default:
throw new Error("Invalid Base.");
}
}
return null;
}
// TODO does this perfectly match the .NET behavior ?
function tryParse(s, radix, initial) {
const a = isValid(s, radix);
if (a !== null) {
const [[, prefix,, digits], radix_] = a;
const v = parseInt((prefix || "") + digits, radix_);
if (!Number.isNaN(v)) {
return [true, v];
}
}
return [false, initial];
}
function parse(s, radix) {
const a = tryParse(s, radix, 0);
if (a[0]) {
return a[1];
} else {
throw new Error("Input string was not in a correct format.");
}
}
+147
View File
@@ -0,0 +1,147 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ofArray = undefined;
exports.append = append;
exports.choose = choose;
exports.collect = collect;
exports.concat = concat;
exports.filter = filter;
exports.where = where;
exports.initialize = initialize;
exports.map = map;
exports.mapIndexed = mapIndexed;
exports.indexed = indexed;
exports.partition = partition;
exports.replicate = replicate;
exports.reverse = reverse;
exports.singleton = singleton;
exports.slice = slice;
exports.unzip = unzip;
exports.unzip3 = unzip3;
exports.groupBy = groupBy;
exports.splitAt = splitAt;
exports.head = head;
exports.tail = tail;
var _ListClass = require("./ListClass");
var _ListClass2 = _interopRequireDefault(_ListClass);
var _Map = require("./Map");
var _Option = require("./Option");
var _Seq = require("./Seq");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _ListClass2.default;
exports.ofArray = _ListClass.ofArray;
function append(xs, ys) {
return (0, _Seq.fold)((acc, x) => new _ListClass2.default(x, acc), ys, reverse(xs));
}
function choose(f, xs) {
const r = (0, _Seq.fold)((acc, x) => {
const y = f(x);
return y != null ? new _ListClass2.default((0, _Option.getValue)(y), acc) : acc;
}, new _ListClass2.default(), xs);
return reverse(r);
}
function collect(f, xs) {
return (0, _Seq.fold)((acc, x) => append(acc, f(x)), new _ListClass2.default(), xs);
}
// TODO: should be xs: Iterable<List<T>>
function concat(xs) {
return collect(x => x, xs);
}
function filter(f, xs) {
return reverse((0, _Seq.fold)((acc, x) => f(x) ? new _ListClass2.default(x, acc) : acc, new _ListClass2.default(), xs));
}
function where(f, xs) {
return filter(f, xs);
}
function initialize(n, f) {
if (n < 0) {
throw new Error("List length must be non-negative");
}
let xs = new _ListClass2.default();
for (let i = 1; i <= n; i++) {
xs = new _ListClass2.default(f(n - i), xs);
}
return xs;
}
function map(f, xs) {
return reverse((0, _Seq.fold)((acc, x) => new _ListClass2.default(f(x), acc), new _ListClass2.default(), xs));
}
function mapIndexed(f, xs) {
return reverse((0, _Seq.fold)((acc, x, i) => new _ListClass2.default(f(i, x), acc), new _ListClass2.default(), xs));
}
function indexed(xs) {
return mapIndexed((i, x) => [i, x], xs);
}
function partition(f, xs) {
return (0, _Seq.fold)((acc, x) => {
const lacc = acc[0];
const racc = acc[1];
return f(x) ? [new _ListClass2.default(x, lacc), racc] : [lacc, new _ListClass2.default(x, racc)];
}, [new _ListClass2.default(), new _ListClass2.default()], reverse(xs));
}
function replicate(n, x) {
return initialize(n, () => x);
}
function reverse(xs) {
return (0, _Seq.fold)((acc, x) => new _ListClass2.default(x, acc), new _ListClass2.default(), xs);
}
function singleton(x) {
return new _ListClass2.default(x, new _ListClass2.default());
}
function slice(lower, upper, xs) {
const noLower = lower == null;
const noUpper = upper == null;
return reverse((0, _Seq.fold)((acc, x, i) => (noLower || lower <= i) && (noUpper || i <= upper) ? new _ListClass2.default(x, acc) : acc, new _ListClass2.default(), xs));
}
/* ToDo: instance unzip() */
function unzip(xs) {
return (0, _Seq.foldBack)((xy, acc) => [new _ListClass2.default(xy[0], acc[0]), new _ListClass2.default(xy[1], acc[1])], xs, [new _ListClass2.default(), new _ListClass2.default()]);
}
/* ToDo: instance unzip3() */
function unzip3(xs) {
return (0, _Seq.foldBack)((xyz, acc) => [new _ListClass2.default(xyz[0], acc[0]), new _ListClass2.default(xyz[1], acc[1]), new _ListClass2.default(xyz[2], acc[2])], xs, [new _ListClass2.default(), new _ListClass2.default(), new _ListClass2.default()]);
}
function groupBy(f, xs) {
return (0, _Seq.toList)((0, _Seq.map)(k => [k[0], (0, _Seq.toList)(k[1])], (0, _Map.groupBy)(f, xs)));
}
function splitAt(index, xs) {
if (index < 0) {
throw new Error("The input must be non-negative.");
}
let i = 0;
let last = xs;
const first = new Array(index);
while (i < index) {
if (last.tail == null) {
throw new Error("The input sequence has an insufficient number of elements.");
}
first[i] = last.head;
last = last.tail;
i++;
}
return [(0, _ListClass.ofArray)(first), last];
}
function head(xs) {
if (xs.head !== undefined) {
return xs.head;
} else {
throw new Error("The input list was empty.");
}
}
function tail(xs) {
if (xs.tail !== undefined) {
return xs.tail;
} else {
throw new Error("The input list was empty.");
}
}
+124
View File
@@ -0,0 +1,124 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ofArray = ofArray;
var _Symbol = require("./Symbol");
var _Symbol2 = _interopRequireDefault(_Symbol);
var _Util = require("./Util");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// This module is split from List.ts to prevent cyclic dependencies
function ofArray(args, base) {
let acc = base || new List();
for (let i = args.length - 1; i >= 0; i--) {
acc = new List(args[i], acc);
}
return acc;
}
class List {
constructor(head, tail) {
this.head = head;
this.tail = tail;
}
ToString() {
return "[" + Array.from(this).map(x => (0, _Util.toString)(x)).join("; ") + "]";
}
Equals(other) {
// Optimization if they are referencially equal
if (this === other) {
return true;
} else {
let cur1 = this;
let cur2 = other;
while ((0, _Util.equals)(cur1.head, cur2.head)) {
cur1 = cur1.tail;
cur2 = cur2.tail;
if (cur1 == null) {
return cur2 == null;
}
}
return false;
}
}
CompareTo(other) {
// Optimization if they are referencially equal
if (this === other) {
return 0;
} else {
let cur1 = this;
let cur2 = other;
let res = (0, _Util.compare)(cur1.head, cur2.head);
while (res === 0) {
cur1 = cur1.tail;
cur2 = cur2.tail;
if (cur1 == null) {
return cur2 == null ? 0 : -1;
}
res = (0, _Util.compare)(cur1.head, cur2.head);
}
return res;
}
}
get length() {
let cur = this;
let acc = 0;
while (cur.tail != null) {
cur = cur.tail;
acc++;
}
return acc;
}
[Symbol.iterator]() {
let cur = this;
return {
next: () => {
const tmp = cur;
cur = cur.tail;
return { done: tmp.tail == null, value: tmp.head };
}
};
}
// append(ys: List<T>): List<T> {
// return append(this, ys);
// }
// choose<U>(f: (x: T) => U, xs: List<T>): List<U> {
// return choose(f, this);
// }
// collect<U>(f: (x: T) => List<U>): List<U> {
// return collect(f, this);
// }
// filter(f: (x: T) => boolean): List<T> {
// return filter(f, this);
// }
// where(f: (x: T) => boolean): List<T> {
// return filter(f, this);
// }
// map<U>(f: (x: T) => U): List<U> {
// return map(f, this);
// }
// mapIndexed<U>(f: (i: number, x: T) => U): List<U> {
// return mapIndexed(f, this);
// }
// partition(f: (x: T) => boolean): [List<T>, List<T>] {
// return partition(f, this) as [List<T>, List<T>];
// }
// reverse(): List<T> {
// return reverse(this);
// }
// slice(lower: number, upper: number): List<T> {
// return slice(lower, upper, this);
// }
[_Symbol2.default.reflection]() {
return {
type: "Microsoft.FSharp.Collections.FSharpList",
interfaces: ["System.IEquatable", "System.IComparable"]
};
}
}
exports.default = List;
+594
View File
@@ -0,0 +1,594 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MapTree = undefined;
exports.groupBy = groupBy;
exports.countBy = countBy;
exports.create = create;
exports.add = add;
exports.remove = remove;
exports.containsValue = containsValue;
exports.tryGetValue = tryGetValue;
exports.exists = exists;
exports.find = find;
exports.tryFind = tryFind;
exports.filter = filter;
exports.fold = fold;
exports.foldBack = foldBack;
exports.forAll = forAll;
exports.isEmpty = isEmpty;
exports.iterate = iterate;
exports.map = map;
exports.partition = partition;
exports.findKey = findKey;
exports.tryFindKey = tryFindKey;
exports.pick = pick;
exports.tryPick = tryPick;
var _Comparer = require("./Comparer");
var _Comparer2 = _interopRequireDefault(_Comparer);
var _ListClass = require("./ListClass");
var _ListClass2 = _interopRequireDefault(_ListClass);
var _Option = require("./Option");
var _Seq = require("./Seq");
var _Symbol = require("./Symbol");
var _Symbol2 = _interopRequireDefault(_Symbol);
var _Util = require("./Util");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// ----------------------------------------------
// These functions belong to Seq.ts but are
// implemented here to prevent cyclic dependencies
function groupBy(f, xs) {
const keys = [];
const iter = xs[Symbol.iterator]();
let acc = create();
let cur = iter.next();
while (!cur.done) {
const k = f(cur.value);
const vs = tryFind(k, acc);
if (vs == null) {
keys.push(k);
acc = add(k, [cur.value], acc);
} else {
(0, _Option.getValue)(vs).push(cur.value);
}
cur = iter.next();
}
return keys.map(k => [k, acc.get(k)]);
}
function countBy(f, xs) {
return groupBy(f, xs).map(kv => [kv[0], kv[1].length]);
}
class MapTree {
constructor(tag, data) {
this.tag = tag | 0;
this.data = data;
}
}
exports.MapTree = MapTree;
function tree_sizeAux(acc, m) {
sizeAux: while (true) {
if (m.tag === 1) {
return acc + 1 | 0;
} else if (m.tag === 2) {
acc = tree_sizeAux(acc + 1, m.data[2]);
m = m.data[3];
continue sizeAux;
} else {
return acc | 0;
}
}
}
function tree_size(x) {
return tree_sizeAux(0, x);
}
function tree_empty() {
return new MapTree(0);
}
function tree_height(_arg1) {
return _arg1.tag === 1 ? 1 : _arg1.tag === 2 ? _arg1.data[4] : 0;
}
function tree_isEmpty(m) {
return m.tag === 0 ? true : false;
}
function tree_mk(l, k, v, r) {
const matchValue = l.tag === 0 ? r.tag === 0 ? 0 : 1 : 1;
switch (matchValue) {
case 0:
return new MapTree(1, [k, v]);
case 1:
const hl = tree_height(l) | 0;
const hr = tree_height(r) | 0;
const m = (hl < hr ? hr : hl) | 0;
return new MapTree(2, [k, v, l, r, m + 1]);
}
throw new Error("internal error: Map.tree_mk");
}
function tree_rebalance(t1, k, v, t2) {
const t1h = tree_height(t1);
const t2h = tree_height(t2);
if (t2h > t1h + 2) {
if (t2.tag === 2) {
if (tree_height(t2.data[2]) > t1h + 1) {
if (t2.data[2].tag === 2) {
return tree_mk(tree_mk(t1, k, v, t2.data[2].data[2]), t2.data[2].data[0], t2.data[2].data[1], tree_mk(t2.data[2].data[3], t2.data[0], t2.data[1], t2.data[3]));
} else {
throw new Error("rebalance");
}
} else {
return tree_mk(tree_mk(t1, k, v, t2.data[2]), t2.data[0], t2.data[1], t2.data[3]);
}
} else {
throw new Error("rebalance");
}
} else {
if (t1h > t2h + 2) {
if (t1.tag === 2) {
if (tree_height(t1.data[3]) > t2h + 1) {
if (t1.data[3].tag === 2) {
return tree_mk(tree_mk(t1.data[2], t1.data[0], t1.data[1], t1.data[3].data[2]), t1.data[3].data[0], t1.data[3].data[1], tree_mk(t1.data[3].data[3], k, v, t2));
} else {
throw new Error("rebalance");
}
} else {
return tree_mk(t1.data[2], t1.data[0], t1.data[1], tree_mk(t1.data[3], k, v, t2));
}
} else {
throw new Error("rebalance");
}
} else {
return tree_mk(t1, k, v, t2);
}
}
}
function tree_add(comparer, k, v, m) {
if (m.tag === 1) {
const c = comparer.Compare(k, m.data[0]);
if (c < 0) {
return new MapTree(2, [k, v, new MapTree(0), m, 2]);
} else if (c === 0) {
return new MapTree(1, [k, v]);
}
return new MapTree(2, [k, v, m, new MapTree(0), 2]);
} else if (m.tag === 2) {
const c = comparer.Compare(k, m.data[0]);
if (c < 0) {
return tree_rebalance(tree_add(comparer, k, v, m.data[2]), m.data[0], m.data[1], m.data[3]);
} else if (c === 0) {
return new MapTree(2, [k, v, m.data[2], m.data[3], m.data[4]]);
}
return tree_rebalance(m.data[2], m.data[0], m.data[1], tree_add(comparer, k, v, m.data[3]));
}
return new MapTree(1, [k, v]);
}
function tree_find(comparer, k, m) {
const res = tree_tryFind(comparer, k, m);
if (res == null) {
throw new Error("key not found: " + k);
}
return (0, _Option.getValue)(res);
}
function tree_tryFind(comparer, k, m) {
tryFind: while (true) {
if (m.tag === 1) {
const c = comparer.Compare(k, m.data[0]) | 0;
if (c === 0) {
return (0, _Option.makeSome)(m.data[1]);
} else {
return null;
}
} else if (m.tag === 2) {
const c_1 = comparer.Compare(k, m.data[0]) | 0;
if (c_1 < 0) {
comparer = comparer;
k = k;
m = m.data[2];
continue tryFind;
} else if (c_1 === 0) {
return (0, _Option.makeSome)(m.data[1]);
} else {
comparer = comparer;
k = k;
m = m.data[3];
continue tryFind;
}
} else {
return null;
}
}
}
function tree_partition1(comparer, f, k, v, acc1, acc2) {
return f(k, v) ? [tree_add(comparer, k, v, acc1), acc2] : [acc1, tree_add(comparer, k, v, acc2)];
}
function tree_partitionAux(comparer, f, s, acc_0, acc_1) {
const acc = [acc_0, acc_1];
if (s.tag === 1) {
return tree_partition1(comparer, f, s.data[0], s.data[1], acc[0], acc[1]);
} else if (s.tag === 2) {
const acc_2 = tree_partitionAux(comparer, f, s.data[3], acc[0], acc[1]);
const acc_3 = tree_partition1(comparer, f, s.data[0], s.data[1], acc_2[0], acc_2[1]);
return tree_partitionAux(comparer, f, s.data[2], acc_3[0], acc_3[1]);
}
return acc;
}
function tree_partition(comparer, f, s) {
return tree_partitionAux(comparer, f, s, tree_empty(), tree_empty());
}
function tree_filter1(comparer, f, k, v, acc) {
return f(k, v) ? tree_add(comparer, k, v, acc) : acc;
}
function tree_filterAux(comparer, f, s, acc) {
return s.tag === 1 ? tree_filter1(comparer, f, s.data[0], s.data[1], acc) : s.tag === 2 ? tree_filterAux(comparer, f, s.data[3], tree_filter1(comparer, f, s.data[0], s.data[1], tree_filterAux(comparer, f, s.data[2], acc))) : acc;
}
function tree_filter(comparer, f, s) {
return tree_filterAux(comparer, f, s, tree_empty());
}
function tree_spliceOutSuccessor(m) {
if (m.tag === 1) {
return [m.data[0], m.data[1], new MapTree(0)];
} else if (m.tag === 2) {
if (m.data[2].tag === 0) {
return [m.data[0], m.data[1], m.data[3]];
} else {
const kvl = tree_spliceOutSuccessor(m.data[2]);
return [kvl[0], kvl[1], tree_mk(kvl[2], m.data[0], m.data[1], m.data[3])];
}
}
throw new Error("internal error: Map.spliceOutSuccessor");
}
function tree_remove(comparer, k, m) {
if (m.tag === 1) {
const c = comparer.Compare(k, m.data[0]);
if (c === 0) {
return new MapTree(0);
} else {
return m;
}
} else if (m.tag === 2) {
const c = comparer.Compare(k, m.data[0]);
if (c < 0) {
return tree_rebalance(tree_remove(comparer, k, m.data[2]), m.data[0], m.data[1], m.data[3]);
} else if (c === 0) {
if (m.data[2].tag === 0) {
return m.data[3];
} else {
if (m.data[3].tag === 0) {
return m.data[2];
} else {
const input = tree_spliceOutSuccessor(m.data[3]);
return tree_mk(m.data[2], input[0], input[1], input[2]);
}
}
} else {
return tree_rebalance(m.data[2], m.data[0], m.data[1], tree_remove(comparer, k, m.data[3]));
}
} else {
return tree_empty();
}
}
function tree_mem(comparer, k, m) {
mem: while (true) {
if (m.tag === 1) {
return comparer.Compare(k, m.data[0]) === 0;
} else if (m.tag === 2) {
const c = comparer.Compare(k, m.data[0]) | 0;
if (c < 0) {
comparer = comparer;
k = k;
m = m.data[2];
continue mem;
} else if (c === 0) {
return true;
} else {
comparer = comparer;
k = k;
m = m.data[3];
continue mem;
}
} else {
return false;
}
}
}
function tree_iter(f, m) {
if (m.tag === 1) {
f(m.data[0], m.data[1]);
} else if (m.tag === 2) {
tree_iter(f, m.data[2]);
f(m.data[0], m.data[1]);
tree_iter(f, m.data[3]);
}
}
function tree_tryPick(f, m) {
if (m.tag === 1) {
return f(m.data[0], m.data[1]);
} else if (m.tag === 2) {
const matchValue = tree_tryPick(f, m.data[2]);
if (matchValue == null) {
const matchValue_1 = f(m.data[0], m.data[1]);
if (matchValue_1 == null) {
return tree_tryPick(f, m.data[3]);
} else {
const res = matchValue_1;
return res;
}
} else {
return matchValue;
}
} else {
return null;
}
}
function tree_exists(f, m) {
return m.tag === 1 ? f(m.data[0], m.data[1]) : m.tag === 2 ? (tree_exists(f, m.data[2]) ? true : f(m.data[0], m.data[1])) ? true : tree_exists(f, m.data[3]) : false;
}
function tree_forall(f, m) {
return m.tag === 1 ? f(m.data[0], m.data[1]) : m.tag === 2 ? (tree_forall(f, m.data[2]) ? f(m.data[0], m.data[1]) : false) ? tree_forall(f, m.data[3]) : false : true;
}
function tree_mapi(f, m) {
return m.tag === 1 ? new MapTree(1, [m.data[0], f(m.data[0], m.data[1])]) : m.tag === 2 ? new MapTree(2, [m.data[0], f(m.data[0], m.data[1]), tree_mapi(f, m.data[2]), tree_mapi(f, m.data[3]), m.data[4]]) : tree_empty();
}
function tree_foldBack(f, m, x) {
return m.tag === 1 ? f(m.data[0], m.data[1], x) : m.tag === 2 ? tree_foldBack(f, m.data[2], f(m.data[0], m.data[1], tree_foldBack(f, m.data[3], x))) : x;
}
function tree_fold(f, x, m) {
return m.tag === 1 ? f(x, m.data[0], m.data[1]) : m.tag === 2 ? tree_fold(f, f(tree_fold(f, x, m.data[2]), m.data[0], m.data[1]), m.data[3]) : x;
}
// function tree_foldFromTo(
// comparer: IComparer<any>, lo: any, hi: any,
// f: (k:any, v: any, acc: any) => any, m: MapTree, x: any): any {
// if (m.tag === 1) {
// var cLoKey = comparer.Compare(lo, m.data[0]);
// var cKeyHi = comparer.Compare(m.data[0], hi);
// var x_1 = (cLoKey <= 0 ? cKeyHi <= 0 : false) ? f(m.data[0], m.data[1], x) : x;
// return x_1;
// } else if (m.tag === 2) {
// var cLoKey = comparer.Compare(lo, m.data[0]);
// var cKeyHi = comparer.Compare(m.data[0], hi);
// var x_1 = cLoKey < 0 ? tree_foldFromTo(comparer, lo, hi, f, m.data[2], x) : x;
// var x_2 = (cLoKey <= 0 ? cKeyHi <= 0 : false) ? f(m.data[0], m.data[1], x_1) : x_1;
// var x_3 = cKeyHi < 0 ? tree_foldFromTo(comparer, lo, hi, f, m.data[3], x_2) : x_2;
// return x_3;
// }
// return x;
// }
// function tree_foldSection(
// comparer: IComparer<any>, lo: any, hi: any,
// f: (k: any, v: any, acc: any) => any, m: MapTree, x: any) {
// return comparer.Compare(lo, hi) === 1 ? x : tree_foldFromTo(comparer, lo, hi, f, m, x);
// }
// function tree_loop(m: MapTree, acc: any): List<[any,any]> {
// return m.tag === 1
// ? new List([m.data[0], m.data[1]], acc)
// : m.tag === 2
// ? tree_loop(m.data[2], new List([m.data[0], m.data[1]], tree_loop(m.data[3], acc)))
// : acc;
// }
// function tree_toList(m: MapTree) {
// return tree_loop(m, new List());
// }
// function tree_toArray(m: MapTree) {
// return Array.from(tree_toList(m));
// }
// function tree_ofList(comparer: IComparer<any>, l: List<[any,any]>) {
// return Seq.fold((acc: MapTree, tupledArg: [any, any]) => {
// return tree_add(comparer, tupledArg[0], tupledArg[1], acc);
// }, tree_empty(), l);
// }
function tree_mkFromEnumerator(comparer, acc, e) {
let cur = e.next();
while (!cur.done) {
acc = tree_add(comparer, cur.value[0], cur.value[1], acc);
cur = e.next();
}
return acc;
}
// function tree_ofArray(comparer: IComparer<any>, arr: ArrayLike<[any,any]>) {
// var res = tree_empty();
// for (var i = 0; i <= arr.length - 1; i++) {
// res = tree_add(comparer, arr[i][0], arr[i][1], res);
// }
// return res;
// }
function tree_ofSeq(comparer, c) {
const ie = c[Symbol.iterator]();
return tree_mkFromEnumerator(comparer, tree_empty(), ie);
}
// function tree_copyToArray(s: MapTree, arr: ArrayLike<any>, i: number) {
// tree_iter((x, y) => { arr[i++] = [x, y]; }, s);
// }
function tree_collapseLHS(stack) {
if (stack.tail != null) {
if (stack.head.tag === 1) {
return stack;
} else if (stack.head.tag === 2) {
return tree_collapseLHS((0, _ListClass.ofArray)([stack.head.data[2], new MapTree(1, [stack.head.data[0], stack.head.data[1]]), stack.head.data[3]], stack.tail));
} else {
return tree_collapseLHS(stack.tail);
}
} else {
return new _ListClass2.default();
}
}
function tree_mkIterator(s) {
return { stack: tree_collapseLHS(new _ListClass2.default(s, new _ListClass2.default())), started: false };
}
function tree_moveNext(i) {
function current(it) {
if (it.stack.tail == null) {
return null;
} else if (it.stack.head.tag === 1) {
return [it.stack.head.data[0], it.stack.head.data[1]];
}
throw new Error("Please report error: Map iterator, unexpected stack for current");
}
if (i.started) {
if (i.stack.tail == null) {
return { done: true, value: null };
} else {
if (i.stack.head.tag === 1) {
i.stack = tree_collapseLHS(i.stack.tail);
return {
done: i.stack.tail == null,
value: current(i)
};
} else {
throw new Error("Please report error: Map iterator, unexpected stack for moveNext");
}
}
} else {
i.started = true;
return {
done: i.stack.tail == null,
value: current(i)
};
}
}
class FableMap {
/** Do not call, use Map.create instead. */
constructor() {
return;
}
ToString() {
return "map [" + Array.from(this).map(x => (0, _Util.toString)(x)).join("; ") + "]";
}
Equals(m2) {
return this.CompareTo(m2) === 0;
}
CompareTo(m2) {
return this === m2 ? 0 : (0, _Seq.compareWith)((kvp1, kvp2) => {
const c = this.comparer.Compare(kvp1[0], kvp2[0]);
return c !== 0 ? c : (0, _Util.compare)(kvp1[1], kvp2[1]);
}, this, m2);
}
[Symbol.iterator]() {
const i = tree_mkIterator(this.tree);
return {
next: () => tree_moveNext(i)
};
}
entries() {
return this[Symbol.iterator]();
}
keys() {
return (0, _Seq.map)(kv => kv[0], this);
}
values() {
return (0, _Seq.map)(kv => kv[1], this);
}
get(k) {
return tree_find(this.comparer, k, this.tree);
}
has(k) {
return tree_mem(this.comparer, k, this.tree);
}
/** Mutating method */
set(k, v) {
this.tree = tree_add(this.comparer, k, v, this.tree);
}
/** Mutating method */
delete(k) {
// TODO: Is calculating the size twice is more performant than calling tree_mem?
const oldSize = tree_size(this.tree);
this.tree = tree_remove(this.comparer, k, this.tree);
return oldSize > tree_size(this.tree);
}
/** Mutating method */
clear() {
this.tree = tree_empty();
}
get size() {
return tree_size(this.tree);
}
[_Symbol2.default.reflection]() {
return {
type: "Microsoft.FSharp.Collections.FSharpMap",
interfaces: ["System.IEquatable", "System.IComparable", "System.Collections.Generic.IDictionary"]
};
}
}
exports.default = FableMap;
function from(comparer, tree) {
const map = new FableMap();
map.tree = tree;
map.comparer = comparer || new _Comparer2.default();
return map;
}
function create(ie, comparer) {
comparer = comparer || new _Comparer2.default();
return from(comparer, ie ? tree_ofSeq(comparer, ie) : tree_empty());
}
function add(k, v, map) {
return from(map.comparer, tree_add(map.comparer, k, v, map.tree));
}
function remove(item, map) {
return from(map.comparer, tree_remove(map.comparer, item, map.tree));
}
function containsValue(v, map) {
return (0, _Seq.fold)((acc, k) => acc || (0, _Util.equals)(map.get(k), v), false, map.keys());
}
function tryGetValue(map, key, defaultValue) {
return map.has(key) ? [true, map.get(key)] : [false, defaultValue];
}
function exists(f, map) {
return tree_exists(f, map.tree);
}
function find(k, map) {
return tree_find(map.comparer, k, map.tree);
}
function tryFind(k, map) {
return tree_tryFind(map.comparer, k, map.tree);
}
function filter(f, map) {
return from(map.comparer, tree_filter(map.comparer, f, map.tree));
}
function fold(f, seed, map) {
return tree_fold(f, seed, map.tree);
}
function foldBack(f, map, seed) {
return tree_foldBack(f, map.tree, seed);
}
function forAll(f, map) {
return tree_forall(f, map.tree);
}
function isEmpty(map) {
return tree_isEmpty(map.tree);
}
function iterate(f, map) {
tree_iter(f, map.tree);
}
function map(f, map) {
return from(map.comparer, tree_mapi(f, map.tree));
}
function partition(f, map) {
const rs = tree_partition(map.comparer, f, map.tree);
return [from(map.comparer, rs[0]), from(map.comparer, rs[1])];
}
function findKey(f, map) {
return (0, _Seq.pick)(kv => f(kv[0], kv[1]) ? (0, _Option.makeSome)(kv[0]) : null, map);
}
function tryFindKey(f, map) {
return (0, _Seq.tryPick)(kv => f(kv[0], kv[1]) ? (0, _Option.makeSome)(kv[0]) : null, map);
}
function pick(f, map) {
const res = tryPick(f, map);
if (res != null) {
return (0, _Option.getValue)(res);
}
throw new Error("key not found");
}
function tryPick(f, map) {
return tree_tryPick(f, map.tree);
}
+60
View File
@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Some = undefined;
exports.makeSome = makeSome;
exports.getValue = getValue;
exports.defaultArg = defaultArg;
exports.defaultArgWith = defaultArgWith;
exports.filter = filter;
var _Util = require("./Util");
class Some {
constructor(value) {
this.value = value;
}
// We don't prefix it with "Some" for consistency with erased options
ToString() {
return (0, _Util.toString)(this.value);
}
Equals(other) {
if (other == null) {
return false;
} else {
return (0, _Util.equals)(this.value, other instanceof Some ? other.value : other);
}
}
CompareTo(other) {
if (other == null) {
return 1;
} else {
return (0, _Util.compare)(this.value, other instanceof Some ? other.value : other);
}
}
}
exports.Some = Some;
function makeSome(x) {
return x == null || x instanceof Some ? new Some(x) : x;
}
function getValue(x, acceptNull) {
if (x == null) {
if (!acceptNull) {
throw new Error("Option has no value");
}
return null;
} else {
return x instanceof Some ? x.value : x;
}
}
function defaultArg(arg, defaultValue, f) {
return arg == null ? defaultValue : f != null ? f(getValue(arg)) : getValue(arg);
}
function defaultArgWith(arg, defThunk) {
return arg == null ? defThunk() : getValue(arg);
}
function filter(predicate, arg) {
return arg != null ? !predicate(getValue(arg)) ? null : arg : arg;
}
+221
View File
@@ -0,0 +1,221 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MemberInfo = undefined;
exports.resolveGeneric = resolveGeneric;
exports.getType = getType;
exports.getTypeFullName = getTypeFullName;
exports.getName = getName;
exports.getPrototypeOfType = getPrototypeOfType;
exports.getProperties = getProperties;
exports.getUnionCases = getUnionCases;
exports.getPropertyValues = getPropertyValues;
exports.getUnionFields = getUnionFields;
exports.makeUnion = makeUnion;
exports.getTupleElements = getTupleElements;
exports.isTupleType = isTupleType;
exports.getFunctionElements = getFunctionElements;
exports.isFunctionType = isFunctionType;
exports.getGenericArguments = getGenericArguments;
var _List = require("./List");
var _List2 = _interopRequireDefault(_List);
var _Symbol = require("./Symbol");
var _Symbol2 = _interopRequireDefault(_Symbol);
var _Util = require("./Util");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class MemberInfo {
constructor(name, index, declaringType, propertyType, unionFields) {
this.name = name;
this.index = index;
this.declaringType = declaringType;
this.propertyType = propertyType;
this.unionFields = unionFields;
}
getUnionFields() {
return this.unionFields.map((fi, i) => new MemberInfo("unknown", i, this.declaringType, fi));
}
}
exports.MemberInfo = MemberInfo;
function resolveGeneric(idx, enclosing) {
try {
const t = enclosing.head;
if (t.generics == null) {
return resolveGeneric(idx, enclosing.tail);
} else {
const name = typeof idx === "string" ? idx : Object.getOwnPropertyNames(t.generics)[idx];
const resolved = t.generics[name];
if (resolved == null) {
return resolveGeneric(idx, enclosing.tail);
} else if (resolved instanceof _Util.NonDeclaredType && resolved.kind === "GenericParam") {
return resolveGeneric(resolved.definition, enclosing.tail);
} else {
return new _List2.default(resolved, enclosing);
}
}
} catch (err) {
throw new Error(`Cannot resolve generic argument ${idx}: ${err}`);
}
}
function getType(obj) {
const t = typeof obj;
switch (t) {
case "boolean":
case "number":
case "string":
case "function":
return t;
default:
return Object.getPrototypeOf(obj).constructor;
}
}
// TODO: This needs improvement, check namespace for non-custom types?
function getTypeFullName(typ, option) {
function trim(fullName, opt) {
if (typeof fullName !== "string") {
return "unknown";
}
if (opt === "name") {
const i = fullName.lastIndexOf(".");
return fullName.substr(i + 1);
}
if (opt === "namespace") {
const i = fullName.lastIndexOf(".");
return i > -1 ? fullName.substr(0, i) : "";
}
return fullName;
}
if (typeof typ === "string") {
return typ;
} else if (typ instanceof _Util.NonDeclaredType) {
switch (typ.kind) {
case "Unit":
return "unit";
case "Option":
return getTypeFullName(typ.generics[0], option) + " option";
case "Array":
return getTypeFullName(typ.generics[0], option) + "[]";
case "Tuple":
return typ.generics.map(x => getTypeFullName(x, option)).join(" * ");
case "Function":
return "Func<" + typ.generics.map(x => getTypeFullName(x, option)).join(", ") + ">";
case "GenericParam":
case "Interface":
return typ.definition;
case "GenericType":
return getTypeFullName(typ.definition, option);
case "Any":
default:
return "unknown";
}
} else {
// Attention: this doesn't work with Object.getPrototypeOf
const proto = typ.prototype;
return trim(typeof proto[_Symbol2.default.reflection] === "function" ? proto[_Symbol2.default.reflection]().type : null, option);
}
}
function getName(x) {
if (x instanceof MemberInfo) {
return x.name;
}
return getTypeFullName(x, "name");
}
function getPrototypeOfType(typ) {
if (typeof typ === "string") {
return null;
} else if (typ instanceof _Util.NonDeclaredType) {
return typ.kind === "GenericType" ? typ.definition.prototype : null;
} else {
return typ.prototype;
}
}
function getProperties(typ) {
const proto = getPrototypeOfType(typ);
if (proto != null && typeof proto[_Symbol2.default.reflection] === "function") {
const info = proto[_Symbol2.default.reflection]();
if (info.properties) {
return Object.getOwnPropertyNames(info.properties).map((k, i) => new MemberInfo(k, i, typ, info.properties[k]));
}
}
throw new Error("Type " + getTypeFullName(typ) + " doesn't contain property info.");
}
function getUnionCases(typ) {
const proto = getPrototypeOfType(typ);
if (proto != null && typeof proto[_Symbol2.default.reflection] === "function") {
const info = proto[_Symbol2.default.reflection]();
if (info.cases) {
return info.cases.map((uci, i) => new MemberInfo(uci[0], i, typ, null, uci.slice(1)));
}
}
throw new Error("Type " + getTypeFullName(typ) + " doesn't contain union case info.");
}
function getPropertyValues(obj) {
return (0, _Util.getPropertyNames)(obj).map(k => obj[k]);
}
function getUnionFields(obj, typ) {
if (obj != null && typeof obj[_Symbol2.default.reflection] === "function") {
const info = obj[_Symbol2.default.reflection]();
if (info.cases) {
const uci = info.cases[obj.tag];
if (uci != null) {
const fields = uci.length > 2 ? obj.data : uci.length > 1 ? [obj.data] : [];
return [new MemberInfo(uci[0], obj.tag, typ, null, uci.slice(1)), fields];
}
}
}
throw new Error("Not an F# union type.");
}
function makeUnion(caseInfo, args) {
const Cons = (0, _Util.getDefinition)(caseInfo.declaringType);
switch (args.length) {
case 0:
return new Cons(caseInfo.index);
case 1:
return new Cons(caseInfo.index, args[0]);
default:
return new Cons(caseInfo.index, args);
}
}
function getTupleElements(typ) {
if (typ instanceof _Util.NonDeclaredType && typ.kind === "Tuple") {
return typ.generics;
}
throw new Error("Type " + getTypeFullName(typ) + " is not a tuple type.");
}
function isTupleType(typ) {
if (typ instanceof _Util.NonDeclaredType) {
return typ.kind === "Tuple";
}
return false;
}
function getFunctionElements(typ) {
if (typ === "function") {
throw new Error("The type of the function must be known at compile time to get the elements.");
}
if (typ instanceof _Util.NonDeclaredType && typ.kind === "Function") {
return typ.generics;
}
throw new Error("Type " + getTypeFullName(typ) + " is not a function type.");
}
function isFunctionType(typ) {
return typ === "function" || typ instanceof _Util.NonDeclaredType && typ.kind === "Function";
}
function getGenericArguments(typ) {
if (typ instanceof _Util.NonDeclaredType) {
if (Array.isArray(typ.generics)) {
return typ.generics;
} else {
const dic = typ.generics;
return Object.keys(dic).map(k => dic[k]);
}
}
return [];
}
+106
View File
@@ -0,0 +1,106 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.create = create;
exports.escape = escape;
exports.unescape = unescape;
exports.isMatch = isMatch;
exports.match = match;
exports.matches = matches;
exports.options = options;
exports.replace = replace;
exports.split = split;
function create(pattern, options) {
let flags = "g";
flags += options & 1 ? "i" : "";
flags += options & 2 ? "m" : "";
return new RegExp(pattern, flags);
}
// From http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
function escape(str) {
return str.replace(/[\-\[\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function unescape(str) {
return str.replace(/\\([\-\[\/\{\}\(\)\*\+\?\.\\\^\$\|])/g, "$1");
}
function isMatch(str, pattern, options = 0) {
let reg;
reg = str instanceof RegExp ? (reg = str, str = pattern, reg.lastIndex = options, reg) : reg = create(pattern, options);
return reg.test(str);
}
function match(str, pattern, options = 0) {
let reg;
reg = str instanceof RegExp ? (reg = str, str = pattern, reg.lastIndex = options, reg) : reg = create(pattern, options);
return reg.exec(str);
}
function matches(str, pattern, options = 0) {
let reg;
reg = str instanceof RegExp ? (reg = str, str = pattern, reg.lastIndex = options, reg) : reg = create(pattern, options);
if (!reg.global) {
throw new Error("Non-global RegExp"); // Prevent infinite loop
}
let m = reg.exec(str);
const matches = [];
while (m !== null) {
matches.push(m);
m = reg.exec(str);
}
return matches;
}
function options(reg) {
let options = 256; // ECMAScript
options |= reg.ignoreCase ? 1 : 0;
options |= reg.multiline ? 2 : 0;
return options;
}
function replace(reg, input, replacement, limit, offset = 0) {
function replacer() {
let res = arguments[0];
if (limit !== 0) {
limit--;
const match = [];
const len = arguments.length;
for (let i = 0; i < len - 2; i++) {
match.push(arguments[i]);
}
match.index = arguments[len - 2];
match.input = arguments[len - 1];
res = replacement(match);
}
return res;
}
if (typeof reg === "string") {
const tmp = reg;
reg = create(input, limit);
input = tmp;
limit = undefined;
}
if (typeof replacement === "function") {
limit = limit == null ? -1 : limit;
return input.substring(0, offset) + input.substring(offset).replace(reg, replacer);
} else {
// $0 doesn't work with JS regex, see #1155
replacement = replacement.replace(/\$0/g, s => "$&");
if (limit != null) {
let m;
const sub1 = input.substring(offset);
const _matches = matches(reg, sub1);
const sub2 = matches.length > limit ? (m = _matches[limit - 1], sub1.substring(0, m.index + m[0].length)) : sub1;
return input.substring(0, offset) + sub2.replace(reg, replacement) + input.substring(offset + sub2.length);
} else {
return input.replace(reg, replacement);
}
}
}
function split(reg, input, limit, offset = 0) {
if (typeof reg === "string") {
const tmp = reg;
reg = create(input, limit);
input = tmp;
limit = undefined;
}
input = input.substring(offset);
return input.split(reg, limit);
}
+803
View File
@@ -0,0 +1,803 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Enumerator = undefined;
exports.getEnumerator = getEnumerator;
exports.toIterator = toIterator;
exports.toList = toList;
exports.ofList = ofList;
exports.ofArray = ofArray;
exports.append = append;
exports.average = average;
exports.averageBy = averageBy;
exports.concat = concat;
exports.collect = collect;
exports.choose = choose;
exports.compareWith = compareWith;
exports.delay = delay;
exports.empty = empty;
exports.enumerateWhile = enumerateWhile;
exports.enumerateThenFinally = enumerateThenFinally;
exports.enumerateUsing = enumerateUsing;
exports.exactlyOne = exactlyOne;
exports.except = except;
exports.exists = exists;
exports.exists2 = exists2;
exports.filter = filter;
exports.where = where;
exports.fold = fold;
exports.foldBack = foldBack;
exports.fold2 = fold2;
exports.foldBack2 = foldBack2;
exports.forAll = forAll;
exports.forAll2 = forAll2;
exports.tryHead = tryHead;
exports.head = head;
exports.initialize = initialize;
exports.initializeInfinite = initializeInfinite;
exports.tryItem = tryItem;
exports.item = item;
exports.iterate = iterate;
exports.iterate2 = iterate2;
exports.iterateIndexed = iterateIndexed;
exports.iterateIndexed2 = iterateIndexed2;
exports.isEmpty = isEmpty;
exports.tryLast = tryLast;
exports.last = last;
exports.count = count;
exports.map = map;
exports.mapIndexed = mapIndexed;
exports.indexed = indexed;
exports.map2 = map2;
exports.mapIndexed2 = mapIndexed2;
exports.map3 = map3;
exports.chunkBySize = chunkBySize;
exports.mapFold = mapFold;
exports.mapFoldBack = mapFoldBack;
exports.max = max;
exports.maxBy = maxBy;
exports.min = min;
exports.minBy = minBy;
exports.pairwise = pairwise;
exports.permute = permute;
exports.rangeStep = rangeStep;
exports.rangeChar = rangeChar;
exports.range = range;
exports.readOnly = readOnly;
exports.reduce = reduce;
exports.reduceBack = reduceBack;
exports.replicate = replicate;
exports.reverse = reverse;
exports.scan = scan;
exports.scanBack = scanBack;
exports.singleton = singleton;
exports.skip = skip;
exports.skipWhile = skipWhile;
exports.sortWith = sortWith;
exports.sum = sum;
exports.sumBy = sumBy;
exports.tail = tail;
exports.take = take;
exports.truncate = truncate;
exports.takeWhile = takeWhile;
exports.tryFind = tryFind;
exports.find = find;
exports.tryFindBack = tryFindBack;
exports.findBack = findBack;
exports.tryFindIndex = tryFindIndex;
exports.findIndex = findIndex;
exports.tryFindIndexBack = tryFindIndexBack;
exports.findIndexBack = findIndexBack;
exports.tryPick = tryPick;
exports.pick = pick;
exports.unfold = unfold;
exports.zip = zip;
exports.zip3 = zip3;
var _Array = require("./Array");
var _ListClass = require("./ListClass");
var _ListClass2 = _interopRequireDefault(_ListClass);
var _Option = require("./Option");
var _Util = require("./Util");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class Enumerator {
constructor(iter) {
this.iter = iter;
}
MoveNext() {
const cur = this.iter.next();
this.current = cur.value;
return !cur.done;
}
get Current() {
return this.current;
}
get get_Current() {
return this.current;
}
Reset() {
throw new Error("JS iterators cannot be reset");
}
Dispose() {
return;
}
}
exports.Enumerator = Enumerator;
function getEnumerator(o) {
return typeof o.GetEnumerator === "function" ? o.GetEnumerator() : new Enumerator(o[Symbol.iterator]());
}
function toIterator(en) {
return {
next() {
return en.MoveNext() ? { done: false, value: en.Current } : { done: true, value: null };
}
};
}
function __failIfNone(res) {
if (res == null) {
throw new Error("Seq did not contain any matching element");
}
return (0, _Option.getValue)(res);
}
function toList(xs) {
return foldBack((x, acc) => new _ListClass2.default(x, acc), xs, new _ListClass2.default());
}
function ofList(xs) {
return delay(() => unfold(x => x.tail != null ? [x.head, x.tail] : null, xs));
}
function ofArray(xs) {
return delay(() => unfold(i => i < xs.length ? [xs[i], i + 1] : null, 0));
}
function append(xs, ys) {
return delay(() => {
let firstDone = false;
const i = xs[Symbol.iterator]();
let iters = [i, null];
return unfold(() => {
let cur;
if (!firstDone) {
cur = iters[0].next();
if (!cur.done) {
return [cur.value, iters];
} else {
firstDone = true;
iters = [null, ys[Symbol.iterator]()];
}
}
cur = iters[1].next();
return !cur.done ? [cur.value, iters] : null;
}, iters);
});
}
function average(xs) {
let count = 1;
const sum = reduce((acc, x) => {
count++;
return acc + x;
}, xs);
return sum / count;
}
function averageBy(f, xs) {
let count = 1;
const sum = reduce((acc, x) => {
count++;
return (count === 2 ? f(acc) : acc) + f(x);
}, xs);
return sum / count;
}
function concat(xs) {
return delay(() => {
const iter = xs[Symbol.iterator]();
let output = { value: null };
return unfold(innerIter => {
let hasFinished = false;
while (!hasFinished) {
if (innerIter == null) {
const cur = iter.next();
if (!cur.done) {
innerIter = cur.value[Symbol.iterator]();
} else {
hasFinished = true;
}
} else {
const cur = innerIter.next();
if (!cur.done) {
output = { value: cur.value };
hasFinished = true;
} else {
innerIter = null;
}
}
}
return innerIter != null && output != null ? [output.value, innerIter] : null;
}, null);
});
}
function collect(f, xs) {
return concat(map(f, xs));
}
function choose(f, xs) {
return delay(() => unfold(iter => {
let cur = iter.next();
while (!cur.done) {
const y = f(cur.value);
if (y != null) {
return [(0, _Option.getValue)(y), iter];
}
cur = iter.next();
}
return null;
}, xs[Symbol.iterator]()));
}
function compareWith(f, xs, ys) {
const nonZero = tryFind(i => i !== 0, map2((x, y) => f(x, y), xs, ys));
return nonZero != null ? (0, _Option.getValue)(nonZero) : count(xs) - count(ys);
}
function delay(f) {
return {
[Symbol.iterator]: () => f()[Symbol.iterator]()
};
}
function empty() {
return unfold(() => void 0);
}
function enumerateWhile(cond, xs) {
return concat(unfold(() => cond() ? [xs, true] : null));
}
function enumerateThenFinally(xs, finalFn) {
return delay(() => {
let iter;
try {
iter = xs[Symbol.iterator]();
} catch (err) {
return void 0;
} finally {
finalFn();
}
return unfold(it => {
try {
const cur = it.next();
return !cur.done ? [cur.value, it] : null;
} catch (err) {
return void 0;
} finally {
finalFn();
}
}, iter);
});
}
function enumerateUsing(disp, work) {
let isDisposed = false;
const disposeOnce = () => {
if (!isDisposed) {
isDisposed = true;
disp.Dispose();
}
};
try {
return enumerateThenFinally(work(disp), disposeOnce);
} catch (err) {
return void 0;
} finally {
disposeOnce();
}
}
function exactlyOne(xs) {
const iter = xs[Symbol.iterator]();
const fst = iter.next();
if (fst.done) {
throw new Error("Seq was empty");
}
const snd = iter.next();
if (!snd.done) {
throw new Error("Seq had multiple items");
}
return fst.value;
}
function except(itemsToExclude, source) {
const exclusionItems = Array.from(itemsToExclude);
const testIsNotInExclusionItems = element => !exclusionItems.some(excludedItem => (0, _Util.equals)(excludedItem, element));
return filter(testIsNotInExclusionItems, source);
}
function exists(f, xs) {
let cur;
for (const iter = xs[Symbol.iterator]();;) {
cur = iter.next();
if (cur.done) {
break;
}
if (f(cur.value)) {
return true;
}
}
return false;
}
function exists2(f, xs, ys) {
let cur1;
let cur2;
for (const iter1 = xs[Symbol.iterator](), iter2 = ys[Symbol.iterator]();;) {
cur1 = iter1.next();
cur2 = iter2.next();
if (cur1.done || cur2.done) {
break;
}
if (f(cur1.value, cur2.value)) {
return true;
}
}
return false;
}
function filter(f, xs) {
return delay(() => unfold(iter => {
let cur = iter.next();
while (!cur.done) {
if (f(cur.value)) {
return [cur.value, iter];
}
cur = iter.next();
}
return null;
}, xs[Symbol.iterator]()));
}
function where(f, xs) {
return filter(f, xs);
}
function fold(f, acc, xs) {
if (Array.isArray(xs) || ArrayBuffer.isView(xs)) {
return xs.reduce(f, acc);
} else {
let cur;
for (let i = 0, iter = xs[Symbol.iterator]();; i++) {
cur = iter.next();
if (cur.done) {
break;
}
acc = f(acc, cur.value, i);
}
return acc;
}
}
function foldBack(f, xs, acc) {
const arr = Array.isArray(xs) || ArrayBuffer.isView(xs) ? xs : Array.from(xs);
for (let i = arr.length - 1; i >= 0; i--) {
acc = f(arr[i], acc, i);
}
return acc;
}
function fold2(f, acc, xs, ys) {
const iter1 = xs[Symbol.iterator]();
const iter2 = ys[Symbol.iterator]();
let cur1;
let cur2;
for (let i = 0;; i++) {
cur1 = iter1.next();
cur2 = iter2.next();
if (cur1.done || cur2.done) {
break;
}
acc = f(acc, cur1.value, cur2.value, i);
}
return acc;
}
function foldBack2(f, xs, ys, acc) {
const ar1 = Array.isArray(xs) || ArrayBuffer.isView(xs) ? xs : Array.from(xs);
const ar2 = Array.isArray(ys) || ArrayBuffer.isView(ys) ? ys : Array.from(ys);
for (let i = ar1.length - 1; i >= 0; i--) {
acc = f(ar1[i], ar2[i], acc, i);
}
return acc;
}
function forAll(f, xs) {
return fold((acc, x) => acc && f(x), true, xs);
}
function forAll2(f, xs, ys) {
return fold2((acc, x, y) => acc && f(x, y), true, xs, ys);
}
function tryHead(xs) {
const iter = xs[Symbol.iterator]();
const cur = iter.next();
return cur.done ? null : (0, _Option.makeSome)(cur.value);
}
function head(xs) {
return __failIfNone(tryHead(xs));
}
function initialize(n, f) {
return delay(() => unfold(i => i < n ? [f(i), i + 1] : null, 0));
}
function initializeInfinite(f) {
return delay(() => unfold(i => [f(i), i + 1], 0));
}
function tryItem(i, xs) {
if (i < 0) {
return null;
}
if (Array.isArray(xs) || ArrayBuffer.isView(xs)) {
return i < xs.length ? (0, _Option.makeSome)(xs[i]) : null;
}
for (let j = 0, iter = xs[Symbol.iterator]();; j++) {
const cur = iter.next();
if (cur.done) {
break;
}
if (j === i) {
return (0, _Option.makeSome)(cur.value);
}
}
return null;
}
function item(i, xs) {
return __failIfNone(tryItem(i, xs));
}
function iterate(f, xs) {
fold((_, x) => f(x), null, xs);
}
function iterate2(f, xs, ys) {
fold2((_, x, y) => f(x, y), null, xs, ys);
}
function iterateIndexed(f, xs) {
fold((_, x, i) => f(i, x), null, xs);
}
function iterateIndexed2(f, xs, ys) {
fold2((_, x, y, i) => f(i, x, y), null, xs, ys);
}
function isEmpty(xs) {
const i = xs[Symbol.iterator]();
return i.next().done;
}
function tryLast(xs) {
try {
return (0, _Option.makeSome)(reduce((_, x) => x, xs));
} catch (err) {
return null;
}
}
function last(xs) {
return __failIfNone(tryLast(xs));
}
// A export function 'length' method causes problems in JavaScript -- https://github.com/Microsoft/TypeScript/issues/442
function count(xs) {
return Array.isArray(xs) || ArrayBuffer.isView(xs) ? xs.length : fold((acc, x) => acc + 1, 0, xs);
}
function map(f, xs) {
return delay(() => unfold(iter => {
const cur = iter.next();
return !cur.done ? [f(cur.value), iter] : null;
}, xs[Symbol.iterator]()));
}
function mapIndexed(f, xs) {
return delay(() => {
let i = 0;
return unfold(iter => {
const cur = iter.next();
return !cur.done ? [f(i++, cur.value), iter] : null;
}, xs[Symbol.iterator]());
});
}
function indexed(xs) {
return mapIndexed((i, x) => [i, x], xs);
}
function map2(f, xs, ys) {
return delay(() => {
const iter1 = xs[Symbol.iterator]();
const iter2 = ys[Symbol.iterator]();
return unfold(() => {
const cur1 = iter1.next();
const cur2 = iter2.next();
return !cur1.done && !cur2.done ? [f(cur1.value, cur2.value), null] : null;
});
});
}
function mapIndexed2(f, xs, ys) {
return delay(() => {
let i = 0;
const iter1 = xs[Symbol.iterator]();
const iter2 = ys[Symbol.iterator]();
return unfold(() => {
const cur1 = iter1.next();
const cur2 = iter2.next();
return !cur1.done && !cur2.done ? [f(i++, cur1.value, cur2.value), null] : null;
});
});
}
function map3(f, xs, ys, zs) {
return delay(() => {
const iter1 = xs[Symbol.iterator]();
const iter2 = ys[Symbol.iterator]();
const iter3 = zs[Symbol.iterator]();
return unfold(() => {
const cur1 = iter1.next();
const cur2 = iter2.next();
const cur3 = iter3.next();
return !cur1.done && !cur2.done && !cur3.done ? [f(cur1.value, cur2.value, cur3.value), null] : null;
});
});
}
function chunkBySize(size, xs) {
const result = (0, _Array.chunkBySize)(size, Array.from(xs));
return ofArray(result);
}
function mapFold(f, acc, xs, transform) {
const result = [];
let r;
let cur;
for (let i = 0, iter = xs[Symbol.iterator]();; i++) {
cur = iter.next();
if (cur.done) {
break;
}
[r, acc] = f(acc, cur.value);
result.push(r);
}
return transform !== void 0 ? [transform(result), acc] : [result, acc];
}
function mapFoldBack(f, xs, acc, transform) {
const arr = Array.isArray(xs) || ArrayBuffer.isView(xs) ? xs : Array.from(xs);
const result = [];
let r;
for (let i = arr.length - 1; i >= 0; i--) {
[r, acc] = f(arr[i], acc);
result.push(r);
}
return transform !== void 0 ? [transform(result), acc] : [result, acc];
}
function max(xs) {
return reduce((acc, x) => (0, _Util.compare)(acc, x) === 1 ? acc : x, xs);
}
function maxBy(f, xs) {
return reduce((acc, x) => (0, _Util.compare)(f(acc), f(x)) === 1 ? acc : x, xs);
}
function min(xs) {
return reduce((acc, x) => (0, _Util.compare)(acc, x) === -1 ? acc : x, xs);
}
function minBy(f, xs) {
return reduce((acc, x) => (0, _Util.compare)(f(acc), f(x)) === -1 ? acc : x, xs);
}
function pairwise(xs) {
return skip(2, scan((last, next) => [last[1], next], [0, 0], xs));
}
function permute(f, xs) {
return ofArray((0, _Array.permute)(f, Array.from(xs)));
}
function rangeStep(first, step, last) {
if (step === 0) {
throw new Error("Step cannot be 0");
}
return delay(() => unfold(x => step > 0 && x <= last || step < 0 && x >= last ? [x, x + step] : null, first));
}
function rangeChar(first, last) {
return delay(() => unfold(x => x <= last ? [x, String.fromCharCode(x.charCodeAt(0) + 1)] : null, first));
}
function range(first, last) {
return rangeStep(first, 1, last);
}
function readOnly(xs) {
return map(x => x, xs);
}
function reduce(f, xs) {
if (Array.isArray(xs) || ArrayBuffer.isView(xs)) {
return xs.reduce(f);
}
const iter = xs[Symbol.iterator]();
let cur = iter.next();
if (cur.done) {
throw new Error("Seq was empty");
}
let acc = cur.value;
while (true) {
cur = iter.next();
if (cur.done) {
break;
}
acc = f(acc, cur.value);
}
return acc;
}
function reduceBack(f, xs) {
const ar = Array.isArray(xs) || ArrayBuffer.isView(xs) ? xs : Array.from(xs);
if (ar.length === 0) {
throw new Error("Seq was empty");
}
let acc = ar[ar.length - 1];
for (let i = ar.length - 2; i >= 0; i--) {
acc = f(ar[i], acc, i);
}
return acc;
}
function replicate(n, x) {
return initialize(n, () => x);
}
function reverse(xs) {
const ar = Array.isArray(xs) || ArrayBuffer.isView(xs) ? xs.slice(0) : Array.from(xs);
return ofArray(ar.reverse());
}
function scan(f, seed, xs) {
return delay(() => {
const iter = xs[Symbol.iterator]();
return unfold(acc => {
if (acc == null) {
return [seed, seed];
}
const cur = iter.next();
if (!cur.done) {
acc = f(acc, cur.value);
return [acc, acc];
}
return void 0;
}, null);
});
}
function scanBack(f, xs, seed) {
return reverse(scan((acc, x) => f(x, acc), seed, reverse(xs)));
}
function singleton(y) {
return unfold(x => x != null ? [x, null] : null, y);
}
function skip(n, xs) {
return {
[Symbol.iterator]: () => {
const iter = xs[Symbol.iterator]();
for (let i = 1; i <= n; i++) {
if (iter.next().done) {
throw new Error("Seq has not enough elements");
}
}
return iter;
}
};
}
function skipWhile(f, xs) {
return delay(() => {
let hasPassed = false;
return filter(x => hasPassed || (hasPassed = !f(x)), xs);
});
}
function sortWith(f, xs) {
const ys = Array.from(xs);
return ofArray(ys.sort(f));
}
function sum(xs) {
return fold((acc, x) => acc + x, 0, xs);
}
function sumBy(f, xs) {
return fold((acc, x) => acc + f(x), 0, xs);
}
function tail(xs) {
const iter = xs[Symbol.iterator]();
const cur = iter.next();
if (cur.done) {
throw new Error("Seq was empty");
}
return {
[Symbol.iterator]: () => iter
};
}
function take(n, xs, truncate = false) {
return delay(() => {
const iter = xs[Symbol.iterator]();
return unfold(i => {
if (i < n) {
const cur = iter.next();
if (!cur.done) {
return [cur.value, i + 1];
}
if (!truncate) {
throw new Error("Seq has not enough elements");
}
}
return void 0;
}, 0);
});
}
function truncate(n, xs) {
return take(n, xs, true);
}
function takeWhile(f, xs) {
return delay(() => {
const iter = xs[Symbol.iterator]();
return unfold(i => {
const cur = iter.next();
if (!cur.done && f(cur.value)) {
return [cur.value, null];
}
return void 0;
}, 0);
});
}
function tryFind(f, xs, defaultValue) {
for (let i = 0, iter = xs[Symbol.iterator]();; i++) {
const cur = iter.next();
if (cur.done) {
break;
}
if (f(cur.value, i)) {
return (0, _Option.makeSome)(cur.value);
}
}
return defaultValue === void 0 ? null : (0, _Option.makeSome)(defaultValue);
}
function find(f, xs) {
return __failIfNone(tryFind(f, xs));
}
function tryFindBack(f, xs, defaultValue) {
const arr = Array.isArray(xs) || ArrayBuffer.isView(xs) ? xs.slice(0) : Array.from(xs);
return tryFind(f, arr.reverse(), defaultValue);
}
function findBack(f, xs) {
return __failIfNone(tryFindBack(f, xs));
}
function tryFindIndex(f, xs) {
for (let i = 0, iter = xs[Symbol.iterator]();; i++) {
const cur = iter.next();
if (cur.done) {
break;
}
if (f(cur.value, i)) {
return i;
}
}
return null;
}
function findIndex(f, xs) {
return __failIfNone(tryFindIndex(f, xs));
}
function tryFindIndexBack(f, xs) {
const arr = Array.isArray(xs) || ArrayBuffer.isView(xs) ? xs.slice(0) : Array.from(xs);
for (let i = arr.length - 1; i >= 0; i--) {
if (f(arr[i], i)) {
return i;
}
}
return null;
}
function findIndexBack(f, xs) {
return __failIfNone(tryFindIndexBack(f, xs));
}
function tryPick(f, xs) {
for (let i = 0, iter = xs[Symbol.iterator]();; i++) {
const cur = iter.next();
if (cur.done) {
break;
}
const y = f(cur.value, i);
if (y != null) {
return y;
}
}
return null;
}
function pick(f, xs) {
return __failIfNone(tryPick(f, xs));
}
function unfold(f, fst) {
return {
[Symbol.iterator]: () => {
// Capture a copy of the first value in the closure
// so the sequence is restarted every time, see #1230
let acc = fst;
return {
next: () => {
const res = f(acc);
if (res != null) {
acc = res[1];
return { done: false, value: res[0] };
}
return { done: true };
}
};
}
};
}
function zip(xs, ys) {
return map2((x, y) => [x, y], xs, ys);
}
function zip3(xs, ys, zs) {
return map3((x, y, z) => [x, y, z], xs, ys, zs);
}
+413
View File
@@ -0,0 +1,413 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.inflate = undefined;
exports.deflate = deflate;
exports.toJson = toJson;
exports.ofJson = ofJson;
exports.toJsonWithTypeInfo = toJsonWithTypeInfo;
exports.ofJsonWithTypeInfo = ofJsonWithTypeInfo;
var _Date = require("./Date");
var _DateOffset = require("./DateOffset");
var _List = require("./List");
var _List2 = _interopRequireDefault(_List);
var _Map = require("./Map");
var _Map2 = _interopRequireDefault(_Map);
var _Option = require("./Option");
var _Reflection = require("./Reflection");
var _Seq = require("./Seq");
var _Set = require("./Set");
var _Set2 = _interopRequireDefault(_Set);
var _String = require("./String");
var _Symbol = require("./Symbol");
var _Symbol2 = _interopRequireDefault(_Symbol);
var _Util = require("./Util");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isDate(v) {
return v instanceof Date;
} // tslint:disable:ban-types
function deflateDate(v) {
return (0, _Date.toString)(v, "O");
}
function deflateValue(v) {
if (isDate(v)) {
return deflateDate(v);
}
return v;
}
function deflate(v) {
if (Array.isArray(v)) {
return v.map(deflateValue);
} else if (ArrayBuffer.isView(v)) {
return Array.from(v).map(deflateValue);
} else if (isDate(v)) {
return deflateDate(v);
} else if (v != null && typeof v === "object") {
if (v instanceof _List2.default || v instanceof _Set2.default || v instanceof Set) {
return Array.from(v).map(deflateValue);
} else if (v instanceof _Map2.default || v instanceof Map) {
let stringKeys = null;
return (0, _Seq.fold)((o, kv) => {
if (stringKeys === null) {
stringKeys = typeof kv[0] === "string";
}
o[stringKeys ? kv[0] : toJson(kv[0])] = deflateValue(kv[1]);
return o;
}, {}, v);
} else if (v instanceof _Option.Some) {
return deflateValue(v.value);
}
const reflectionInfo = typeof v[_Symbol2.default.reflection] === "function" ? v[_Symbol2.default.reflection]() : {};
if (reflectionInfo.properties) {
return (0, _Seq.fold)((o, prop) => {
return o[prop] = deflateValue(v[prop]), o;
}, {}, Object.getOwnPropertyNames(reflectionInfo.properties));
} else if (reflectionInfo.cases) {
const caseInfo = reflectionInfo.cases[v.tag];
const caseName = caseInfo[0];
const fieldsLength = caseInfo.length - 1;
if (fieldsLength === 0) {
return caseName;
} else {
// Prevent undefined assignment from removing case property; see #611:
return { [caseName]: v.data !== void 0 ? deflate(v.data) : null };
}
} else {
return (0, _Seq.fold)((o, prop) => {
return o[prop] = deflateValue(v[prop]), o;
}, {}, Object.getOwnPropertyNames(v));
}
}
return v;
}
function toJson(o) {
return JSON.stringify(deflateValue(o), (k, v) => deflate(v));
}
function combine(path1, path2) {
return typeof path2 === "number" ? path1 + "[" + path2 + "]" : (path1 ? path1 + "." : "") + path2;
}
function isNullable(typ) {
if (typeof typ === "string") {
return typ !== "boolean" && typ !== "number";
} else if (typ instanceof _Util.NonDeclaredType) {
return typ.kind !== "Array" && typ.kind !== "Tuple";
} else {
const info = typeof typ.prototype[_Symbol2.default.reflection] === "function" ? typ.prototype[_Symbol2.default.reflection]() : null;
return info ? info.nullable : true;
}
}
function invalidate(val, typ, path) {
const str = (0, _String.toText)((0, _String.printf)("%A"))(val);
throw new Error(`${str} ${path ? "(" + path + ")" : ""} is not of type ${(0, _Reflection.getTypeFullName)(typ)}`);
}
function needsInflate(enclosing) {
const typ = enclosing.head;
if (typeof typ === "string") {
return false;
}
if (typ instanceof _Util.NonDeclaredType) {
switch (typ.kind) {
case "Option":
case "Array":
return typ.definition != null || needsInflate(new _List2.default(typ.generics[0], enclosing));
case "Tuple":
return typ.generics.some(x => needsInflate(new _List2.default(x, enclosing)));
case "Function":
return false;
case "GenericParam":
return needsInflate((0, _Reflection.resolveGeneric)(typ.definition, enclosing.tail));
case "GenericType":
return true;
default:
return false;
}
}
return true;
}
function inflateArray(arr, enclosing, path) {
if (!Array.isArray) {
invalidate(arr, "array", path);
}
// TODO: Validate non-inflated elements
return needsInflate(enclosing) ? arr.map((x, i) => inflate(x, enclosing, combine(path, i))) : arr;
}
function inflateMap(obj, keyEnclosing, valEnclosing, path) {
const inflateKey = keyEnclosing.head !== "string";
const inflateVal = needsInflate(valEnclosing);
return Object.getOwnPropertyNames(obj).map(k => {
const key = inflateKey ? inflate(JSON.parse(k), keyEnclosing, combine(path, k)) : k;
const val = inflateVal ? inflate(obj[k], valEnclosing, combine(path, k)) : obj[k];
return [key, val];
});
}
function inflateList(val, enclosing, path) {
const ar = [];
let li = new _List2.default();
let cur = val;
const inf = needsInflate(enclosing);
while (cur.tail != null) {
ar.push(inf ? inflate(cur.head, enclosing, path) : cur.head);
cur = cur.tail;
}
ar.reverse();
for (const a of ar) {
li = new _List2.default(a, li);
}
return li;
}
function inflateUnion(val, typ, info, path, inflateField) {
let caseName;
// Same shape as runtime DUs, for example, if they've been serialized with `JSON.stringify`
if (typeof val.tag === "number") {
return Object.assign(new typ(), val);
} else if (typeof val === "string") {
// Cases without fields are serialized as strings by `toJson`
caseName = val;
} else {
// Non-empty cases are serialized as `{ "MyCase": [1, 2] }` by `toJson`
caseName = Object.getOwnPropertyNames(val)[0];
}
// Locate case index
let tag = -1;
for (let i = 0; info.cases[i] != null; i++) {
if (info.cases[i][0] === caseName) {
tag = i;
break;
}
}
// Validate
if (tag === -1) {
invalidate(val, typ, path);
}
const caseInfo = info.cases[tag];
let inflatedData = void 0;
if (caseInfo.length > 2) {
inflatedData = [];
const data = val[caseName];
path = combine(path, caseName);
for (let i = 0; i < data.length; i++) {
inflatedData.push(inflateField ? inflateField(data[i], caseInfo[i + 1], combine(path, i)) : data[i]);
}
} else if (caseInfo.length > 1) {
inflatedData = inflateField ? inflateField(val[caseName], caseInfo[1], combine(path, caseName)) : val[caseName];
}
return new typ(tag, inflatedData);
}
function inflate(val, typ, path) {
let enclosing = null;
if (typ instanceof _List2.default) {
enclosing = typ;
typ = typ.head;
} else {
enclosing = new _List2.default(typ, new _List2.default());
}
if (val == null) {
if (!isNullable(typ)) {
invalidate(val, typ, path);
}
return val;
} else if (typeof typ === "string") {
if ((typ === "boolean" || typ === "number" || typ === "string") && typeof val !== typ) {
invalidate(val, typ, path);
}
return val;
} else if (typ instanceof _Util.NonDeclaredType) {
switch (typ.kind) {
case "Unit":
return null;
case "Option":
return inflate(val, new _List2.default(typ.generics[0], enclosing), path);
case "Array":
if (typ.definition != null) {
return new typ.definition(val);
} else {
return inflateArray(val, new _List2.default(typ.generics[0], enclosing), path);
}
case "Tuple":
return typ.generics.map((x, i) => inflate(val[i], new _List2.default(x, enclosing), combine(path, i)));
case "Function":
return val;
case "GenericParam":
return inflate(val, (0, _Reflection.resolveGeneric)(typ.definition, enclosing.tail), path);
case "GenericType":
const def = typ.definition;
if (def === _List2.default) {
return Array.isArray(val) ? (0, _List.ofArray)(inflateArray(val, (0, _Reflection.resolveGeneric)(0, enclosing), path)) : inflateList(val, (0, _Reflection.resolveGeneric)(0, enclosing), path);
}
// TODO: Should we try to inflate also sets and maps serialized with `JSON.stringify`?
if (def === _Set2.default) {
return (0, _Set.create)(inflateArray(val, (0, _Reflection.resolveGeneric)(0, enclosing), path));
}
if (def === Set) {
return new Set(inflateArray(val, (0, _Reflection.resolveGeneric)(0, enclosing), path));
}
if (def === _Map2.default) {
return (0, _Map.create)(inflateMap(val, (0, _Reflection.resolveGeneric)(0, enclosing), (0, _Reflection.resolveGeneric)(1, enclosing), path));
}
if (def === Map) {
return new Map(inflateMap(val, (0, _Reflection.resolveGeneric)(0, enclosing), (0, _Reflection.resolveGeneric)(1, enclosing), path));
}
return inflate(val, new _List2.default(typ.definition, enclosing), path);
case "Interface":
return typ.definition === "System.DateTimeOffset" ? (0, _DateOffset.parse)(val) : val;
default:
// case "Interface": // case "Any":
return val;
}
} else if (typeof typ === "function") {
if (typ === Date) {
return (0, _Date.parse)(val, true);
}
if (typeof typ.ofJSON === "function") {
return typ.ofJSON(val);
}
const info = typeof typ.prototype[_Symbol2.default.reflection] === "function" ? typ.prototype[_Symbol2.default.reflection]() : {};
// Union types
if (info.cases) {
return inflateUnion(val, typ, info, path, (fi, t, p) => inflate(fi, new _List2.default(t, enclosing), path));
}
if (info.properties) {
const newObj = new typ();
const properties = info.properties;
const ks = Object.getOwnPropertyNames(properties);
for (const k of ks) {
newObj[k] = inflate(val[k], new _List2.default(properties[k], enclosing), combine(path, k));
}
return newObj;
}
return val;
}
throw new Error("Unexpected type when deserializing JSON: " + typ);
}
function inflatePublic(val, genArgs) {
return inflate(val, genArgs ? genArgs.T : null, "");
}
exports.inflate = inflatePublic;
function ofJson(json, genArgs) {
function raise(msg, err, json, targetType) {
let fullMsg = "Cannot deserialize";
if (targetType != null) {
fullMsg += " into " + (0, _Reflection.getTypeFullName)(targetType);
}
fullMsg += " - Error (" + msg + "): " + err.message + " - Data: '" + json + "'";
throw new Error(fullMsg);
}
let value = null;
const targetType = genArgs ? genArgs.T : null;
try {
value = JSON.parse(json);
} catch (e) {
raise("JSON.parse", e, json, targetType);
}
try {
value = inflate(value, targetType, "");
} catch (e) {
raise("inflate", e, json, targetType);
}
return value;
}
// TODO: Dates and types with `toJSON` are not adding the $type field
function toJsonWithTypeInfo(val) {
return JSON.stringify(val, (k, v) => {
if (ArrayBuffer.isView(v)) {
return Array.from(v);
} else if (v != null && typeof v === "object") {
const info = typeof v[_Symbol2.default.reflection] === "function" ? v[_Symbol2.default.reflection]() : {};
if (v instanceof _List2.default || v instanceof _Set2.default || v instanceof Set) {
return {
$type: info.type || "System.Collections.Generic.HashSet",
$values: Array.from(v)
};
} else if (v instanceof _Map2.default || v instanceof Map) {
return (0, _Seq.fold)((o, kv) => {
o[kv[0]] = kv[1];return o;
}, { $type: info.type || "System.Collections.Generic.Dictionary" }, v);
} else if (info.properties) {
return (0, _Seq.fold)((o, prop) => {
return o[prop] = v[prop], o;
}, { $type: info.type }, Object.getOwnPropertyNames(info.properties));
} else if (info.cases) {
const uci = info.cases[v.tag];
return {
// Prevent undefined assignment from removing case property; see #611:
[uci[0]]: v.data !== void 0 ? v.data : null,
$type: info.type
};
}
}
return v;
});
}
function ofJsonWithTypeInfo(json, genArgs) {
const parsed = JSON.parse(json, (key, v) => {
if (v == null) {
return v;
} else if (typeof v === "object" && typeof v.$type === "string") {
// Remove generic args and assembly info added by Newtonsoft.Json
let type = v.$type.replace("+", ".");
let i = type.indexOf("`");
delete v.$type;
if (i > -1) {
type = type.substr(0, i);
} else {
i = type.indexOf(",");
type = i > -1 ? type.substr(0, i) : type;
}
if (type === "System.Collections.Generic.List" || type.indexOf("[]") === type.length - 2) {
return v.$values;
}
if (type === "Microsoft.FSharp.Collections.FSharpList") {
return (0, _List.ofArray)(v.$values);
} else if (type === "Microsoft.FSharp.Collections.FSharpSet") {
return (0, _Set.create)(v.$values);
} else if (type === "System.Collections.Generic.HashSet") {
return new Set(v.$values);
} else if (type === "Microsoft.FSharp.Collections.FSharpMap") {
return (0, _Map.create)(Object.getOwnPropertyNames(v).map(k => [k, v[k]]));
} else if (type === "System.Collections.Generic.Dictionary") {
return new Map(Object.getOwnPropertyNames(v).map(k => [k, v[k]]));
} else {
const typ = (0, _Symbol.getType)(type);
if (typ) {
if (typeof typ.ofJSON === "function") {
return typ.ofJSON(v);
}
const info = typeof typ.prototype[_Symbol2.default.reflection] === "function" ? typ.prototype[_Symbol2.default.reflection]() : {};
if (info.cases) {
return inflateUnion(v, typ, info, key);
}
return Object.assign(new typ(), v);
}
}
} else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[+-]\d{2}:\d{2}|Z)$/.test(v)) {
return (0, _Date.parse)(v, true);
} else {
return v;
}
});
const expected = genArgs ? genArgs.T : null;
if (parsed != null && typeof expected === "function" && !(parsed instanceof (0, _Util.getDefinition)(expected))) {
throw new Error("JSON is not of type " + expected.name + ": " + json);
}
return parsed;
}
+840
View File
@@ -0,0 +1,840 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SetTree = undefined;
exports.distinctBy = distinctBy;
exports.distinct = distinct;
exports.create = create;
exports.isEmpty = isEmpty;
exports.add = add;
exports.addInPlace = addInPlace;
exports.remove = remove;
exports.union = union;
exports.op_Addition = op_Addition;
exports.unionInPlace = unionInPlace;
exports.unionMany = unionMany;
exports.difference = difference;
exports.op_Subtraction = op_Subtraction;
exports.differenceInPlace = differenceInPlace;
exports.intersect = intersect;
exports.intersectInPlace = intersectInPlace;
exports.intersectMany = intersectMany;
exports.isProperSubsetOf = isProperSubsetOf;
exports.isProperSubset = isProperSubset;
exports.isSubsetOf = isSubsetOf;
exports.isSubset = isSubset;
exports.isProperSupersetOf = isProperSupersetOf;
exports.isProperSuperset = isProperSuperset;
exports.isSupersetOf = isSupersetOf;
exports.isSuperset = isSuperset;
exports.copyTo = copyTo;
exports.partition = partition;
exports.filter = filter;
exports.map = map;
exports.exists = exists;
exports.forAll = forAll;
exports.fold = fold;
exports.foldBack = foldBack;
exports.iterate = iterate;
exports.minimumElement = minimumElement;
exports.minElement = minElement;
exports.maximumElement = maximumElement;
exports.maxElement = maxElement;
var _Comparer = require("./Comparer");
var _Comparer2 = _interopRequireDefault(_Comparer);
var _List = require("./List");
var _List2 = _interopRequireDefault(_List);
var _Seq = require("./Seq");
var _Symbol = require("./Symbol");
var _Symbol2 = _interopRequireDefault(_Symbol);
var _Util = require("./Util");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// ----------------------------------------------
// These functions belong to Seq.ts but are
// implemented here to prevent cyclic dependencies
// tslint:disable:max-line-length
function distinctBy(f, xs) {
return (0, _Seq.choose)(tup => tup[0], (0, _Seq.scan)((tup, x) => {
const acc = tup[1];
const k = f(x);
return acc.has(k) ? [null, acc] : [x, add(k, acc)];
}, [null, create()], xs));
}
function distinct(xs) {
return distinctBy(x => x, xs);
}
class SetTree {
constructor(tag, data) {
this.tag = tag | 0;
this.data = data;
}
}
exports.SetTree = SetTree;
const tree_tolerance = 2;
function tree_countAux(s, acc) {
countAux: while (true) {
if (s.tag === 1) {
return acc + 1 | 0;
} else if (s.tag === 0) {
return acc | 0;
} else {
const _var5 = s.data[1];
acc = tree_countAux(s.data[2], acc + 1);
s = _var5;
continue countAux;
}
}
}
function tree_count(s) {
return tree_countAux(s, 0);
}
function tree_SetOne(n) {
return new SetTree(1, [n]);
}
function tree_SetNode(x, l, r, h) {
return new SetTree(2, [x, l, r, h]);
}
function tree_height(t) {
return t.tag === 1 ? 1 : t.tag === 2 ? t.data[3] : 0;
}
function tree_mk(l, k, r) {
const matchValue = l.tag === 0 ? r.tag === 0 ? 0 : 1 : 1;
switch (matchValue) {
case 0:
return tree_SetOne(k);
case 1:
const hl = tree_height(l) | 0;
const hr = tree_height(r) | 0;
const m = (hl < hr ? hr : hl) | 0;
return tree_SetNode(k, l, r, m + 1);
}
throw new Error("internal error: Set.tree_mk");
}
function tree_rebalance(t1, k, t2) {
const t1h = tree_height(t1);
const t2h = tree_height(t2);
if (t2h > t1h + tree_tolerance) {
if (t2.tag === 2) {
if (tree_height(t2.data[1]) > t1h + 1) {
if (t2.data[1].tag === 2) {
return tree_mk(tree_mk(t1, k, t2.data[1].data[1]), t2.data[1].data[0], tree_mk(t2.data[1].data[2], t2.data[0], t2.data[2]));
} else {
throw new Error("rebalance");
}
} else {
return tree_mk(tree_mk(t1, k, t2.data[1]), t2.data[0], t2.data[2]);
}
} else {
throw new Error("rebalance");
}
} else {
if (t1h > t2h + tree_tolerance) {
if (t1.tag === 2) {
if (tree_height(t1.data[2]) > t2h + 1) {
if (t1.data[2].tag === 2) {
return tree_mk(tree_mk(t1.data[1], t1.data[0], t1.data[2].data[1]), t1.data[2].data[0], tree_mk(t1.data[2].data[2], k, t2));
} else {
throw new Error("rebalance");
}
} else {
return tree_mk(t1.data[1], t1.data[0], tree_mk(t1.data[2], k, t2));
}
} else {
throw new Error("rebalance");
}
} else {
return tree_mk(t1, k, t2);
}
}
}
function tree_add(comparer, k, t) {
if (t.tag === 1) {
const c = comparer.Compare(k, t.data[0]);
if (c < 0) {
return tree_SetNode(k, new SetTree(0), t, 2);
} else if (c === 0) {
return t;
} else {
return tree_SetNode(k, t, new SetTree(0), 2);
}
} else if (t.tag === 0) {
return tree_SetOne(k);
} else {
const c = comparer.Compare(k, t.data[0]);
if (c < 0) {
return tree_rebalance(tree_add(comparer, k, t.data[1]), t.data[0], t.data[2]);
} else if (c === 0) {
return t;
} else {
return tree_rebalance(t.data[1], t.data[0], tree_add(comparer, k, t.data[2]));
}
}
}
function tree_balance(comparer, t1, k, t2) {
const matchValue = t1.tag === 1 ? t2.tag === 0 ? [1, t1] : t2.tag === 1 ? [2, t1.data[0], t2] : [2, t1.data[0], t2] : t1.tag === 2 ? t2.tag === 1 ? [3, t2.data[0], t1] : t2.tag === 2 ? [4, t1.data[3], t2.data[3], t1.data[0], t2.data[0], t1.data[1], t1.data[2], t2.data[1], t2.data[2]] : [1, t1] : [0, t2];
switch (matchValue[0]) {
case 0:
return tree_add(comparer, k, matchValue[1]);
case 1:
return tree_add(comparer, k, matchValue[1]);
case 2:
return tree_add(comparer, k, tree_add(comparer, matchValue[1], matchValue[2]));
case 3:
return tree_add(comparer, k, tree_add(comparer, matchValue[1], matchValue[2]));
case 4:
if (matchValue[1] + tree_tolerance < matchValue[2]) {
return tree_rebalance(tree_balance(comparer, t1, k, matchValue[7]), matchValue[4], matchValue[8]);
} else if (matchValue[2] + tree_tolerance < matchValue[1]) {
return tree_rebalance(matchValue[5], matchValue[3], tree_balance(comparer, matchValue[6], k, t2));
} else {
return tree_mk(t1, k, t2);
}
}
throw new Error("internal error: Set.tree_balance");
}
function tree_split(comparer, pivot, t) {
if (t.tag === 1) {
const c = comparer.Compare(t.data[0], pivot);
if (c < 0) {
return [t, false, new SetTree(0)];
} else if (c === 0) {
return [new SetTree(0), true, new SetTree(0)];
} else {
return [new SetTree(0), false, t];
}
} else if (t.tag === 0) {
return [new SetTree(0), false, new SetTree(0)];
} else {
const c = comparer.Compare(pivot, t.data[0]);
if (c < 0) {
const patternInput = tree_split(comparer, pivot, t.data[1]);
return [patternInput[0], patternInput[1], tree_balance(comparer, patternInput[2], t.data[0], t.data[2])];
} else if (c === 0) {
return [t.data[1], true, t.data[2]];
} else {
const patternInput = tree_split(comparer, pivot, t.data[2]);
return [tree_balance(comparer, t.data[1], t.data[0], patternInput[0]), patternInput[1], patternInput[2]];
}
}
}
function tree_spliceOutSuccessor(t) {
if (t.tag === 1) {
return [t.data[0], new SetTree(0)];
} else if (t.tag === 2) {
if (t.data[1].tag === 0) {
return [t.data[0], t.data[2]];
} else {
const patternInput = tree_spliceOutSuccessor(t.data[1]);
return [patternInput[0], tree_mk(patternInput[1], t.data[0], t.data[2])];
}
} else {
throw new Error("internal error: Map.spliceOutSuccessor");
}
}
function tree_remove(comparer, k, t) {
if (t.tag === 1) {
const c = comparer.Compare(k, t.data[0]);
if (c === 0) {
return new SetTree(0);
} else {
return t;
}
} else if (t.tag === 2) {
const c = comparer.Compare(k, t.data[0]);
if (c < 0) {
return tree_rebalance(tree_remove(comparer, k, t.data[1]), t.data[0], t.data[2]);
} else if (c === 0) {
const matchValue = [t.data[1], t.data[2]];
if (matchValue[0].tag === 0) {
return t.data[2];
} else if (matchValue[1].tag === 0) {
return t.data[1];
} else {
const patternInput = tree_spliceOutSuccessor(t.data[2]);
return tree_mk(t.data[1], patternInput[0], patternInput[1]);
}
} else {
return tree_rebalance(t.data[1], t.data[0], tree_remove(comparer, k, t.data[2]));
}
} else {
return t;
}
}
function tree_mem(comparer, k, t) {
mem: while (true) {
if (t.tag === 1) {
return comparer.Compare(k, t.data[0]) === 0;
} else if (t.tag === 0) {
return false;
} else {
const c = comparer.Compare(k, t.data[0]) | 0;
if (c < 0) {
comparer = comparer;
k = k;
t = t.data[1];
continue mem;
} else if (c === 0) {
return true;
} else {
comparer = comparer;
k = k;
t = t.data[2];
continue mem;
}
}
}
}
function tree_iter(f, t) {
if (t.tag === 1) {
f(t.data[0]);
} else if (t.tag !== 0) {
tree_iter(f, t.data[1]);
f(t.data[0]);
tree_iter(f, t.data[2]);
}
}
function tree_foldBack(f, m, x) {
return m.tag === 1 ? f(m.data[0], x) : m.tag === 0 ? x : tree_foldBack(f, m.data[1], f(m.data[0], tree_foldBack(f, m.data[2], x)));
}
function tree_fold(f, x, m) {
if (m.tag === 1) {
return f(x, m.data[0]);
} else if (m.tag === 0) {
return x;
} else {
const x_1 = tree_fold(f, x, m.data[1]);
const x_2 = f(x_1, m.data[0]);
return tree_fold(f, x_2, m.data[2]);
}
}
function tree_forall(f, m) {
return m.tag === 1 ? f(m.data[0]) : m.tag === 0 ? true : (f(m.data[0]) ? tree_forall(f, m.data[1]) : false) ? tree_forall(f, m.data[2]) : false;
}
function tree_exists(f, m) {
return m.tag === 1 ? f(m.data[0]) : m.tag === 0 ? false : (f(m.data[0]) ? true : tree_exists(f, m.data[1])) ? true : tree_exists(f, m.data[2]);
}
function tree_isEmpty(m) {
return m.tag === 0 ? true : false;
}
function tree_subset(comparer, a, b) {
return tree_forall(x => tree_mem(comparer, x, b), a);
}
function tree_psubset(comparer, a, b) {
return tree_forall(x => tree_mem(comparer, x, b), a) ? tree_exists(x => !tree_mem(comparer, x, a), b) : false;
}
function tree_filterAux(comparer, f, s, acc) {
if (s.tag === 1) {
if (f(s.data[0])) {
return tree_add(comparer, s.data[0], acc);
} else {
return acc;
}
} else if (s.tag === 0) {
return acc;
} else {
const acc_1 = f(s.data[0]) ? tree_add(comparer, s.data[0], acc) : acc;
return tree_filterAux(comparer, f, s.data[1], tree_filterAux(comparer, f, s.data[2], acc_1));
}
}
function tree_filter(comparer, f, s) {
return tree_filterAux(comparer, f, s, new SetTree(0));
}
function tree_diffAux(comparer, m, acc) {
diffAux: while (true) {
if (m.tag === 1) {
return tree_remove(comparer, m.data[0], acc);
} else if (m.tag === 0) {
return acc;
} else {
const _var6 = comparer;
const _var7 = m.data[1];
acc = tree_diffAux(comparer, m.data[2], tree_remove(comparer, m.data[0], acc));
comparer = _var6;
m = _var7;
continue diffAux;
}
}
}
function tree_diff(comparer, a, b) {
return tree_diffAux(comparer, b, a);
}
function tree_union(comparer, t1, t2) {
const matchValue = t1.tag === 0 ? [1, t2] : t1.tag === 1 ? t2.tag === 0 ? [2, t1] : t2.tag === 1 ? [3, t1.data[0], t2] : [3, t1.data[0], t2] : t2.tag === 0 ? [2, t1] : t2.tag === 1 ? [4, t2.data[0], t1] : [0, t1.data[3], t2.data[3], t1.data[0], t2.data[0], t1.data[1], t1.data[2], t2.data[1], t2.data[2]];
switch (matchValue[0]) {
case 0:
if (matchValue[1] > matchValue[2]) {
const patternInput = tree_split(comparer, matchValue[3], t2);
return tree_balance(comparer, tree_union(comparer, matchValue[5], patternInput[0]), matchValue[3], tree_union(comparer, matchValue[6], patternInput[2]));
} else {
const patternInput_1 = tree_split(comparer, matchValue[4], t1);
return tree_balance(comparer, tree_union(comparer, matchValue[7], patternInput_1[0]), matchValue[4], tree_union(comparer, matchValue[8], patternInput_1[2]));
}
case 1:
return matchValue[1];
case 2:
return matchValue[1];
case 3:
return tree_add(comparer, matchValue[1], matchValue[2]);
case 4:
return tree_add(comparer, matchValue[1], matchValue[2]);
}
throw new Error("internal error: Set.tree_union");
}
function tree_intersectionAux(comparer, b, m, acc) {
intersectionAux: while (true) {
if (m.tag === 1) {
if (tree_mem(comparer, m.data[0], b)) {
return tree_add(comparer, m.data[0], acc);
} else {
return acc;
}
} else if (m.tag === 0) {
return acc;
} else {
const acc_1 = tree_intersectionAux(comparer, b, m.data[2], acc);
const acc_2 = tree_mem(comparer, m.data[0], b) ? tree_add(comparer, m.data[0], acc_1) : acc_1;
comparer = comparer;
b = b;
m = m.data[1];
acc = acc_2;
continue intersectionAux;
}
}
}
function tree_intersection(comparer, a, b) {
return tree_intersectionAux(comparer, b, a, new SetTree(0));
}
function tree_partition1(comparer, f, k, acc1, acc2) {
return f(k) ? [tree_add(comparer, k, acc1), acc2] : [acc1, tree_add(comparer, k, acc2)];
}
function tree_partitionAux(comparer, f, s, acc_0, acc_1) {
const acc = [acc_0, acc_1];
if (s.tag === 1) {
return tree_partition1(comparer, f, s.data[0], acc[0], acc[1]);
} else if (s.tag === 0) {
return acc;
} else {
const acc_2 = tree_partitionAux(comparer, f, s.data[2], acc[0], acc[1]);
const acc_3 = tree_partition1(comparer, f, s.data[0], acc_2[0], acc_2[1]);
return tree_partitionAux(comparer, f, s.data[1], acc_3[0], acc_3[1]);
}
}
function tree_partition(comparer, f, s) {
return tree_partitionAux(comparer, f, s, new SetTree(0), new SetTree(0));
}
// function tree_$MatchSetNode$MatchSetEmpty$(s: SetTree) {
// return s.tag === 1 ? new Choice("Choice1Of2", [[s.data[0], new SetTree(0), new SetTree(0)]]) : s.tag === 0 ? new Choice("Choice2Of2", [null]) : new Choice("Choice1Of2", [[s.data[0], s.data[1], s.data[2]]]);
// }
function tree_minimumElementAux(s, n) {
return s.tag === 1 ? s.data[0] : s.tag === 0 ? n : tree_minimumElementAux(s.data[1], s.data[0]);
}
function tree_minimumElementOpt(s) {
return s.tag === 1 ? s.data[0] : s.tag === 0 ? null : tree_minimumElementAux(s.data[1], s.data[0]);
}
function tree_maximumElementAux(s, n) {
return s.tag === 1 ? s.data[0] : s.tag === 0 ? n : tree_maximumElementAux(s.data[2], s.data[0]);
}
function tree_maximumElementOpt(s) {
return s.tag === 1 ? s.data[0] : s.tag === 0 ? null : tree_maximumElementAux(s.data[2], s.data[0]);
}
function tree_minimumElement(s) {
const matchValue = tree_minimumElementOpt(s);
if (matchValue == null) {
throw new Error("Set contains no elements");
} else {
return matchValue;
}
}
function tree_maximumElement(s) {
const matchValue = tree_maximumElementOpt(s);
if (matchValue == null) {
throw new Error("Set contains no elements");
} else {
return matchValue;
}
}
function tree_collapseLHS(stack) {
collapseLHS: while (true) {
if (stack.tail != null) {
if (stack.head.tag === 1) {
return stack;
} else if (stack.head.tag === 2) {
stack = (0, _List.ofArray)([stack.head.data[1], tree_SetOne(stack.head.data[0]), stack.head.data[2]], stack.tail);
continue collapseLHS;
} else {
stack = stack.tail;
continue collapseLHS;
}
} else {
return new _List2.default();
}
}
}
function tree_mkIterator(s) {
return { stack: tree_collapseLHS(new _List2.default(s, new _List2.default())), started: false };
}
// function tree_notStarted() {
// throw new Error("Enumeration not started");
// };
// var alreadyFinished = $exports.alreadyFinished = function () {
// throw new Error("Enumeration already started");
// };
function tree_moveNext(i) {
function current(it) {
if (it.stack.tail == null) {
return null;
} else if (it.stack.head.tag === 1) {
return it.stack.head.data[0];
}
throw new Error("Please report error: Set iterator, unexpected stack for current");
}
if (i.started) {
if (i.stack.tail == null) {
return { done: true, value: null };
} else {
if (i.stack.head.tag === 1) {
i.stack = tree_collapseLHS(i.stack.tail);
return {
done: i.stack.tail == null,
value: current(i)
};
} else {
throw new Error("Please report error: Set iterator, unexpected stack for moveNext");
}
}
} else {
i.started = true;
return {
done: i.stack.tail == null,
value: current(i)
};
}
}
function tree_compareStacks(comparer, l1, l2) {
compareStacks: while (true) {
const matchValue = l1.tail != null ? l2.tail != null ? l2.head.tag === 1 ? l1.head.tag === 1 ? [4, l1.head.data[0], l2.head.data[0], l1.tail, l2.tail] : l1.head.tag === 2 ? l1.head.data[1].tag === 0 ? [6, l1.head.data[1], l1.head.data[0], l1.head.data[2], l2.head.data[0], l1.tail, l2.tail] : [9, l1.head.data[0], l1.head.data[1], l1.head.data[2], l1.tail] : [10, l2.head.data[0], l2.tail] : l2.head.tag === 2 ? l2.head.data[1].tag === 0 ? l1.head.tag === 1 ? [5, l1.head.data[0], l2.head.data[0], l2.head.data[2], l1.tail, l2.tail] : l1.head.tag === 2 ? l1.head.data[1].tag === 0 ? [7, l1.head.data[0], l1.head.data[2], l2.head.data[0], l2.head.data[2], l1.tail, l2.tail] : [9, l1.head.data[0], l1.head.data[1], l1.head.data[2], l1.tail] : [11, l2.head.data[0], l2.head.data[1], l2.head.data[2], l2.tail] : l1.head.tag === 1 ? [8, l1.head.data[0], l1.tail] : l1.head.tag === 2 ? [9, l1.head.data[0], l1.head.data[1], l1.head.data[2], l1.tail] : [11, l2.head.data[0], l2.head.data[1], l2.head.data[2], l2.tail] : l1.head.tag === 1 ? [8, l1.head.data[0], l1.tail] : l1.head.tag === 2 ? [9, l1.head.data[0], l1.head.data[1], l1.head.data[2], l1.tail] : [3, l1.tail, l2.tail] : [2] : l2.tail != null ? [1] : [0];
switch (matchValue[0]) {
case 0:
return 0;
case 1:
return -1;
case 2:
return 1;
case 3:
comparer = comparer;
l1 = matchValue[1];
l2 = matchValue[2];
continue compareStacks;
case 4:
const c = comparer.Compare(matchValue[1], matchValue[2]) | 0;
if (c !== 0) {
return c | 0;
} else {
comparer = comparer;
l1 = matchValue[3];
l2 = matchValue[4];
continue compareStacks;
}
case 5:
const c_1 = comparer.Compare(matchValue[1], matchValue[2]) | 0;
if (c_1 !== 0) {
return c_1 | 0;
} else {
comparer = comparer;
l1 = new _List2.default(new SetTree(0), matchValue[4]);
l2 = new _List2.default(matchValue[3], matchValue[5]);
continue compareStacks;
}
case 6:
const c_2 = comparer.Compare(matchValue[2], matchValue[4]) | 0;
if (c_2 !== 0) {
return c_2 | 0;
} else {
comparer = comparer;
l1 = new _List2.default(matchValue[3], matchValue[5]);
l2 = new _List2.default(matchValue[1], matchValue[6]);
continue compareStacks;
}
case 7:
const c_3 = comparer.Compare(matchValue[1], matchValue[3]) | 0;
if (c_3 !== 0) {
return c_3 | 0;
} else {
comparer = comparer;
l1 = new _List2.default(matchValue[2], matchValue[5]);
l2 = new _List2.default(matchValue[4], matchValue[6]);
continue compareStacks;
}
case 8:
comparer = comparer;
l1 = (0, _List.ofArray)([new SetTree(0), tree_SetOne(matchValue[1])], matchValue[2]);
l2 = l2;
continue compareStacks;
case 9:
comparer = comparer;
l1 = (0, _List.ofArray)([matchValue[2], tree_SetNode(matchValue[1], new SetTree(0), matchValue[3], 0)], matchValue[4]);
l2 = l2;
continue compareStacks;
case 10:
comparer = comparer;
l1 = l1;
l2 = (0, _List.ofArray)([new SetTree(0), tree_SetOne(matchValue[1])], matchValue[2]);
continue compareStacks;
case 11:
comparer = comparer;
l1 = l1;
l2 = (0, _List.ofArray)([matchValue[2], tree_SetNode(matchValue[1], new SetTree(0), matchValue[3], 0)], matchValue[4]);
continue compareStacks;
}
}
}
function tree_compare(comparer, s1, s2) {
if (s1.tag === 0) {
return s2.tag === 0 ? 0 : -1;
} else {
return s2.tag === 0 ? 1 : tree_compareStacks(comparer, (0, _List.ofArray)([s1]), (0, _List.ofArray)([s2]));
}
}
function tree_mkFromEnumerator(comparer, acc, e) {
let cur = e.next();
while (!cur.done) {
acc = tree_add(comparer, cur.value, acc);
cur = e.next();
}
return acc;
}
function tree_ofSeq(comparer, c) {
const ie = c[Symbol.iterator]();
return tree_mkFromEnumerator(comparer, new SetTree(0), ie);
}
class FableSet {
/** Do not call, use Set.create instead. */
constructor() {
return;
}
ToString() {
return "set [" + Array.from(this).map(x => (0, _Util.toString)(x)).join("; ") + "]";
}
Equals(s2) {
return this.CompareTo(s2) === 0;
}
CompareTo(s2) {
return this === s2 ? 0 : tree_compare(this.comparer, this.tree, s2.tree);
}
[Symbol.iterator]() {
const i = tree_mkIterator(this.tree);
return {
next: () => tree_moveNext(i)
};
}
values() {
return this[Symbol.iterator]();
}
has(v) {
return tree_mem(this.comparer, v, this.tree);
}
/** Mutating method */
add(v) {
this.tree = tree_add(this.comparer, v, this.tree);
return this;
}
/** Mutating method */
delete(v) {
// TODO: Is calculating the size twice is more performant than calling tree_mem?
const oldSize = tree_count(this.tree);
this.tree = tree_remove(this.comparer, v, this.tree);
return oldSize > tree_count(this.tree);
}
/** Mutating method */
clear() {
this.tree = new SetTree(0);
}
get size() {
return tree_count(this.tree);
}
[_Symbol2.default.reflection]() {
return {
type: "Microsoft.FSharp.Collections.FSharpSet",
interfaces: ["System.IEquatable", "System.IComparable"]
};
}
}
exports.default = FableSet;
function from(comparer, tree) {
const s = new FableSet();
s.tree = tree;
s.comparer = comparer || new _Comparer2.default();
return s;
}
function create(ie, comparer) {
comparer = comparer || new _Comparer2.default();
return from(comparer, ie ? tree_ofSeq(comparer, ie) : new SetTree(0));
}
function isEmpty(s) {
return tree_isEmpty(s.tree);
}
function add(item, s) {
return from(s.comparer, tree_add(s.comparer, item, s.tree));
}
function addInPlace(item, s) {
return s.has(item) ? false : (s.add(item), true);
}
function remove(item, s) {
return from(s.comparer, tree_remove(s.comparer, item, s.tree));
}
function union(set1, set2) {
return set2.tree.tag === 0 ? set1 : set1.tree.tag === 0 ? set2 : from(set1.comparer, tree_union(set1.comparer, set1.tree, set2.tree));
}
function op_Addition(set1, set2) {
return union(set1, set2);
}
function unionInPlace(set1, set2) {
(0, _Seq.iterate)(x => {
set1.add(x);
}, set2);
}
function unionMany(sets) {
// Pass args as union(s, acc) instead of union(acc, s)
// to discard the comparer of the first empty set
return (0, _Seq.fold)((acc, s) => union(s, acc), create(), sets);
}
function difference(set1, set2) {
return set1.tree.tag === 0 ? set1 : set2.tree.tag === 0 ? set1 : from(set1.comparer, tree_diff(set1.comparer, set1.tree, set2.tree));
}
function op_Subtraction(set1, set2) {
return difference(set1, set2);
}
function differenceInPlace(set1, set2) {
(0, _Seq.iterate)(x => {
set1.delete(x);
}, set2);
}
function intersect(set1, set2) {
return set2.tree.tag === 0 ? set2 : set1.tree.tag === 0 ? set1 : from(set1.comparer, tree_intersection(set1.comparer, set1.tree, set2.tree));
}
function intersectInPlace(set1, set2) {
const set2_ = set2 instanceof Set ? set2 : new Set(set2);
(0, _Seq.iterate)(x => {
if (!set2_.has(x)) {
set1.delete(x);
}
}, set1);
}
function intersectMany(sets) {
return (0, _Seq.reduce)((s1, s2) => intersect(s1, s2), sets);
}
function isProperSubsetOf(set1, set2) {
if (set1 instanceof FableSet && set2 instanceof FableSet) {
return tree_psubset(set1.comparer, set1.tree, set2.tree);
} else {
set2 = set2 instanceof Set ? set2 : new Set(set2);
return (0, _Seq.forAll)(x => set2.has(x), set1) && (0, _Seq.exists)(x => !set1.has(x), set2);
}
}
function isProperSubset(set1, set2) {
return isProperSubsetOf(set1, set2);
}
function isSubsetOf(set1, set2) {
if (set1 instanceof FableSet && set2 instanceof FableSet) {
return tree_subset(set1.comparer, set1.tree, set2.tree);
} else {
set2 = set2 instanceof Set ? set2 : new Set(set2);
return (0, _Seq.forAll)(x => set2.has(x), set1);
}
}
function isSubset(set1, set2) {
return isSubsetOf(set1, set2);
}
function isProperSupersetOf(set1, set2) {
if (set1 instanceof FableSet && set2 instanceof FableSet) {
return tree_psubset(set1.comparer, set2.tree, set1.tree);
} else {
return isProperSubset(set2 instanceof Set ? set2 : new Set(set2), set1);
}
}
function isProperSuperset(set1, set2) {
return isProperSupersetOf(set1, set2);
}
function isSupersetOf(set1, set2) {
if (set1 instanceof FableSet && set2 instanceof FableSet) {
return tree_subset(set1.comparer, set2.tree, set1.tree);
} else {
return isSubset(set2 instanceof Set ? set2 : new Set(set2), set1);
}
}
function isSuperset(set1, set2) {
return isSupersetOf(set1, set2);
}
function copyTo(xs, arr, arrayIndex, count) {
if (!Array.isArray(arr) && !ArrayBuffer.isView(arr)) {
throw new Error("Array is invalid");
}
count = count || arr.length;
let i = arrayIndex || 0;
const iter = xs[Symbol.iterator]();
while (count--) {
const el = iter.next();
if (el.done) {
break;
}
arr[i++] = el.value;
}
}
function partition(f, s) {
if (s.tree.tag === 0) {
return [s, s];
} else {
const tuple = tree_partition(s.comparer, f, s.tree);
return [from(s.comparer, tuple[0]), from(s.comparer, tuple[1])];
}
}
function filter(f, s) {
if (s.tree.tag === 0) {
return s;
} else {
return from(s.comparer, tree_filter(s.comparer, f, s.tree));
}
}
function map(f, s) {
const comparer = new _Comparer2.default();
return from(comparer, tree_fold((acc, k) => tree_add(comparer, f(k), acc), new SetTree(0), s.tree));
}
function exists(f, s) {
return tree_exists(f, s.tree);
}
function forAll(f, s) {
return tree_forall(f, s.tree);
}
function fold(f, seed, s) {
return tree_fold(f, seed, s.tree);
}
function foldBack(f, s, seed) {
return tree_foldBack(f, s.tree, seed);
}
function iterate(f, s) {
tree_iter(f, s.tree);
}
function minimumElement(s) {
return tree_minimumElement(s.tree);
}
function minElement(s) {
return tree_minimumElement(s.tree);
}
function maximumElement(s) {
return tree_maximumElement(s.tree);
}
function maxElement(s) {
return tree_maximumElement(s.tree);
}
+502
View File
@@ -0,0 +1,502 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.compare = compare;
exports.compareTo = compareTo;
exports.startsWith = startsWith;
exports.indexOfAny = indexOfAny;
exports.printf = printf;
exports.toConsole = toConsole;
exports.toConsoleError = toConsoleError;
exports.toText = toText;
exports.toFail = toFail;
exports.fsFormat = fsFormat;
exports.format = format;
exports.endsWith = endsWith;
exports.initialize = initialize;
exports.insert = insert;
exports.isNullOrEmpty = isNullOrEmpty;
exports.isNullOrWhiteSpace = isNullOrWhiteSpace;
exports.join = join;
exports.validateGuid = validateGuid;
exports.newGuid = newGuid;
exports.guidToArray = guidToArray;
exports.arrayToGuid = arrayToGuid;
exports.toBase64String = toBase64String;
exports.fromBase64String = fromBase64String;
exports.padLeft = padLeft;
exports.padRight = padRight;
exports.remove = remove;
exports.replace = replace;
exports.replicate = replicate;
exports.getCharAtIndex = getCharAtIndex;
exports.split = split;
exports.trim = trim;
exports.filter = filter;
var _Date = require("./Date");
var _RegExp = require("./RegExp");
var _Util = require("./Util");
const fsFormatRegExp = /(^|[^%])%([0+ ]*)(-?\d+)?(?:\.(\d+))?(\w)/;
const formatRegExp = /\{(\d+)(,-?\d+)?(?:\:(.+?))?\}/g;
// From https://stackoverflow.com/a/13653180/3922220
const guidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const StringComparison = {
CurrentCulture: 0,
CurrentCultureIgnoreCase: 1,
InvariantCulture: 2,
InvariantCultureIgnoreCase: 3,
Ordinal: 4,
OrdinalIgnoreCase: 5
};
function cmp(x, y, ic) {
function isIgnoreCase(i) {
return i === true || i === StringComparison.CurrentCultureIgnoreCase || i === StringComparison.InvariantCultureIgnoreCase || i === StringComparison.OrdinalIgnoreCase;
}
function isOrdinal(i) {
return i === StringComparison.Ordinal || i === StringComparison.OrdinalIgnoreCase;
}
if (x == null) {
return y == null ? 0 : -1;
}
if (y == null) {
return 1;
} // everything is bigger than null
if (isOrdinal(ic)) {
if (isIgnoreCase(ic)) {
x = x.toLowerCase();
y = y.toLowerCase();
}
return x === y ? 0 : x < y ? -1 : 1;
} else {
if (isIgnoreCase(ic)) {
x = x.toLocaleLowerCase();
y = y.toLocaleLowerCase();
}
return x.localeCompare(y);
}
}
function compare(...args) {
switch (args.length) {
case 2:
return cmp(args[0], args[1], false);
case 3:
return cmp(args[0], args[1], args[2]);
case 4:
return cmp(args[0], args[1], args[2] === true);
case 5:
return cmp(args[0].substr(args[1], args[4]), args[2].substr(args[3], args[4]), false);
case 6:
return cmp(args[0].substr(args[1], args[4]), args[2].substr(args[3], args[4]), args[5]);
case 7:
return cmp(args[0].substr(args[1], args[4]), args[2].substr(args[3], args[4]), args[5] === true);
default:
throw new Error("String.compare: Unsupported number of parameters");
}
}
function compareTo(x, y) {
return cmp(x, y, false);
}
function startsWith(str, pattern, ic) {
if (str.length >= pattern.length) {
return cmp(str.substr(0, pattern.length), pattern, ic) === 0;
}
return false;
}
function indexOfAny(str, anyOf, ...args) {
if (str == null || str === "") {
return -1;
}
const startIndex = args.length > 0 ? args[0] : 0;
if (startIndex < 0) {
throw new Error("String.indexOfAny: Start index cannot be negative");
}
const length = args.length > 1 ? args[1] : str.length - startIndex;
if (length < 0) {
throw new Error("String.indexOfAny: Length cannot be negative");
}
if (length > str.length - startIndex) {
throw new Error("String.indexOfAny: Invalid startIndex and length");
}
str = str.substr(startIndex, length);
for (const c of anyOf) {
const index = str.indexOf(c);
if (index > -1) {
return index + startIndex;
}
}
return -1;
}
function toHex(value) {
return value < 0 ? "ff" + (16777215 - (Math.abs(value) - 1)).toString(16) : value.toString(16);
}
function printf(input) {
return {
input,
cont: fsFormat(input)
};
}
function toConsole(arg) {
// Don't remove the lambda here, see #1357
return arg.cont(x => {
console.log(x);
});
}
function toConsoleError(arg) {
return arg.cont(x => {
console.error(x);
});
}
function toText(arg) {
return arg.cont(x => x);
}
function toFail(arg) {
return arg.cont(x => {
throw new Error(x);
});
}
function formatOnce(str2, rep) {
return str2.replace(fsFormatRegExp, (_, prefix, flags, pad, precision, format) => {
switch (format) {
case "f":
case "F":
rep = rep.toFixed(precision || 6);
break;
case "g":
case "G":
rep = rep.toPrecision(precision);
break;
case "e":
case "E":
rep = rep.toExponential(precision);
break;
case "O":
rep = (0, _Util.toString)(rep);
break;
case "A":
rep = (0, _Util.toString)(rep, true);
break;
case "x":
rep = toHex(Number(rep));
break;
case "X":
rep = toHex(Number(rep)).toUpperCase();
break;
}
const plusPrefix = flags.indexOf("+") >= 0 && parseInt(rep, 10) >= 0;
pad = parseInt(pad, 10);
if (!isNaN(pad)) {
const ch = pad >= 0 && flags.indexOf("0") >= 0 ? "0" : " ";
rep = padLeft(rep, Math.abs(pad) - (plusPrefix ? 1 : 0), ch, pad < 0);
}
const once = prefix + (plusPrefix ? "+" + rep : rep);
return once.replace(/%/g, "%%");
});
}
function createPrinter(str, cont) {
const printer = (...args) => {
// Make a copy as the function may be used several times
let strCopy = str;
for (const arg of args) {
strCopy = formatOnce(strCopy, arg);
}
return fsFormatRegExp.test(strCopy) ? createPrinter(strCopy, cont) : cont(strCopy.replace(/%%/g, "%"));
};
// Mark it as curried so it doesn't
// get wrapped by CurriedLambda
printer.curried = true;
return printer;
}
function fsFormat(str) {
return cont => {
return fsFormatRegExp.test(str) ? createPrinter(str, cont) : cont(str);
};
}
function format(str, ...args) {
return str.replace(formatRegExp, (match, idx, pad, pattern) => {
let rep = args[idx];
let padSymbol = " ";
if (typeof rep === "number") {
switch ((pattern || "").substring(0, 1)) {
case "f":
case "F":
rep = pattern.length > 1 ? rep.toFixed(pattern.substring(1)) : rep.toFixed(2);
break;
case "g":
case "G":
rep = pattern.length > 1 ? rep.toPrecision(pattern.substring(1)) : rep.toPrecision();
break;
case "e":
case "E":
rep = pattern.length > 1 ? rep.toExponential(pattern.substring(1)) : rep.toExponential();
break;
case "p":
case "P":
rep = (pattern.length > 1 ? (rep * 100).toFixed(pattern.substring(1)) : (rep * 100).toFixed(2)) + " %";
break;
case "x":
rep = toHex(Number(rep));
break;
case "X":
rep = toHex(Number(rep)).toUpperCase();
break;
default:
const m = /^(0+)(\.0+)?$/.exec(pattern);
if (m != null) {
let decs = 0;
if (m[2] != null) {
rep = rep.toFixed(decs = m[2].length - 1);
}
pad = "," + (m[1].length + (decs ? decs + 1 : 0)).toString();
padSymbol = "0";
} else if (pattern) {
rep = pattern;
}
}
} else if (typeof rep.ToString === "function") {
rep = rep.ToString(pattern);
} else if (rep instanceof Date) {
rep = (0, _Date.toString)(rep, pattern);
}
pad = parseInt((pad || "").substring(1), 10);
if (!isNaN(pad)) {
rep = padLeft(rep, Math.abs(pad), padSymbol, pad < 0);
}
return rep;
});
}
function endsWith(str, search) {
const idx = str.lastIndexOf(search);
return idx >= 0 && idx === str.length - search.length;
}
function initialize(n, f) {
if (n < 0) {
throw new Error("String length must be non-negative");
}
const xs = new Array(n);
for (let i = 0; i < n; i++) {
xs[i] = f(i);
}
return xs.join("");
}
function insert(str, startIndex, value) {
if (startIndex < 0 || startIndex > str.length) {
throw new Error("startIndex is negative or greater than the length of this instance.");
}
return str.substring(0, startIndex) + value + str.substring(startIndex);
}
function isNullOrEmpty(str) {
return typeof str !== "string" || str.length === 0;
}
function isNullOrWhiteSpace(str) {
return typeof str !== "string" || /^\s*$/.test(str);
}
function join(delimiter, xs) {
let xs2 = typeof xs === "string" ? [xs] : xs;
const len = arguments.length;
if (len > 2) {
xs2 = Array(len - 1);
for (let key = 1; key < len; key++) {
xs2[key - 1] = arguments[key];
}
} else if (!Array.isArray(xs2)) {
xs2 = Array.from(xs2);
}
return xs2.map(x => (0, _Util.toString)(x)).join(delimiter);
}
/** Validates UUID as specified in RFC4122 (versions 1-5). Trims braces. */
function validateGuid(str, doNotThrow) {
const trimmed = trim(str, "both", "{", "}");
if (guidRegex.test(trimmed)) {
return doNotThrow ? [true, trimmed] : trimmed;
} else if (doNotThrow) {
return [false, "00000000-0000-0000-0000-000000000000"];
}
throw new Error("Guid should contain 32 digits with 4 dashes: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
}
/* tslint:disable */
// From https://gist.github.com/LeverOne/1308368
function newGuid() {
let b = "";
for (let a = 0; a++ < 36; b += a * 51 & 52 ? (a ^ 15 ? 8 ^ Math.random() * (a ^ 20 ? 16 : 4) : 4).toString(16) : "-");
return b;
}
// Maps for number <-> hex string conversion
let _convertMapsInitialized = false;
let _byteToHex;
let _hexToByte;
function initConvertMaps() {
_byteToHex = new Array(256);
_hexToByte = {};
for (var i = 0; i < 256; i++) {
_byteToHex[i] = (i + 0x100).toString(16).substr(1);
_hexToByte[_byteToHex[i]] = i;
}
_convertMapsInitialized = true;
}
/** Parse a UUID into it's component bytes */
// Adapted from https://github.com/zefferus/uuid-parse
function guidToArray(s) {
if (!_convertMapsInitialized) {
initConvertMaps();
}
let i = 0;
const buf = new Uint8Array(16);
s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) {
switch (i) {
// .NET saves first three byte groups with differten endianness
// See https://stackoverflow.com/a/16722909/3922220
case 0:
case 1:
case 2:
case 3:
buf[3 - i++] = _hexToByte[oct];
break;
case 4:
case 5:
buf[9 - i++] = _hexToByte[oct];
break;
case 6:
case 7:
buf[13 - i++] = _hexToByte[oct];
break;
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
buf[i++] = _hexToByte[oct];
break;
}
});
// Zero out remaining bytes if string was short
while (i < 16) {
buf[i++] = 0;
}
return buf;
}
/** Convert UUID byte array into a string */
function arrayToGuid(buf) {
if (buf.length !== 16) {
throw new Error("Byte array for GUID must be exactly 16 bytes long");
}
if (!_convertMapsInitialized) {
initConvertMaps();
}
return _byteToHex[buf[3]] + _byteToHex[buf[2]] + _byteToHex[buf[1]] + _byteToHex[buf[0]] + "-" + _byteToHex[buf[5]] + _byteToHex[buf[4]] + "-" + _byteToHex[buf[7]] + _byteToHex[buf[6]] + "-" + _byteToHex[buf[8]] + _byteToHex[buf[9]] + "-" + _byteToHex[buf[10]] + _byteToHex[buf[11]] + _byteToHex[buf[12]] + _byteToHex[buf[13]] + _byteToHex[buf[14]] + _byteToHex[buf[15]];
}
/* tslint:enable */
function notSupported(name) {
throw new Error("The environment doesn't support '" + name + "', please use a polyfill.");
}
function toBase64String(inArray) {
let str = "";
for (let i = 0; i < inArray.length; i++) {
str += String.fromCharCode(inArray[i]);
}
return typeof btoa === "function" ? btoa(str) : notSupported("btoa");
}
function fromBase64String(b64Encoded) {
const binary = typeof atob === "function" ? atob(b64Encoded) : notSupported("atob");
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
function padLeft(str, len, ch, isRight) {
ch = ch || " ";
str = String(str);
len = len - str.length;
for (let i = 0; i < len; i++) {
str = isRight ? str + ch : ch + str;
}
return str;
}
function padRight(str, len, ch) {
return padLeft(str, len, ch, true);
}
function remove(str, startIndex, count) {
if (startIndex >= str.length) {
throw new Error("startIndex must be less than length of string");
}
if (typeof count === "number" && startIndex + count > str.length) {
throw new Error("Index and count must refer to a location within the string.");
}
return str.slice(0, startIndex) + (typeof count === "number" ? str.substr(startIndex + count) : "");
}
function replace(str, search, replace) {
return str.replace(new RegExp((0, _RegExp.escape)(search), "g"), replace);
}
function replicate(n, x) {
return initialize(n, () => x);
}
function getCharAtIndex(input, index) {
if (index < 0 || index > input.length) {
throw new Error("System.IndexOutOfRangeException: Index was outside the bounds of the array.");
}
return input[index];
}
function split(str, splitters, count, removeEmpty) {
count = typeof count === "number" ? count : null;
removeEmpty = typeof removeEmpty === "number" ? removeEmpty : null;
if (count < 0) {
throw new Error("Count cannot be less than zero");
}
if (count === 0) {
return [];
}
let splitters2 = splitters;
if (!Array.isArray(splitters)) {
const len = arguments.length;
splitters2 = Array(len - 1);
for (let key = 1; key < len; key++) {
splitters2[key - 1] = arguments[key];
}
}
splitters2 = splitters2.map(x => (0, _RegExp.escape)(x));
splitters2 = splitters2.length > 0 ? splitters2 : [" "];
let i = 0;
const splits = [];
const reg = new RegExp(splitters2.join("|"), "g");
while (count == null || count > 1) {
const m = reg.exec(str);
if (m === null) {
break;
}
if (!removeEmpty || m.index - i > 0) {
count = count != null ? count - 1 : count;
splits.push(str.substring(i, m.index));
}
i = reg.lastIndex;
}
if (!removeEmpty || str.length - i > 0) {
splits.push(str.substring(i));
}
return splits;
}
function trim(str, side, ...chars) {
if (side === "both" && chars.length === 0) {
return str.trim();
}
if (side === "start" || side === "both") {
const reg = chars.length === 0 ? /^\s+/ : new RegExp("^[" + (0, _RegExp.escape)(chars.join("")) + "]+");
str = str.replace(reg, "");
}
if (side === "end" || side === "both") {
const reg = chars.length === 0 ? /\s+$/ : new RegExp("[" + (0, _RegExp.escape)(chars.join("")) + "]+$");
str = str.replace(reg, "");
}
return str;
}
function filter(pred, x) {
return x.split("").filter(pred).join("");
}
+17
View File
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setType = setType;
exports.getType = getType;
const types = new Map();
function setType(fullName, cons) {
types.set(fullName, cons);
}
function getType(fullName) {
return types.get(fullName);
}
exports.default = {
reflection: Symbol("reflection")
};
+560
View File
@@ -0,0 +1,560 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ObjectRef = exports.Function = exports.Array = exports.Unit = exports.Any = exports.NonDeclaredType = undefined;
exports.Option = Option;
exports.Tuple = Tuple;
exports.GenericParam = GenericParam;
exports.Interface = Interface;
exports.makeGeneric = makeGeneric;
exports.isGeneric = isGeneric;
exports.getDefinition = getDefinition;
exports.extendInfo = extendInfo;
exports.hasInterface = hasInterface;
exports.getPropertyNames = getPropertyNames;
exports.isArray = isArray;
exports.toString = toString;
exports.getHashCode = getHashCode;
exports.hash = hash;
exports.equals = equals;
exports.comparePrimitives = comparePrimitives;
exports.compare = compare;
exports.lessThan = lessThan;
exports.lessOrEqual = lessOrEqual;
exports.greaterThan = greaterThan;
exports.greaterOrEqual = greaterOrEqual;
exports.equalsRecords = equalsRecords;
exports.compareRecords = compareRecords;
exports.equalsUnions = equalsUnions;
exports.compareUnions = compareUnions;
exports.createDisposable = createDisposable;
exports.createAtom = createAtom;
exports.createObj = createObj;
exports.toPlainJsObj = toPlainJsObj;
exports.jsOptions = jsOptions;
exports.round = round;
exports.sign = sign;
exports.randomNext = randomNext;
exports.applyOperator = applyOperator;
exports.unescapeDataString = unescapeDataString;
exports.escapeDataString = escapeDataString;
exports.escapeUriString = escapeUriString;
exports.clear = clear;
var _Date = require("./Date");
var _Symbol = require("./Symbol");
var _Symbol2 = _interopRequireDefault(_Symbol);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class NonDeclaredType {
constructor(kind, definition, generics) {
this.kind = kind;
this.definition = definition;
this.generics = generics;
}
Equals(other) {
if (this.kind === other.kind && this.definition === other.definition) {
return typeof this.generics === "object"
// equalsRecords should also work for Type[] (tuples)
? equalsRecords(this.generics, other.generics) : this.generics === other.generics;
}
return false;
}
}
exports.NonDeclaredType = NonDeclaredType;
const Any = exports.Any = new NonDeclaredType("Any");
const Unit = exports.Unit = new NonDeclaredType("Unit");
function Option(t) {
return new NonDeclaredType("Option", null, [t]);
}
function FableArray(t, isTypedArray = false) {
let def = null;
let genArg = null;
if (isTypedArray) {
def = t;
} else {
genArg = t;
}
return new NonDeclaredType("Array", def, [genArg]);
}
exports.Array = FableArray;
function Tuple(types) {
return new NonDeclaredType("Tuple", null, types);
}
function FableFunction(types) {
return new NonDeclaredType("Function", null, types);
}
exports.Function = FableFunction;
function GenericParam(definition) {
return new NonDeclaredType("GenericParam", definition);
}
function Interface(definition) {
return new NonDeclaredType("Interface", definition);
}
function makeGeneric(typeDef, genArgs) {
return new NonDeclaredType("GenericType", typeDef, genArgs);
}
function isGeneric(typ) {
return typ instanceof NonDeclaredType && typ.kind === "GenericType";
}
/**
* Returns the parent if this is a declared generic type or the argument otherwise.
* Attention: Unlike .NET this doesn't throw an exception if type is not generic.
*/
function getDefinition(typ) {
return isGeneric(typ) ? typ.definition : typ;
}
function extendInfo(cons, info) {
const parent = Object.getPrototypeOf(cons.prototype);
if (typeof parent[_Symbol2.default.reflection] === "function") {
const newInfo = {};
const parentInfo = parent[_Symbol2.default.reflection]();
Object.getOwnPropertyNames(info).forEach(k => {
const i = info[k];
if (typeof i === "object") {
newInfo[k] = Array.isArray(i) ? (parentInfo[k] || []).concat(i) : Object.assign(parentInfo[k] || {}, i);
} else {
newInfo[k] = i;
}
});
return newInfo;
}
return info;
}
function hasInterface(obj, interfaceName) {
if (interfaceName === "System.Collections.Generic.IEnumerable") {
return typeof obj[Symbol.iterator] === "function";
} else if (typeof obj[_Symbol2.default.reflection] === "function") {
const interfaces = obj[_Symbol2.default.reflection]().interfaces;
return Array.isArray(interfaces) && interfaces.indexOf(interfaceName) > -1;
}
return false;
}
/**
* Returns:
* - Records: array with names of fields
* - Classes: array with names of getters
* - Nulls and unions: empty array
* - JS Objects: The result of calling Object.getOwnPropertyNames
*/
function getPropertyNames(obj) {
if (obj == null) {
return [];
}
const propertyMap = typeof obj[_Symbol2.default.reflection] === "function" ? obj[_Symbol2.default.reflection]().properties || [] : obj;
return Object.getOwnPropertyNames(propertyMap);
}
function isArray(obj) {
return Array.isArray(obj) || ArrayBuffer.isView(obj);
}
function toString(obj, quoteStrings = false) {
function isObject(x) {
return x !== null && typeof x === "object" && !(x instanceof Number) && !(x instanceof String) && !(x instanceof Boolean);
}
if (obj == null || typeof obj === "number") {
return String(obj);
}
if (typeof obj === "string") {
return quoteStrings ? JSON.stringify(obj) : obj;
}
if (obj instanceof Date) {
return (0, _Date.toString)(obj);
}
if (typeof obj.ToString === "function") {
return obj.ToString();
}
if (hasInterface(obj, "FSharpUnion")) {
const info = obj[_Symbol2.default.reflection]();
const uci = info.cases[obj.tag];
switch (uci.length) {
case 1:
return uci[0];
case 2:
// For simplicity let's always use parens, in .NET they're ommitted in some cases
return uci[0] + " (" + toString(obj.data, true) + ")";
default:
return uci[0] + " (" + obj.data.map(x => toString(x, true)).join(",") + ")";
}
}
try {
return JSON.stringify(obj, (k, v) => {
return v && v[Symbol.iterator] && !Array.isArray(v) && isObject(v) ? Array.from(v) : v && typeof v.ToString === "function" ? toString(v) : v;
});
} catch (err) {
// Fallback for objects with circular references
return "{" + Object.getOwnPropertyNames(obj).map(k => k + ": " + String(obj[k])).join(", ") + "}";
}
}
class ObjectRef {
static id(o) {
if (!ObjectRef.idMap.has(o)) {
ObjectRef.idMap.set(o, ++ObjectRef.count);
}
return ObjectRef.idMap.get(o);
}
}
exports.ObjectRef = ObjectRef;
ObjectRef.idMap = new WeakMap();
ObjectRef.count = 0;
function getHashCode(x) {
return ObjectRef.id(x) * 2654435761 | 0;
}
function hash(x) {
if (typeof x === typeof 1) {
return x * 2654435761 | 0;
}
if (x != null && typeof x.GetHashCode === "function") {
return x.GetHashCode();
} else {
const s = toString(x);
let h = 5381;
let i = 0;
const len = s.length;
while (i < len) {
h = h * 33 ^ s.charCodeAt(i++);
}
return h;
}
}
function equals(x, y) {
// Optimization if they are referencially equal
if (x === y) {
return true;
} else if (x == null) {
return y == null;
} else if (y == null) {
return false;
} else if (typeof x !== "object" || typeof y !== "object") {
return x === y;
// Equals override or IEquatable implementation
} else if (typeof x.Equals === "function") {
return x.Equals(y);
} else if (typeof y.Equals === "function") {
return y.Equals(x);
} else if (Object.getPrototypeOf(x) !== Object.getPrototypeOf(y)) {
return false;
} else if (Array.isArray(x)) {
if (x.length !== y.length) {
return false;
}
for (let i = 0; i < x.length; i++) {
if (!equals(x[i], y[i])) {
return false;
}
}
return true;
} else if (ArrayBuffer.isView(x)) {
if (x.byteLength !== y.byteLength) {
return false;
}
const dv1 = new DataView(x.buffer);
const dv2 = new DataView(y.buffer);
for (let i = 0; i < x.byteLength; i++) {
if (dv1.getUint8(i) !== dv2.getUint8(i)) {
return false;
}
}
return true;
} else if (x instanceof Date) {
return x.getTime() === y.getTime();
} else {
return false;
}
}
function comparePrimitives(x, y) {
return x === y ? 0 : x < y ? -1 : 1;
}
function compare(x, y) {
// Optimization if they are referencially equal
if (x === y) {
return 0;
} else if (x == null) {
return y == null ? 0 : -1;
} else if (y == null) {
return 1; // everything is bigger than null
} else if (typeof x !== "object" || typeof y !== "object") {
return x === y ? 0 : x < y ? -1 : 1;
// Some types (see Long.ts) may just implement the function and not the interface
// else if (hasInterface(x, "System.IComparable"))
} else if (typeof x.CompareTo === "function") {
return x.CompareTo(y);
} else if (typeof y.CompareTo === "function") {
return y.CompareTo(x) * -1;
} else if (Object.getPrototypeOf(x) !== Object.getPrototypeOf(y)) {
return -1;
} else if (Array.isArray(x)) {
if (x.length !== y.length) {
return x.length < y.length ? -1 : 1;
}
for (let i = 0, j = 0; i < x.length; i++) {
j = compare(x[i], y[i]);
if (j !== 0) {
return j;
}
}
return 0;
} else if (ArrayBuffer.isView(x)) {
if (x.byteLength !== y.byteLength) {
return x.byteLength < y.byteLength ? -1 : 1;
}
const dv1 = new DataView(x.buffer);
const dv2 = new DataView(y.buffer);
for (let i = 0, b1 = 0, b2 = 0; i < x.byteLength; i++) {
b1 = dv1.getUint8(i), b2 = dv2.getUint8(i);
if (b1 < b2) {
return -1;
}
if (b1 > b2) {
return 1;
}
}
return 0;
} else if (x instanceof Date) {
return (0, _Date.compare)(x, y);
} else if (typeof x === "object") {
const xhash = hash(x);
const yhash = hash(y);
if (xhash === yhash) {
return equals(x, y) ? 0 : -1;
} else {
return xhash < yhash ? -1 : 1;
}
} else {
return x < y ? -1 : 1;
}
}
function lessThan(x, y) {
return compare(x, y) < 0;
}
function lessOrEqual(x, y) {
return compare(x, y) <= 0;
}
function greaterThan(x, y) {
return compare(x, y) > 0;
}
function greaterOrEqual(x, y) {
return compare(x, y) >= 0;
}
function equalsRecords(x, y) {
// Optimization if they are referencially equal
if (x === y) {
return true;
} else {
const keys = getPropertyNames(x);
for (const key of keys) {
if (!equals(x[key], y[key])) {
return false;
}
}
return true;
}
}
function compareRecords(x, y) {
// Optimization if they are referencially equal
if (x === y) {
return 0;
} else {
const keys = getPropertyNames(x);
for (const key of keys) {
const res = compare(x[key], y[key]);
if (res !== 0) {
return res;
}
}
return 0;
}
}
function equalsUnions(x, y) {
return x === y || x.tag === y.tag && equals(x.data, y.data);
}
function compareUnions(x, y) {
if (x === y) {
return 0;
} else {
const res = x.tag < y.tag ? -1 : x.tag > y.tag ? 1 : 0;
return res !== 0 ? res : compare(x.data, y.data);
}
}
function createDisposable(f) {
return {
Dispose: f,
[_Symbol2.default.reflection]() {
return { interfaces: ["System.IDisposable"] };
}
};
}
// tslint forbids non-arrow functions, but it's
// necessary here to use the arguments object
/* tslint:disable */
function createAtom(value) {
let atom = value;
return function () {
return arguments.length === 0 ? atom : (atom = arguments[0], void 0);
};
}
/* tslint:enable */
const CaseRules = {
None: 0,
LowerFirst: 1
};
function isList(o) {
if (o != null) {
if (typeof o[_Symbol2.default.reflection] === "function") {
return o[_Symbol2.default.reflection]().type === "Microsoft.FSharp.Collections.FSharpList";
}
}
return false;
}
function createObj(fields, caseRule = CaseRules.None, casesCache) {
const iter = fields[Symbol.iterator]();
let cur = iter.next();
const o = {};
while (!cur.done) {
const value = cur.value;
if (Array.isArray(value)) {
o[value[0]] = value[1];
} else {
casesCache = casesCache || new Map();
const proto = Object.getPrototypeOf(value);
let cases = casesCache.get(proto);
if (cases == null) {
if (typeof proto[_Symbol2.default.reflection] === "function") {
cases = proto[_Symbol2.default.reflection]().cases;
casesCache.set(proto, cases);
}
}
const caseInfo = cases != null ? cases[value.tag] : null;
if (Array.isArray(caseInfo)) {
let key = caseInfo[0];
if (caseRule === CaseRules.LowerFirst) {
key = key[0].toLowerCase() + key.substr(1);
}
o[key] = caseInfo.length === 1 ? true : isList(value.data) ? createObj(value.data, caseRule, casesCache) : value.data;
} else {
throw new Error("Cannot infer key and value of " + value);
}
}
cur = iter.next();
}
return o;
}
function toPlainJsObj(source) {
if (source != null && source.constructor !== Object) {
const target = {};
let props = Object.getOwnPropertyNames(source);
for (const p of props) {
target[p] = source[p];
}
// Copy also properties from prototype, see #192
const proto = Object.getPrototypeOf(source);
if (proto != null) {
props = Object.getOwnPropertyNames(proto);
for (const p of props) {
const prop = Object.getOwnPropertyDescriptor(proto, p);
if (prop.value) {
target[p] = prop.value;
} else if (prop.get) {
target[p] = prop.get.apply(source);
}
}
}
return target;
} else {
return source;
}
}
function jsOptions(mutator) {
const opts = {};
mutator(opts);
return opts;
}
function round(value, digits = 0) {
const m = Math.pow(10, digits);
const n = +(digits ? value * m : value).toFixed(8);
const i = Math.floor(n);
const f = n - i;
const e = 1e-8;
const r = f > 0.5 - e && f < 0.5 + e ? i % 2 === 0 ? i : i + 1 : Math.round(n);
return digits ? r / m : r;
}
function sign(x) {
return x > 0 ? 1 : x < 0 ? -1 : 0;
}
function randomNext(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function applyOperator(x, y, operator) {
function getMethod(obj) {
if (typeof obj === "object") {
const cons = Object.getPrototypeOf(obj).constructor;
if (typeof cons[operator] === "function") {
return cons[operator];
}
}
return null;
}
let meth = getMethod(x);
if (meth != null) {
return meth(x, y);
}
meth = getMethod(y);
if (meth != null) {
return meth(x, y);
}
switch (operator) {
case "op_Addition":
return x + y;
case "op_Subtraction":
return x - y;
case "op_Multiply":
return x * y;
case "op_Division":
return x / y;
case "op_Modulus":
return x % y;
case "op_LeftShift":
return x << y;
case "op_RightShift":
return x >> y;
case "op_BitwiseAnd":
return x & y;
case "op_BitwiseOr":
return x | y;
case "op_ExclusiveOr":
return x ^ y;
case "op_LogicalNot":
return x + y;
case "op_UnaryNegation":
return !x;
case "op_BooleanAnd":
return x && y;
case "op_BooleanOr":
return x || y;
default:
return null;
}
}
function unescapeDataString(s) {
// https://stackoverflow.com/a/4458580/524236
return decodeURIComponent(s.replace(/\+/g, "%20"));
}
function escapeDataString(s) {
return encodeURIComponent(s).replace(/!/g, "%21").replace(/'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29").replace(/\*/g, "%2A");
}
function escapeUriString(s) {
return encodeURI(s);
}
// ICollection.Clear method can be called on IDictionary
// too so we need to make a runtime check (see #1120)
function clear(col) {
if (Array.isArray(col)) {
col.splice(0);
} else {
col.clear();
}
}
+22
View File
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.esKeywords = exports.keywords = exports.reserved = undefined;
var _Set = require("./fable-core/Set");
var _List = require("./fable-core/List");
var _Comparer = require("./fable-core/Comparer");
var _Comparer2 = _interopRequireDefault(_Comparer);
var _Util = require("./fable-core/Util");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const reserved = exports.reserved = (0, _Set.create)((0, _List.ofArray)(["atomic", "break", "checked", "component", "const", "constraint", "constructor", "continue", "eager", "event", "external", "fixed", "functor", "include", "measure", "method", "mixin", "object", "parallel", "params", "process", "protected", "pure", "sealed", "tailcall", "trait", "virtual", "volatile", "asr", "land", "lor", "lsl", "lsr", "lxor", "mod", "sig"]), new _Comparer2.default(_Util.comparePrimitives));
const keywords = exports.keywords = (0, _Set.create)((0, _List.ofArray)(["abstract", "and", "as", "assert", "base", "begin", "class", "default", "delegate", "do", "done", "downcast", "downto", "elif", "else", "end", "exception", "extern", "false", "finally", "for", "fun", "function", "global", "if", "in", "inherit", "inline", "interface", "internal", "lazy", "let", "match", "member", "module", "mutable", "namespace", "new", "null", "of", "open", "or", "override", "private", "public", "rec", "return", "sig", "static", "struct", "then", "to", "true", "try", "type", "upcast", "use", "val", "void", "when", "while", "with", "yield"]), new _Comparer2.default(_Util.comparePrimitives));
const esKeywords = exports.esKeywords = (0, _Set.create)((0, _List.ofArray)(["Readonly", "Partial", "Pick", "HTMLDialogElement", "HTMLWebViewElement"]), new _Comparer2.default(_Util.comparePrimitives));
+361
View File
@@ -0,0 +1,361 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.primatives = exports.$7C$Digit$7C$_$7C$ = exports.$7C$Capital$7C$_$7C$ = undefined;
exports.isDigit = isDigit;
exports.createEnumNameParts = createEnumNameParts;
exports.capitalize = capitalize;
exports.lowerFirst = lowerFirst;
exports.createEnumName = createEnumName;
exports.nameEqualsDefaultFableValue = nameEqualsDefaultFableValue;
exports.createModuleNameParts = createModuleNameParts;
exports.escapeWord = escapeWord;
exports.fixModuleName = fixModuleName;
exports.removeQuotes = removeQuotes;
exports.getJsModuleName = getJsModuleName;
exports.fixNamespaceString = fixNamespaceString;
var _Seq = require("./fable-core/Seq");
var _Util = require("./fable-core/Util");
var _Option = require("./fable-core/Option");
var _List = require("./fable-core/List");
var _List2 = _interopRequireDefault(_List);
var _CurriedLambda = require("./fable-core/CurriedLambda");
var _CurriedLambda2 = _interopRequireDefault(_CurriedLambda);
var _String = require("./fable-core/String");
var _keywords = require("./keywords");
var _Set = require("./fable-core/Set");
var _Comparer = require("./fable-core/Comparer");
var _Comparer2 = _interopRequireDefault(_Comparer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _Capital___(letter) {
const capitals = (0, _Seq.map)(function (value) {
return value;
}, (0, _Seq.toList)((0, _Seq.rangeChar)("A", "Z")));
const matchValue = (0, _Seq.exists)($var1 => (0, _Util.equals)(letter, $var1), capitals);
if (matchValue) {
return letter;
} else {
return null;
}
}
exports.$7C$Capital$7C$_$7C$ = _Capital___;
const digits = (0, _Seq.map)(function (value) {
return value;
}, (0, _Seq.toList)((0, _Seq.rangeChar)("0", "9")));
function isDigit(digit) {
return (0, _Seq.exists)($var2 => (0, _Util.equals)(digit, $var2), digits);
}
function _Digit___(digit) {
const matchValue = isDigit(digit);
if (matchValue) {
return digit;
} else {
return null;
}
}
exports.$7C$Digit$7C$_$7C$ = _Digit___;
function createEnumNameParts(name) {
const tokens = (0, _Seq.map)(function (value) {
return value;
}, name);
const splitParts = function (part, parts, _arg1) {
splitParts: while (true) {
let $var3;
if (_arg1.tail != null) {
const activePatternResult1148 = _Digit___(_arg1.head);
if (activePatternResult1148 != null) {
if (parts.tail == null ? part === "" : false) {
$var3 = [1, (0, _Option.getValue)(activePatternResult1148), _arg1.tail];
} else {
$var3 = [2];
}
} else {
$var3 = [2];
}
} else {
$var3 = [0];
}
switch ($var3[0]) {
case 0:
return new _List2.default(part, parts);
case 1:
part = "N" + $var3[1];
parts = parts;
_arg1 = $var3[2];
continue splitParts;
case 2:
let $var4;
if (_arg1.tail != null) {
const activePatternResult1147 = _Capital___(_arg1.head);
if (activePatternResult1147 != null) {
if (part === "") {
$var4 = [0, (0, _Option.getValue)(activePatternResult1147), _arg1.tail];
} else {
$var4 = [1];
}
} else {
$var4 = [1];
}
} else {
$var4 = [1];
}
switch ($var4[0]) {
case 0:
part = $var4[1];
parts = parts;
_arg1 = $var4[2];
continue splitParts;
case 1:
let $var5;
if (_arg1.tail != null) {
const activePatternResult1146 = _Capital___(_arg1.head);
if (activePatternResult1146 != null) {
$var5 = [0, (0, _Option.getValue)(activePatternResult1146), _arg1.tail];
} else {
$var5 = [1];
}
} else {
$var5 = [1];
}
switch ($var5[0]) {
case 0:
const $var7 = $var5[1];
parts = new _List2.default(part, parts);
_arg1 = $var5[2];
part = $var7;
continue splitParts;
case 1:
if (_arg1.tail != null) {
if (_arg1.head === "-") {
const $var8 = "";
parts = new _List2.default(part, parts);
_arg1 = _arg1.tail;
part = $var8;
continue splitParts;
} else {
part = part + _arg1.head;
parts = parts;
_arg1 = _arg1.tail;
continue splitParts;
}
} else {
throw new Error("C:/projects/ts2fable/src/naming.fs", 27, 8);
}
}
}
}
}
};
return (0, _List.reverse)((0, _CurriedLambda2.default)(splitParts)("", new _List2.default())((0, _Seq.toList)(tokens)));
}
function capitalize(input) {
if ((0, _String.isNullOrWhiteSpace)(input)) {
return "";
} else {
return (0, _String.toText)((0, _String.printf)("%c%s"))(input[0].toLocaleUpperCase(), input.substr(1));
}
}
function lowerFirst(input) {
if ((0, _String.isNullOrWhiteSpace)(input)) {
return "";
} else {
return (0, _String.toText)((0, _String.printf)("%c%s"))(input[0].toLocaleLowerCase(), input.substr(1));
}
}
function createEnumName(s) {
if ((0, _String.isNullOrWhiteSpace)(s)) {
return "Empty";
} else {
return (0, _String.join)("", function (list) {
return (0, _List.map)(capitalize, list);
}(createEnumNameParts(s)));
}
}
function nameEqualsDefaultFableValue(name, value) {
const defaultFableValue = (0, _String.toText)((0, _String.printf)("%s%s"))(name.substr(0, 1).toLocaleLowerCase(), name.substr(1));
return defaultFableValue === value;
}
function createModuleNameParts(name) {
const tokens = (0, _Seq.map)(function (value) {
return value;
}, name);
const splitParts = function (part, parts, _arg1) {
splitParts: while (true) {
if (_arg1.tail != null) {
if (_arg1.head === "-") {
const $var9 = "";
parts = new _List2.default(part, parts);
_arg1 = _arg1.tail;
part = $var9;
continue splitParts;
} else if (_arg1.head === "/") {
const $var10 = "";
parts = new _List2.default(part, parts);
_arg1 = _arg1.tail;
part = $var10;
continue splitParts;
} else if (_arg1.head === ".") {
const $var11 = "";
parts = new _List2.default(part, parts);
_arg1 = _arg1.tail;
part = $var11;
continue splitParts;
} else {
part = part + _arg1.head;
parts = parts;
_arg1 = _arg1.tail;
continue splitParts;
}
} else {
return new _List2.default(part, parts);
}
}
};
return (0, _List.reverse)((0, _CurriedLambda2.default)(splitParts)("", new _List2.default())((0, _Seq.toList)(tokens)));
}
function escapeWord(s) {
if ((0, _String.isNullOrEmpty)(s)) {
return "";
} else {
const s_1 = (0, _String.replace)(s, "'", "");
if (((((_keywords.reserved.has(s_1) ? true : _keywords.keywords.has(s_1)) ? true : (0, _String.indexOfAny)(s_1, ["-", "/", "$"]) !== -1) ? true : isDigit(s_1.substr(0, 1))) ? true : (0, _String.indexOfAny)(s_1.substr(0, 1), [".", "["]) !== -1) ? true : s_1 === "_") {
return (0, _String.toText)((0, _String.printf)("``%s``"))(s_1);
} else {
return s_1;
}
}
}
function fixModuleName(s) {
const s_1 = (0, _String.replace)(s, "'", "");
const s_2 = capitalize(s_1);
let s_3;
const parts = createModuleNameParts(s_2);
s_3 = (0, _String.join)("_", parts);
const s_4 = (_keywords.reserved.has(s_3) ? true : _keywords.keywords.has(s_3)) ? (0, _String.toText)((0, _String.printf)("%s_"))(s_3) : s_3;
return s_4;
}
function removeQuotes(s) {
if (s == null) {
return "";
} else {
return (0, _String.replace)((0, _String.replace)(s, "\"", ""), "'", "");
}
}
function getJsModuleName(path) {
const parts = function (x) {
return (0, _List.filter)(function (s) {
return s !== "index.d.ts" ? s !== "types" : false;
}, (0, _List.ofArray)((0, _String.split)(x, "/")));
}(function (x_1) {
const is = x_1.lastIndexOf("@") | 0;
if (is === -1) {
return x_1;
} else {
return x_1.substr(is);
}
}(function (x_2) {
const inm = path.lastIndexOf("node_modules") | 0;
if (inm === -1) {
return x_2;
} else {
return x_2.substr(inm + 13);
}
}(path)));
let out;
const $var6 = parts.tail != null ? parts.head === "@types" ? parts.tail.tail != null ? [0, parts.tail.head, parts.tail.tail] : parts.head.indexOf("@") === 0 ? [1, parts.head, parts.tail] : [2] : parts.head.indexOf("@") === 0 ? [1, parts.head, parts.tail] : [2] : [2];
switch ($var6[0]) {
case 0:
const xs_ = new _List2.default((0, _String.replace)($var6[1], "__", "/"), $var6[2]);
out = (0, _String.join)("/", xs_);
break;
case 1:
out = (0, _String.join)("/", new _List2.default($var6[1], $var6[2]));
break;
case 2:
out = (0, _List.head)(parts);
break;
}
return (0, _String.replace)((0, _String.replace)(out, ".ts", ""), ".d", "");
}
const primatives = exports.primatives = (0, _Set.create)((0, _List.ofArray)(["string", "obj", "unit", "float", "bool"]), new _Comparer2.default(_Util.comparePrimitives));
function fixNamespaceString(name) {
if (primatives.has(name)) {
return name;
} else {
const parts = (0, _String.split)(name, ".");
if (parts.length === 1) {
return name;
} else {
const parts_1 = (0, _List.reverse)((0, _List.ofArray)(parts));
const parts_2 = function (list) {
return (0, _List.map)(fixModuleName, list);
}((0, _List.append)((0, _List.ofArray)([(0, _List.head)(parts_1)]), (0, _List.tail)(parts_1)));
return (0, _String.join)(".", (0, _List.reverse)(parts_2));
}
}
}
+338
View File
@@ -0,0 +1,338 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.printType = printType;
exports.printFunction = printFunction;
exports.printProperty = printProperty;
exports.printTypeParameters = printTypeParameters;
exports.printComments = printComments;
exports.printModule = printModule;
exports.printFsFile = printFsFile;
var _String = require("./fable-core/String");
var _Seq = require("./fable-core/Seq");
var _List = require("./fable-core/List");
var _syntax = require("./syntax");
var _Option = require("./fable-core/Option");
var _naming = require("./naming");
var _CurriedLambda = require("./fable-core/CurriedLambda");
var _CurriedLambda2 = _interopRequireDefault(_CurriedLambda);
var _version = require("./version");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function printType(tp) {
switch (tp.tag) {
case 7:
return tp.data.Name;
case 5:
return "obj";
case 4:
return (0, _String.toText)((0, _String.printf)("ResizeArray<%s>"))(printType(tp.data));
case 9:
if (tp.data.Types.length === 1) {
return (0, _String.toText)((0, _String.printf)("%s%s"))(printType((0, _Seq.item)(0, tp.data.Types)), tp.data.Option ? " option" : "");
} else {
const line = [];
line.push.bind(line)((0, _String.toText)((0, _String.printf)("U%d<"))(tp.data.Types.length));
line.push.bind(line)((0, _String.join)(", ", (0, _List.map)(printType, tp.data.Types)));
line.push.bind(line)((0, _String.toText)((0, _String.printf)(">%s"))(tp.data.Option ? " option" : ""));
return (0, _String.join)("", line);
}
case 11:
const line_1 = [];
line_1.push.bind(line_1)((0, _String.toText)((0, _String.printf)("%s"))(printType(tp.data.Type)));
if (tp.data.TypeParameters.length > 0) {
line_1.push.bind(line_1)("<");
line_1.push.bind(line_1)((0, _String.join)(", ", (0, _List.map)(printType, tp.data.TypeParameters)));
line_1.push.bind(line_1)(">");
}
return (0, _String.join)("", line_1);
case 8:
const line_2 = [];
const typs = tp.data.Params.length === 0 ? (0, _List.ofArray)([(0, _syntax.simpleType)("unit"), tp.data.ReturnType]) : (0, _List.append)((0, _List.map)(function (p) {
return p.Type;
}, tp.data.Params), (0, _List.ofArray)([tp.data.ReturnType]));
line_2.push.bind(line_2)("(");
line_2.push.bind(line_2)((0, _String.join)(" -> ", (0, _List.map)(printType, typs)));
line_2.push.bind(line_2)(")");
return (0, _String.join)("", line_2);
case 12:
const line_3 = [];
line_3.push.bind(line_3)((0, _String.join)(" * ", (0, _List.map)(printType, tp.data.Types)));
return (0, _String.join)("", line_3);
case 16:
const vtp = printType(tp.data.Type);
return (0, _String.toText)((0, _String.printf)("abstract %s: %s%s"))(tp.data.Name, vtp, tp.data.IsConst ? "" : " with get, set");
case 17:
return "string";
case 21:
return "obj";
default:
(0, _String.toConsole)((0, _String.printf)("unsupported printType %A"))(tp);
return "obj";
}
}
function printFunction(fn) {
const line = [];
if (fn.Kind.tag === 1) {
line.push.bind(line)("[<Emit \"new $0($1...)\">] ");
} else if (fn.Kind.tag === 2) {
line.push.bind(line)("[<Emit \"$0($1...)\">] ");
} else if (fn.Kind.tag === 3) {
line.push.bind(line)((0, _String.toText)((0, _String.printf)("[<Emit \"%s\">] "))(fn.Kind.data));
}
line.push.bind(line)((0, _String.toText)((0, _String.printf)("abstract %s"))((0, _Option.getValue)(fn.Name)));
const prms = (0, _List.map)(function (p) {
return p.ParamArray ? (0, _String.toText)((0, _String.printf)("[<ParamArray>] %s%s: %s"))(p.Optional ? "?" : "", p.Name, p.Type.tag === 4 ? printType(p.Type) : ((0, _String.toConsole)((0, _String.printf)("ParamArray function is not an array type: %s"))((0, _syntax.getName)(new _syntax.FsType(8, fn))), printType(p.Type))) : (0, _String.toText)((0, _String.printf)("%s%s: %s"))(p.Optional ? "?" : "", p.Name, printType(p.Type));
}, fn.Params);
if (prms.length === 0) {
line.push.bind(line)((0, _String.toText)((0, _String.printf)(": unit")));
} else {
line.push.bind(line)((0, _String.toText)((0, _String.printf)(": %s"))((0, _String.join)(" * ", prms)));
}
line.push.bind(line)((0, _String.toText)((0, _String.printf)(" -> %s"))(printType(fn.ReturnType)));
return (0, _String.join)("", line);
}
function printProperty(pr) {
return (0, _String.toText)((0, _String.printf)("%sabstract %s: %s%s%s%s"))(pr.Kind.tag === 1 ? "[<Emit \"$0[$1]{{=$2}}\">] " : "", pr.Name, pr.Index != null ? (0, _String.toText)((0, _String.printf)("%s: %s -> "))((0, _Option.getValue)(pr.Index).Name, printType((0, _Option.getValue)(pr.Index).Type)) : "", printType(pr.Type), pr.Option ? " option" : "", pr.IsReadonly ? "" : " with get, set");
}
function printTypeParameters(tps) {
if (tps.length === 0) {
return "";
} else {
const line = [];
line.push("<");
line.push.bind(line)((0, _String.join)(", ", (0, _List.map)(printType, tps)));
line.push(">");
return (0, _String.join)("", line);
}
}
function printComments(lines, indent, comments) {
if (function (list) {
return (0, _Seq.exists)(_syntax.FsCommentModule.isParam.bind(_syntax.FsCommentModule), list);
}(comments)) {
const summaryLines = function (list_1) {
return (0, _List.choose)(_syntax.FsCommentModule.asSummaryLine.bind(_syntax.FsCommentModule), list_1);
}(comments);
(0, _Seq.iterateIndexed)(function (i, desc) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s/// %s%s%s"))(indent, i === 0 ? "<summary>" : "", desc, i === summaryLines.length - 1 ? "</summary>" : ""));
}, summaryLines);
(0, _Seq.iterate)(function (comment) {
(0, _Seq.iterateIndexed)(function (i_1, desc_1) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s/// %s%s%s"))(indent, i_1 === 0 ? (0, _String.toText)((0, _String.printf)("<param name=\"%s\">"))(comment.Name) : "", desc_1, i_1 === comment.Description.length - 1 ? "</param>" : ""));
}, comment.Description);
}, function (list_2) {
return (0, _List.choose)(_syntax.FsCommentModule.asParam.bind(_syntax.FsCommentModule), list_2);
}(comments));
} else {
(0, _Seq.iterate)(function (comment_1) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s/// %s"))(indent, comment_1));
}, function (list_3) {
return (0, _List.choose)(_syntax.FsCommentModule.asSummaryLine.bind(_syntax.FsCommentModule), list_3);
}(comments));
}
}
function printModule(lines, indent, md) {
const lineCountStart = lines.length | 0;
let indent_1;
if (md.Name !== "") {
lines.push.bind(lines)("");
if (md.HasAttributes) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s[<%s)>]"))(indent, (0, _String.join)("; ", md.Attributes)));
}
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%smodule %s ="))(indent, md.Name));
indent_1 = (0, _String.toText)((0, _String.printf)("%s "))(indent);
} else {
indent_1 = indent;
}
for (let line of md.HelperLines) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s%s"))(indent_1, line));
}
for (let tp of md.Types) {
if (tp.tag === 20) {
if (tp.data.tag === 1) {
if (tp.data.data.Module !== tp.data.data.SpecifiedModule) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%smodule %s = %s"))(indent_1, tp.data.data.Module, tp.data.data.SpecifiedModule));
}
}
}
}
for (let tp_1 of md.Types) {
if (tp_1.tag === 20) {
if (tp_1.data.tag === 0) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%stype %s = %s.%s"))(indent_1, tp_1.data.data.Type, tp_1.data.data.SpecifiedModule, tp_1.data.data.Type));
}
}
}
for (let tp_2 of md.Types) {
switch (tp_2.tag) {
case 0:
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("")));
printComments(lines, indent_1, tp_2.data.Comments);
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%stype [<AllowNullLiteral>] %s%s ="))(indent_1, tp_2.data.Name, printTypeParameters(tp_2.data.TypeParameters)));
const nLines = {
contents: 0
};
for (let ih of tp_2.data.Inherits) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s inherit %s"))(indent_1, printType(ih)));
void nLines.contents++;
}
for (let mbr of tp_2.data.Members) {
if (mbr.tag === 8) {
const indent_2 = (0, _String.toText)((0, _String.printf)("%s "))(indent_1);
printComments(lines, indent_2, mbr.data.AllComments);
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s%s"))(indent_2, printFunction(mbr.data)));
void nLines.contents++;
} else if (mbr.tag === 2) {
const indent_3 = (0, _String.toText)((0, _String.printf)("%s "))(indent_1);
printComments(lines, indent_3, mbr.data.Comments);
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s%s"))(indent_3, printProperty(mbr.data)));
void nLines.contents++;
} else {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s %s"))(indent_1, printType(mbr)));
void nLines.contents++;
}
}
if (nLines.contents === 0) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s interface end"))(indent_1));
}
break;
case 1:
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("")));
const matchValue = tp_2.data.Type;
if (matchValue.tag === 1) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%stype [<StringEnum>] [<RequireQualifiedAccess>] %s ="))(indent_1, tp_2.data.Name));
for (let cs of tp_2.data.Cases) {
const v = function (option) {
return (0, _Option.defaultArg)(option, cs.Name);
}(cs.Value);
const unm = (0, _naming.createEnumName)(cs.Name);
const line_1 = [];
if ((0, _naming.nameEqualsDefaultFableValue)(unm, v)) {
line_1.push.bind(line_1)((0, _String.toText)((0, _String.printf)(" | %s"))(unm));
} else {
line_1.push.bind(line_1)((0, _String.toText)((0, _String.printf)(" | [<CompiledName \"%s\">] %s"))(v, unm));
}
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s%s"))(indent_1, (0, _String.join)("", line_1)));
}
} else if (matchValue.tag === 2) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%stype %s ="))(indent_1, tp_2.data.Name));
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s obj"))(indent_1));
} else {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%stype [<RequireQualifiedAccess>] %s ="))(indent_1, tp_2.data.Name));
for (let cs_1 of tp_2.data.Cases) {
const unm_1 = (0, _naming.createEnumName)(cs_1.Name);
const line_2 = [];
line_2.push.bind(line_2)((0, _String.toText)((0, _String.printf)(" | %s"))(unm_1));
if ((0, _CurriedLambda2.default)(() => cs_1.Value != null)()) {
line_2.push.bind(line_2)((0, _String.toText)((0, _String.printf)(" = %s"))((0, _Option.getValue)(cs_1.Value)));
}
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s%s"))(indent_1, (0, _String.join)("", line_2)));
}
}
break;
case 10:
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("")));
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%stype %s%s ="))(indent_1, tp_2.data.Name, printTypeParameters(tp_2.data.TypeParameters)));
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%s %s"))(indent_1, printType(tp_2.data.Type)));
break;
case 13:
printModule(lines, indent_1, tp_2.data);
break;
case 16:
if (tp_2.data.HasDeclare) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("%slet %s%s: %s = jsNative"))(indent_1, tp_2.data.Export != null ? (0, _Option.getValue)(tp_2.data.Export).IsGlobal ? "[<Global>] " : (0, _String.toText)((0, _String.printf)("[<Import(\"%s\",\"%s\")>] "))((0, _Option.getValue)(tp_2.data.Export).Selector, (0, _Option.getValue)(tp_2.data.Export).Path) : "", tp_2.data.Name, printType(tp_2.data.Type)));
}
break;
default:}
}
const addedLines = lines.length - lineCountStart | 0;
if (addedLines === 2) {
for (let forLoopVar = 0; forLoopVar <= 1; forLoopVar++) {
lines.splice(lines.length - 1, 1);
}
}
}
function printFsFile(file) {
const lines = [];
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("// ts2fable %s"))(_version.version));
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("module rec %s"))(file.Namespace));
for (let opn of file.Opens) {
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("open %s"))(opn));
}
lines.push.bind(lines)((0, _String.toText)((0, _String.printf)("")));
for (let f of file.Files) {
(0, _Seq.iterate)(function (md) {
printModule(lines, "", md);
}, (0, _List.filter)(function (md_1) {
return md_1.Types.length > 0;
}, f.Modules));
}
return lines;
}
+846
View File
@@ -0,0 +1,846 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Node$2E$ForEachChild = undefined;
exports.getPropertyName = getPropertyName;
exports.getBindingName = getBindingName;
exports.readEnumCase = readEnumCase;
exports.readTypeParameters = readTypeParameters;
exports.readInherits = readInherits;
exports.readCommentLines = readCommentLines;
exports.readComments = readComments;
exports.readCommentTags = readCommentTags;
exports.readCommentsForSignatureDeclaration = readCommentsForSignatureDeclaration;
exports.readCommentsAtLocation = readCommentsAtLocation;
exports.readInterface = readInterface;
exports.readTypeLiteral = readTypeLiteral;
exports.getFullTypeName = getFullTypeName;
exports.getFullNodeName = getFullNodeName;
exports.readClass = readClass;
exports.hasModifier = hasModifier;
exports.isConst = isConst;
exports.isNamespace = isNamespace;
exports.readVariable = readVariable;
exports.readEnum = readEnum;
exports.readTypeReference = readTypeReference;
exports.readFunctionType = readFunctionType;
exports.readTypeNode = readTypeNode;
exports.readParameterDeclaration = readParameterDeclaration;
exports.readMethodSignature = readMethodSignature;
exports.readMethodDeclaration = readMethodDeclaration;
exports.isReadOnly = isReadOnly;
exports.readPropertySignature = readPropertySignature;
exports.readPropertyNameComments = readPropertyNameComments;
exports.readPropertyDeclaration = readPropertyDeclaration;
exports.readFunctionDeclaration = readFunctionDeclaration;
exports.readIndexSignature = readIndexSignature;
exports.readCallSignature = readCallSignature;
exports.readConstructSignatureDeclaration = readConstructSignatureDeclaration;
exports.readConstructorDeclaration = readConstructorDeclaration;
exports.readNamedDeclaration = readNamedDeclaration;
exports.readAliasDeclaration = readAliasDeclaration;
exports.readExpressionText = readExpressionText;
exports.readExportAssignment = readExportAssignment;
exports.readImportDeclaration = readImportDeclaration;
exports.readStatement = readStatement;
exports.readModuleName = readModuleName;
exports.readModuleDeclaration = readModuleDeclaration;
exports.readSourceFile = readSourceFile;
var _Util = require("./fable-core/Util");
var _naming = require("./naming");
var _Option = require("./fable-core/Option");
var _syntax = require("./syntax");
var _Int = require("./fable-core/Int32");
var _String = require("./fable-core/String");
var _List = require("./fable-core/List");
var _List2 = _interopRequireDefault(_List);
var _Seq = require("./fable-core/Seq");
var _typescript = require("typescript");
var typescript = _interopRequireWildcard(_typescript);
var _CurriedLambda = require("./fable-core/CurriedLambda");
var _CurriedLambda2 = _interopRequireDefault(_CurriedLambda);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Node_ForEachChild(cbNode) {
this.forEachChild(nd => {
cbNode(nd);
return null;
}), void 0;
}
exports.Node$2E$ForEachChild = Node_ForEachChild;
function getPropertyName(pn) {
if ((0, _Util.hasInterface)(pn, "TypeScript.Ts.StringLiteral")) {
return pn.getText();
} else if ((0, _Util.hasInterface)(pn, "TypeScript.Ts.NumericLiteral")) {
return pn.getText();
} else if ((0, _Util.hasInterface)(pn, "TypeScript.Ts.ComputedPropertyName")) {
return pn.getText();
} else {
return (0, _naming.removeQuotes)(pn.getText());
}
}
function getBindingName(bn) {
if (true) {
if ((0, _Util.hasInterface)(bn, "TypeScript.Ts.ArrayBindingPattern")) {
return bn.getText();
} else {
return bn.getText();
}
} else {
return bn.getText();
}
}
function readEnumCase(em) {
const name = getPropertyName(em.name);
let patternInput_1;
const matchValue = em.initializer;
if (matchValue != null) {
const matchValue_1 = (0, _Option.getValue)(matchValue).kind | 0;
if (matchValue_1 === 8) {
const nl = (0, _Option.getValue)(matchValue);
patternInput_1 = [new _syntax.FsEnumCaseType(0), nl.text];
} else if (matchValue_1 === 9) {
const sl = (0, _Option.getValue)(matchValue);
patternInput_1 = [new _syntax.FsEnumCaseType(1), sl.text];
} else if (matchValue_1 === 192) {
const pue = (0, _Option.getValue)(matchValue);
const txt = pue.getText();
const patternInput = (0, _Int.tryParse)(txt, 10, 0);
if (patternInput[0]) {
patternInput_1 = [new _syntax.FsEnumCaseType(0), txt];
} else {
patternInput_1 = [new _syntax.FsEnumCaseType(2), null];
}
} else {
patternInput_1 = (0, _String.toFail)((0, _String.printf)("EnumCase type not supported %A %A"))((0, _Option.getValue)(matchValue).kind, name);
}
} else {
patternInput_1 = [new _syntax.FsEnumCaseType(2), null];
}
return new _syntax.FsEnumCase(name, patternInput_1[0], patternInput_1[1]);
}
function readTypeParameters(checker, tps) {
if (tps != null) {
return (0, _List.map)(function (tp) {
const matchValue = tp.default;
if (matchValue == null) {
return new _syntax.FsType(7, new _syntax.FsMapped(tp.name.getText(), getFullNodeName(checker, tp)));
} else {
return new _syntax.FsType(22, new _syntax.FsGenericParameterDefaults(readTypeNode(checker, (0, _Option.getValue)(matchValue)), tp.name.getText(), getFullNodeName(checker, tp)));
}
}, (0, _Seq.toList)((0, _Option.getValue)(tps)));
} else {
return new _List2.default();
}
}
function readInherits(checker, hcs) {
if (hcs != null) {
return (0, _List.collect)(function (hc) {
return (0, _List.map)(function (eta) {
const tp = readTypeNode(checker, eta);
let prms;
const matchValue = eta.typeArguments;
if (matchValue != null) {
prms = (0, _List.map)(function (t) {
return readTypeNode(checker, t);
}, (0, _Seq.toList)((0, _Option.getValue)(matchValue)));
} else {
prms = new _List2.default();
}
if (prms.length === 0) {
return tp;
} else {
return new _syntax.FsType(11, new _syntax.FsGenericType(tp, prms));
}
}, (0, _Seq.toList)(hc.types));
}, (0, _Seq.toList)((0, _Option.getValue)(hcs)));
} else {
return new _List2.default();
}
}
function readCommentLines(text) {
return (0, _List.ofArray)((0, _String.split)((0, _String.replace)((0, _String.replace)(text, "\r\n", "\n"), "\r", "\n"), "\n"));
}
function readComments(comments) {
if (comments.length === 0) {
return new _List2.default();
} else {
return (0, _List.collect)(function (dp) {
const matchValue = dp.kind;
if (matchValue === "text") {
return (0, _List.map)(function (arg0) {
return new _syntax.FsComment(0, arg0);
}, readCommentLines(dp.text));
} else {
return new _List2.default();
}
}, (0, _Seq.toList)(comments));
}
}
function readCommentTags(nd) {
const matchValue = typescript.getJSDocTags(nd);
if (matchValue != null) {
return (0, _List.collect)(function (tag) {
const matchValue_1 = tag.kind | 0;
if (matchValue_1 === 279) {
const matchValue_2 = tag.comment;
if (matchValue_2 != null) {
return (0, _List.ofArray)([new _syntax.FsComment(1, new _syntax.FsParamComment("", readCommentLines((0, _Option.getValue)(matchValue_2))))]);
} else {
return new _List2.default();
}
} else {
return (0, _List.ofArray)([new _syntax.FsComment(2, tag.comment)]);
}
}, (0, _Seq.toList)((0, _Option.getValue)(matchValue)));
} else {
return new _List2.default();
}
}
function readCommentsForSignatureDeclaration(checker, declaration) {
const matchValue = checker.getSignatureFromDeclaration(declaration);
if (matchValue != null) {
return readComments((0, _Option.getValue)(matchValue).getDocumentationComment());
} else {
return new _List2.default();
}
}
function readCommentsAtLocation(checker, nd) {
const matchValue = checker.getSymbolAtLocation(nd);
if (matchValue != null) {
return readComments((0, _Option.getValue)(matchValue).getDocumentationComment());
} else {
return new _List2.default();
}
}
function readInterface(checker, id) {
const Comments = readCommentsAtLocation(checker, id.name);
const Name = id.name.getText();
const FullName = getFullNodeName(checker, id);
const Inherits = readInherits(checker, id.heritageClauses);
const Members = (0, _List.map)(function (te) {
return readNamedDeclaration(checker, te);
}, (0, _Seq.toList)(id.members));
return new _syntax.FsInterface(Comments, false, false, Name, FullName, readTypeParameters(checker, id.typeParameters), Inherits, Members);
}
function readTypeLiteral(checker, tl) {
return new _syntax.FsTypeLiteral((0, _List.map)(function (te) {
return readNamedDeclaration(checker, te);
}, (0, _Seq.toList)(tl.members)));
}
function getFullTypeName(checker, tp) {
const matchValue = tp.symbol;
if (matchValue != null) {
return checker.getFullyQualifiedName((0, _Option.getValue)(matchValue));
} else {
return "";
}
}
function getFullNodeName(checker, nd) {
const matchValue = checker.getSymbolAtLocation(nd);
if (matchValue != null) {
return checker.getFullyQualifiedName((0, _Option.getValue)(matchValue));
} else {
return "";
}
}
function readClass(checker, cd) {
const fullName = getFullNodeName(checker, cd);
const Comments = (0, _Option.defaultArg)((0, _Option.defaultArg)(cd.name, null, function (nd) {
return readCommentsAtLocation(checker, nd);
}), new _List2.default());
let Name;
const matchValue = cd.name;
if (matchValue != null) {
Name = (0, _Option.getValue)(matchValue).getText();
} else {
Name = fullName;
}
const Inherits = readInherits(checker, cd.heritageClauses);
const Members = (0, _List.map)(function (te) {
return readNamedDeclaration(checker, te);
}, (0, _Seq.toList)(cd.members));
return new _syntax.FsInterface(Comments, false, true, Name, fullName, readTypeParameters(checker, cd.typeParameters), Inherits, Members);
}
function hasModifier(kind, modifiers) {
if (modifiers != null) {
return (0, _Seq.exists)(function (md) {
return md.kind === kind;
}, (0, _Option.getValue)(modifiers));
} else {
return false;
}
}
function isConst(nd) {
return (nd.flags | 2) !== 0;
}
function isNamespace(nd) {
return (0, _Seq.exists)(function (nd_1) {
return nd_1.kind === 129;
}, nd.getChildren());
}
function readVariable(checker, vb) {
return (0, _List.map)(function (vd) {
return new _syntax.FsType(16, new _syntax.FsVariable(null, hasModifier(124, vb.modifiers), getBindingName(vd.name), (0, _Option.defaultArg)((0, _Option.defaultArg)(vd.type, null, function (t) {
return readTypeNode(checker, t);
}), (0, _syntax.simpleType)("obj")), isConst(vd)));
}, (0, _Seq.toList)(vb.declarationList.declarations));
}
function readEnum(ed) {
return new _syntax.FsEnum(ed.name.getText(), (0, _List.map)(readEnumCase, (0, _Seq.toList)(ed.members)));
}
function readTypeReference(checker, tr) {
var typeName;
var matchValue_1;
const matchValue = tr.typeArguments;
if (matchValue != null) {
return new _syntax.FsType(11, new _syntax.FsGenericType((typeName = (matchValue_1 = tr.typeName, (0, _Util.hasInterface)(matchValue_1, "TypeScript.Ts.QualifiedName") ? matchValue_1.getText() : matchValue_1.getText()), typeName == null ? (0, _String.toFail)((0, _String.printf)("readTypeReference type name is null: %s"))(tr.getText()) : null, new _syntax.FsType(7, new _syntax.FsMapped(typeName, getFullNodeName(checker, tr)))), (0, _List.map)(function (t) {
return readTypeNode(checker, t);
}, (0, _Seq.toList)((0, _Option.getValue)(matchValue)))));
} else {
return new _syntax.FsType(7, new _syntax.FsMapped(tr.getText(), getFullNodeName(checker, tr)));
}
}
function readFunctionType(checker, ft) {
var matchValue;
return new _syntax.FsFunction(new _List2.default(), new _syntax.FsFunctionKind(0), hasModifier(115, ft.modifiers), (0, _Option.defaultArg)(ft.name, null, getPropertyName), readTypeParameters(checker, ft.typeParameters), (0, _List.map)(function (pd) {
return readParameterDeclaration(checker, pd);
}, (0, _Seq.toList)(ft.parameters)), (matchValue = ft.type, matchValue == null ? (0, _syntax.simpleType)("unit") : readTypeNode(checker, (0, _Option.getValue)(matchValue))));
}
function readTypeNode(checker, t) {
var ts;
readTypeNode: while (true) {
const matchValue = t.kind | 0;
switch (matchValue) {
case 136:
return (0, _syntax.simpleType)("string");
case 160:
return new _syntax.FsType(8, readFunctionType(checker, t));
case 159:
return readTypeReference(checker, t);
case 164:
const at = t;
return new _syntax.FsType(4, readTypeNode(checker, at.elementType));
case 133:
return (0, _syntax.simpleType)("float");
case 122:
return (0, _syntax.simpleType)("bool");
case 166:
const un = t;
const typs = (0, _Seq.toList)(un.types);
const isOption = function (t_1) {
if (t_1.kind === 139) {
return true;
} else {
return t_1.kind === 95;
}
};
return new _syntax.FsType(9, new _syntax.FsUnion((0, _Seq.exists)(isOption, typs), (ts = (0, _List.map)(function (t_2) {
return readTypeNode(checker, t_2);
}, (0, _List.filter)($var1 => function (value) {
return !value;
}(isOption($var1)), typs)), ts.length === 0 ? (0, _List.ofArray)([(0, _syntax.simpleType)("obj")]) : ts)));
case 119:
return new _syntax.FsType(9, new _syntax.FsUnion(true, (0, _List.ofArray)([(0, _syntax.simpleType)("obj")])));
case 105:
return (0, _syntax.simpleType)("unit");
case 165:
const tp = t;
return new _syntax.FsType(12, new _syntax.FsTuple((0, _List.map)(function (t_3) {
return readTypeNode(checker, t_3);
}, (0, _Seq.toList)(tp.elementTypes)), new _syntax.FsTupleKind(1)));
case 137:
return (0, _syntax.simpleType)("Symbol");
case 169:
return new _syntax.FsType(19);
case 158:
return (0, _syntax.simpleType)("bool");
case 163:
const tl = t;
return new _syntax.FsType(21, readTypeLiteral(checker, tl));
case 167:
const itp = t;
return new _syntax.FsType(12, new _syntax.FsTuple((0, _List.map)(function (t_4) {
return readTypeNode(checker, t_4);
}, (0, _Seq.toList)(itp.types)), new _syntax.FsTupleKind(0)));
case 171:
const ia = t;
checker = checker;
t = ia.objectType;
continue readTypeNode;
case 162:
return (0, _syntax.simpleType)("obj");
case 173:
const lt = t;
const readLiteralKind = function (kind, text) {
if (kind === 9) {
return new _syntax.FsType(17, (0, _naming.removeQuotes)(text));
} else {
return (0, _syntax.simpleType)("obj");
}
};
const matchValue_1 = lt.literal;
if ((0, _Util.hasInterface)(matchValue_1, "TypeScript.Ts.LiteralExpression")) {
return readLiteralKind(matchValue_1.kind, matchValue_1.getText());
} else if ((0, _Util.hasInterface)(matchValue_1, "TypeScript.Ts.PrefixUnaryExpression")) {
return readLiteralKind(matchValue_1.kind, matchValue_1.getText());
} else {
return readLiteralKind(matchValue_1.kind, matchValue_1.getText());
}
case 201:
const eta = t;
const tp_1 = checker.getTypeFromTypeNode(eta);
return new _syntax.FsType(7, new _syntax.FsMapped(readExpressionText(eta.expression), getFullTypeName(checker, tp_1)));
case 168:
const pt = t;
checker = checker;
t = pt.type;
continue readTypeNode;
case 172:
return new _syntax.FsType(12, new _syntax.FsTuple((0, _List.ofArray)([(0, _syntax.simpleType)("obj")]), new _syntax.FsTupleKind(2)));
case 130:
return new _syntax.FsType(5);
case 139:
return (0, _syntax.simpleType)("obj");
case 95:
return new _syntax.FsType(5);
case 134:
return (0, _syntax.simpleType)("obj");
case 170:
(0, _String.toConsole)((0, _String.printf)("unsupported TypeNode TypeOperator: %A"))(t);
return new _syntax.FsType(5);
default:
(0, _String.toConsole)((0, _String.printf)("unsupported TypeNode kind: %A"))(t.kind);
return new _syntax.FsType(5);
}
}
}
function readParameterDeclaration(checker, pd) {
const stringLiteral = (0, _Seq.tryPick)(function (ch) {
return (0, _Seq.tryFind)(function (gch) {
return gch.kind === 9;
}, (0, _Seq.toList)(ch.getChildren()));
}, (0, _Seq.toList)(pd.getChildren()));
let tp;
if (stringLiteral == null) {
const matchValue = pd.type;
if (matchValue == null) {
tp = (0, _syntax.simpleType)("obj");
} else {
tp = readTypeNode(checker, (0, _Option.getValue)(matchValue));
}
} else {
tp = new _syntax.FsType(17, (0, _naming.removeQuotes)((0, _Option.getValue)(stringLiteral).getText()));
}
const name = getBindingName(pd.name);
return new _syntax.FsParam((0, _Option.defaultArg)(function (list) {
return (0, _Seq.tryFind)(_syntax.FsCommentModule.isParam.bind(_syntax.FsCommentModule), list);
}(readCommentTags(pd)), null, function (comment) {
return comment.tag === 1 ? new _syntax.FsComment(1, new _syntax.FsParamComment(name, comment.data.Description)) : comment;
}), name, (0, _CurriedLambda2.default)(() => pd.questionToken != null)(), (0, _CurriedLambda2.default)(() => pd.dotDotDotToken != null)(), tp);
}
function readMethodSignature(checker, ms) {
var matchValue;
return new _syntax.FsFunction(readCommentsForSignatureDeclaration(checker, ms), new _syntax.FsFunctionKind(0), hasModifier(115, ms.modifiers), getPropertyName(ms.name), readTypeParameters(checker, ms.typeParameters), (0, _List.map)(function (pd) {
return readParameterDeclaration(checker, pd);
}, (0, _Seq.toList)(ms.parameters)), (matchValue = ms.type, matchValue == null ? (0, _syntax.simpleType)("unit") : readTypeNode(checker, (0, _Option.getValue)(matchValue))));
}
function readMethodDeclaration(checker, md) {
var matchValue;
return new _syntax.FsFunction(readCommentsForSignatureDeclaration(checker, md), new _syntax.FsFunctionKind(0), hasModifier(115, md.modifiers), getPropertyName(md.name), readTypeParameters(checker, md.typeParameters), (0, _List.map)(function (pd) {
return readParameterDeclaration(checker, pd);
}, (0, _Seq.toList)(md.parameters)), (matchValue = md.type, matchValue == null ? (0, _syntax.simpleType)("unit") : readTypeNode(checker, (0, _Option.getValue)(matchValue))));
}
function isReadOnly(modifiers) {
return hasModifier(131, modifiers);
}
function readPropertySignature(checker, ps) {
var matchValue;
return new _syntax.FsProperty(readPropertyNameComments(checker, ps.name), new _syntax.FsPropertyKind(0), null, getPropertyName(ps.name), (0, _CurriedLambda2.default)(() => ps.questionToken != null)(), (matchValue = ps.type, matchValue != null ? readTypeNode(checker, (0, _Option.getValue)(matchValue)) : new _syntax.FsType(6)), isReadOnly(ps.modifiers));
}
function readPropertyNameComments(checker, pn) {
if ((0, _Util.hasInterface)(pn, "TypeScript.Ts.StringLiteral")) {
return readCommentsAtLocation(checker, pn);
} else if ((0, _Util.hasInterface)(pn, "TypeScript.Ts.NumericLiteral")) {
return readCommentsAtLocation(checker, pn);
} else if ((0, _Util.hasInterface)(pn, "TypeScript.Ts.ComputedPropertyName")) {
return readCommentsAtLocation(checker, pn);
} else {
return readCommentsAtLocation(checker, pn);
}
}
function readPropertyDeclaration(checker, pd) {
var matchValue;
return new _syntax.FsProperty(readPropertyNameComments(checker, pd.name), new _syntax.FsPropertyKind(0), null, getPropertyName(pd.name), (0, _CurriedLambda2.default)(() => pd.questionToken != null)(), (matchValue = pd.type, matchValue != null ? readTypeNode(checker, (0, _Option.getValue)(matchValue)) : new _syntax.FsType(6)), isReadOnly(pd.modifiers));
}
function readFunctionDeclaration(checker, fd) {
var matchValue;
return new _syntax.FsFunction(readCommentsForSignatureDeclaration(checker, fd), new _syntax.FsFunctionKind(0), hasModifier(115, fd.modifiers), (0, _Option.defaultArg)(fd.name, null, function (id) {
return id.getText();
}), readTypeParameters(checker, fd.typeParameters), (0, _List.map)(function (pd) {
return readParameterDeclaration(checker, pd);
}, (0, _Seq.toList)(fd.parameters)), (matchValue = fd.type, matchValue == null ? (0, _syntax.simpleType)("unit") : readTypeNode(checker, (0, _Option.getValue)(matchValue))));
}
function readIndexSignature(checker, ps) {
var matchValue;
const pm = readParameterDeclaration(checker, ps.parameters[0]);
return new _syntax.FsProperty(readCommentsForSignatureDeclaration(checker, ps), new _syntax.FsPropertyKind(1), pm, "Item", (0, _CurriedLambda2.default)(() => ps.questionToken != null)(), (matchValue = ps.type, matchValue != null ? readTypeNode(checker, (0, _Option.getValue)(matchValue)) : new _syntax.FsType(6)), isReadOnly(ps.modifiers));
}
function readCallSignature(checker, cs) {
var matchValue;
return new _syntax.FsFunction(readCommentsForSignatureDeclaration(checker, cs), new _syntax.FsFunctionKind(2), false, "Invoke", new _List2.default(), (0, _List.map)(function (pd) {
return readParameterDeclaration(checker, pd);
}, (0, _Seq.toList)(cs.parameters)), (matchValue = cs.type, matchValue == null ? (0, _syntax.simpleType)("unit") : readTypeNode(checker, (0, _Option.getValue)(matchValue))));
}
function readConstructSignatureDeclaration(checker, cs) {
return new _syntax.FsFunction(readCommentsForSignatureDeclaration(checker, cs), new _syntax.FsFunctionKind(1), true, "Create", function (tps) {
return readTypeParameters(checker, tps);
}(cs.typeParameters), (0, _List.map)(function (pd) {
return readParameterDeclaration(checker, pd);
}, (0, _Seq.toList)(cs.parameters)), new _syntax.FsType(19));
}
function readConstructorDeclaration(checker, cs) {
return new _syntax.FsFunction(readCommentsForSignatureDeclaration(checker, cs), new _syntax.FsFunctionKind(1), true, "Create", function (tps) {
return readTypeParameters(checker, tps);
}(cs.typeParameters), (0, _List.map)(function (pd) {
return readParameterDeclaration(checker, pd);
}, (0, _Seq.toList)(cs.parameters)), new _syntax.FsType(19));
}
function readNamedDeclaration(checker, te) {
const matchValue = te.kind | 0;
switch (matchValue) {
case 157:
return new _syntax.FsType(2, readIndexSignature(checker, te));
case 150:
return new _syntax.FsType(8, readMethodSignature(checker, te));
case 148:
return new _syntax.FsType(2, readPropertySignature(checker, te));
case 155:
return new _syntax.FsType(8, readCallSignature(checker, te));
case 156:
return new _syntax.FsType(8, readConstructSignatureDeclaration(checker, te));
case 152:
return new _syntax.FsType(8, readConstructorDeclaration(checker, te));
case 149:
return new _syntax.FsType(2, readPropertyDeclaration(checker, te));
case 151:
return new _syntax.FsType(8, readMethodDeclaration(checker, te));
default:
(0, _String.toConsole)((0, _String.printf)("unsupported NamedDeclaration kind: %A"))(te.kind);
return new _syntax.FsType(5);
}
}
function readAliasDeclaration(checker, d) {
const tp = function (t) {
return readTypeNode(checker, t);
}(d.type);
const name = d.name.getText();
const asAlias = function () {
return new _syntax.FsType(10, new _syntax.FsAlias(name, tp, readTypeParameters(checker, d.typeParameters)));
};
if (tp.tag === 9) {
const sls = function (list) {
return (0, _List.choose)(_syntax.FsTypeModule.asStringLiteral.bind(_syntax.FsTypeModule), list);
}(tp.data.Types);
if (tp.data.Types.length === sls.length) {
return new _syntax.FsType(1, new _syntax.FsEnum(name, (0, _List.map)(function (sl) {
return new _syntax.FsEnumCase(sl, new _syntax.FsEnumCaseType(1), null);
}, sls)));
} else {
return asAlias();
}
} else {
return asAlias();
}
}
function readExpressionText(ep) {
const matchValue = ep.kind | 0;
if (matchValue === 71) {
const id = ep;
return id.getText();
} else if (matchValue === 179) {
const pa = ep;
return pa.getText();
} else {
(0, _String.toConsole)((0, _String.printf)("readExpressionText kind not yet supported: %A"))(ep.kind);
return ep.getText();
}
}
function readExportAssignment(ea) {
const matchValue = ea.expression.kind | 0;
if (matchValue === 71) {
const path = readExpressionText(ea.expression);
return new _syntax.FsType(18, path);
} else {
return new _syntax.FsType(6);
}
}
function readImportDeclaration(im) {
const moduleSpecifier = (0, _naming.removeQuotes)(im.moduleSpecifier.getText());
const matchValue = im.importClause;
if (matchValue != null) {
const matchValue_1 = (0, _Option.getValue)(matchValue).namedBindings;
if (matchValue_1 != null) {
if ((0, _Util.hasInterface)((0, _Option.getValue)(matchValue_1), "TypeScript.Ts.NamedImports")) {
return new _List2.default();
} else if ((0, _Option.getValue)(matchValue_1).name == null === false) {
return (0, _List.ofArray)([new _syntax.FsType(20, new _syntax.FsImport(1, new _syntax.ModuleImport((0, _Option.getValue)(matchValue_1).name.getText(), moduleSpecifier, null)))]);
} else {
return (0, _List.collect)(function (ch) {
const matchValue_2 = ch.kind | 0;
if (matchValue_2 === 286) {
const sl = ch;
return (0, _List.choose)(function (slch) {
const matchValue_3 = slch.kind | 0;
if (matchValue_3 === 242) {
const imp = slch;
return new _syntax.FsType(20, new _syntax.FsImport(0, new _syntax.TypeImport(imp.getText(), moduleSpecifier, null)));
} else {
return null;
}
}, (0, _Seq.toList)(sl.getChildren()));
} else {
return new _List2.default();
}
}, (0, _Seq.toList)((0, _Option.getValue)(matchValue_1).getChildren()));
}
} else {
return new _List2.default();
}
} else {
return new _List2.default();
}
}
function readStatement(checker, sd) {
const matchValue = sd.kind | 0;
switch (matchValue) {
case 230:
return (0, _List.ofArray)([new _syntax.FsType(0, readInterface(checker, sd))]);
case 232:
return (0, _List.ofArray)([new _syntax.FsType(1, readEnum(sd))]);
case 231:
return (0, _List.ofArray)([readAliasDeclaration(checker, sd)]);
case 229:
return (0, _List.ofArray)([new _syntax.FsType(0, readClass(checker, sd))]);
case 208:
return readVariable(checker, sd);
case 228:
return (0, _List.ofArray)([new _syntax.FsType(8, readFunctionDeclaration(checker, sd))]);
case 233:
return (0, _List.ofArray)([new _syntax.FsType(13, readModuleDeclaration(checker, sd))]);
case 243:
return (0, _List.ofArray)([readExportAssignment(sd)]);
case 238:
return readImportDeclaration(sd);
case 236:
return new _List2.default();
case 244:
return new _List2.default();
case 237:
const ime = sd;
return new _List2.default();
default:
(0, _String.toConsole)((0, _String.printf)("unsupported Statement kind: %A"))(sd.kind);
return new _List2.default();
}
}
function readModuleName(mn) {
if ((0, _Util.hasInterface)(mn, "TypeScript.Ts.StringLiteral")) {
return mn.getText();
} else {
return (0, _String.replace)(mn.getText(), "\"", "");
}
}
function readModuleDeclaration(checker, md) {
const types = [];
Node_ForEachChild.bind(md)(function (nd) {
const matchValue = nd.kind | 0;
switch (matchValue) {
case 234:
const mb = nd;
(0, _Seq.iterate)(types.push.bind(types), (0, _List.collect)(function (sd) {
return readStatement(checker, sd);
}, (0, _Seq.toList)(mb.statements)));
break;
case 124:
break;
case 71:
break;
case 233:
types.push.bind(types)(new _syntax.FsType(13, readModuleDeclaration(checker, nd)));
break;
case 9:
break;
case 84:
break;
default:
(0, _String.toConsole)((0, _String.printf)("unknown kind in ModuleDeclaration: %A"))(nd.kind);
}
});
return new _syntax.FsModule(hasModifier(124, md.modifiers), isNamespace(md), readModuleName(md.name), (0, _Seq.toList)(types), new _List2.default(), new _List2.default());
}
function readSourceFile(checker, sf, file) {
const modules = [];
const gbl = new _syntax.FsModule(false, false, "", (0, _List.collect)(function (sd) {
return readStatement(checker, sd);
}, (0, _Seq.toList)(sf.statements)), new _List2.default(), new _List2.default());
modules.push(gbl);
const Modules = (0, _Seq.toList)(modules);
return new _syntax.FsFile(file.FileName, file.ModuleName, Modules);
}
+1321
View File
File diff suppressed because it is too large. Load diff
+1122
View File
File diff suppressed because it is too large. Load diff
Generated Vendored Executable
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.exports = exports.fsfile = exports.tsfiles = exports.files = exports.argv = undefined;
var _yargs = require("yargs");
var yargs = _interopRequireWildcard(_yargs);
var _List = require("./fable-core/List");
var _List2 = _interopRequireDefault(_List);
var _Option = require("./fable-core/Option");
var _String = require("./fable-core/String");
var _Seq = require("./fable-core/Seq");
var _version = require("./version");
var _fs = require("fs");
var fs = _interopRequireWildcard(_fs);
var _write = require("./write");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
const argv = exports.argv = yargs.usage("Usage: ts2fable some.d.ts src/Some.fs").command("$0 [files..]", "").option("files", {
type: "array",
description: "input ts files and output fs file",
alias: "f"
}).option("exports", {
type: "array",
description: "export types from files that contain the string",
alias: "e"
}).help().argv;
const files = exports.files = (0, _List.ofArray)((0, _Option.getValue)(argv["files"]));
const tsfiles = exports.tsfiles = (0, _List.filter)(function (s) {
return (0, _String.endsWith)(s, ".ts");
}, files);
const fsfile = exports.fsfile = (0, _Seq.tryFind)(function (s) {
return (0, _String.endsWith)(s, ".fs");
}, files);
const _exports = (() => {
const matchValue = argv["exports"];
if (matchValue != null) {
return (0, _List.ofArray)((0, _Option.getValue)(matchValue));
} else {
return new _List2.default();
}
})();
exports.exports = _exports;
const matchValue = [tsfiles.length, fsfile];
if (matchValue[0] === 0) {
(0, _String.toFail)((0, _String.printf)("Please provide the path to a TypeScript file"));
} else if (matchValue[1] != null) {
const fsf = (0, _Option.getValue)(matchValue[1]);
(0, _String.toConsole)((0, _String.printf)("ts2fable %s"))(_version.version);
for (let ts of tsfiles) {
if (!fs.existsSync(ts)) {
(0, _String.toFail)((0, _String.printf)("TypeScript file not found: %s"))(ts);
}
}
(0, _write.writeFile)(tsfiles, fsf, _exports);
} else {
(0, _String.toFail)((0, _String.printf)("Please provide the path to the F# file to be written "));
}
+69
View File
@@ -0,0 +1,69 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.version = exports.PackageJson = undefined;
var _Symbol2 = require("./fable-core/Symbol");
var _Symbol3 = _interopRequireDefault(_Symbol2);
var _Util = require("./fable-core/Util");
var _path = require("path");
var path = _interopRequireWildcard(_path);
var _List = require("./fable-core/List");
var _fs = require("fs");
var fs = _interopRequireWildcard(_fs);
var _Serialize = require("./fable-core/Serialize");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class PackageJson {
constructor(version) {
this.version = version;
}
[_Symbol3.default.reflection]() {
return {
type: "ts2fable.Version.PackageJson",
interfaces: ["FSharpRecord", "System.IEquatable", "System.IComparable"],
properties: {
version: "string"
}
};
}
Equals(other) {
return (0, _Util.equalsRecords)(this, other);
}
CompareTo(other) {
return (0, _Util.compareRecords)(this, other) | 0;
}
}
exports.PackageJson = PackageJson;
(0, _Symbol2.setType)("ts2fable.Version.PackageJson", PackageJson);
const version = exports.version = (() => {
const packageJsonPath = path.join(...Array.from((0, _List.ofArray)([__dirname, "../package.json"])));
if (fs.existsSync(packageJsonPath)) {
const packageJson = (0, _Serialize.ofJson)(fs.readFileSync(packageJsonPath, "utf8"), {
T: PackageJson
});
return packageJson.version;
} else {
return "0.0.0";
}
})();
+108
View File
@@ -0,0 +1,108 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transform = transform;
exports.stringContainsAny = stringContainsAny;
exports.getFsFileOut = getFsFileOut;
exports.emitFsFileOut = emitFsFileOut;
exports.emitFsFileOutAsLines = emitFsFileOutAsLines;
exports.writeFile = writeFile;
var _transform = require("./transform");
var _Seq = require("./fable-core/Seq");
var _typescript = require("typescript");
var typescript = _interopRequireWildcard(_typescript);
var _List = require("./fable-core/List");
var _List2 = _interopRequireDefault(_List);
var _String = require("./fable-core/String");
var _naming = require("./naming");
var _read = require("./read");
var _syntax = require("./syntax");
var _path = require("path");
var path = _interopRequireWildcard(_path);
var _fs = require("fs");
var fs = _interopRequireWildcard(_fs);
var _print = require("./print");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function transform(file) {
return (0, _transform.addAliasUnionHelpers)((0, _transform.extractTypeLiterals)((0, _transform.removeDuplicateOptions)((0, _transform.removeDuplicateFunctions)((0, _transform.removeTypeParamsFromStatic)((0, _transform.addTicForGenericTypes)((0, _transform.addTicForGenericFunctions)((0, _transform.fixNamespace)((0, _transform.fixEscapeWords)((0, _transform.fixDuplicatesInUnion)((0, _transform.fixEnumReferences)((0, _transform.fixOverloadingOnStringParameters)((0, _transform.createIExports)((0, _transform.fixStatic)((0, _transform.fixDateTime)((0, _transform.fixReadonlyArray)((0, _transform.fixNodeArray)((0, _transform.fixThis)((0, _transform.addConstructors)((0, _transform.extractTypesInGlobalModules)((0, _transform.fixTypesHasESKeywords)((0, _transform.extractGenericParameterDefaults)((0, _transform.aliasToInterfacePartly)((0, _transform.mergeModulesInFile)((0, _transform.removeInternalModules)(file)))))))))))))))))))))))));
}
function stringContainsAny(b, a) {
return (0, _Seq.exists)(function (arg00) {
return a.indexOf(arg00) >= 0;
}, b);
}
function getFsFileOut(fsPath, tsPaths, exports) {
const options = {
module: 1,
target: 2
};
const host = typescript.createCompilerHost(options, true);
const program = typescript.createProgram(Array.from(tsPaths), options, host);
const exportFiles = exports.length === 0 ? tsPaths : (0, _List.filter)(function (a) {
return stringContainsAny(exports, a);
}, (0, _List.map)(function (sf) {
return sf.fileName;
}, (0, _Seq.toList)(program.getSourceFiles())));
for (let _export of exportFiles) {
(0, _String.toConsole)((0, _String.printf)("export %s"))(_export);
}
const tsFiles = (0, _List.map)(program.getSourceFile.bind(program), exportFiles);
const checker = program.getTypeChecker();
const moduleNameMap = new Map((0, _Seq.map)(function (sf_1) {
return [sf_1.fileName, (0, _naming.getJsModuleName)(sf_1.fileName)];
}, program.getSourceFiles()));
const fsFiles = (0, _List.map)(function (tsFile) {
return transform(function (file) {
return (0, _read.readSourceFile)(checker, tsFile, file);
}(new _syntax.FsFile(tsFile.fileName, moduleNameMap.get(tsFile.fileName), new _List2.default())));
}, tsFiles);
return (0, _transform.fixFsFileOut)(new _syntax.FsFileOut(path.basename(fsPath, path.extname(fsPath)), (0, _List.ofArray)(["System", "Fable.Core", "Fable.Import.JS"]), fsFiles));
}
function emitFsFileOut(fsPath, fsFileOut) {
emitFsFileOutAsLines(fsPath, fsFileOut), void 0;
}
function emitFsFileOutAsLines(fsPath, fsFileOut) {
const file = fs.createWriteStream(fsPath);
const lines = Array.from(new _List2.default());
const inputSequence = (0, _print.printFsFile)(fsFileOut);
for (let line of inputSequence) {
lines.push(line);
file.write((0, _String.toText)((0, _String.printf)("%s%c"))(line, "\n")), void 0;
}
file.end();
return (0, _Seq.toList)(lines);
}
function writeFile(tsPaths, fsPath, exports) {
const fsFileOut = getFsFileOut(fsPath, tsPaths, exports);
emitFsFileOut(fsPath, fsFileOut);
}
+10
View File
@@ -0,0 +1,10 @@
'use strict';
module.exports = () => {
const pattern = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'
].join('|');
return new RegExp(pattern, 'g');
};
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+121
View File
@@ -0,0 +1,121 @@
{
"_args": [
[
"ansi-regex@^3.0.0",
"/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/strip-ansi"
]
],
"_from": "ansi-regex@>=3.0.0 <4.0.0",
"_id": "ansi-regex@3.0.0",
"_inCache": true,
"_installable": true,
"_location": "/ts2fable/ansi-regex",
"_nodeVersion": "4.8.3",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/ansi-regex-3.0.0.tgz_1497985412590_0.5700640194118023"
},
"_npmUser": {
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
},
"_npmVersion": "2.15.11",
"_phantomChildren": {},
"_requested": {
"name": "ansi-regex",
"raw": "ansi-regex@^3.0.0",
"rawSpec": "^3.0.0",
"scope": null,
"spec": ">=3.0.0 <4.0.0",
"type": "range"
},
"_requiredBy": [
"/ts2fable/strip-ansi"
],
"_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"_shasum": "ed0317c322064f79466c02966bddb605ab37d998",
"_shrinkwrap": null,
"_spec": "ansi-regex@^3.0.0",
"_where": "/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/strip-ansi",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/ansi-regex/issues"
},
"dependencies": {},
"description": "Regular expression for matching ANSI escape codes",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"directories": {},
"dist": {
"shasum": "ed0317c322064f79466c02966bddb605ab37d998",
"tarball": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"gitHead": "0a8cc19946c03c38520fe8c086b8adb66f9cce0b",
"homepage": "https://github.com/chalk/ansi-regex#readme",
"keywords": [
"256",
"ansi",
"cli",
"color",
"colors",
"colour",
"command-line",
"console",
"escape",
"find",
"formatting",
"match",
"pattern",
"re",
"regex",
"regexp",
"rgb",
"shell",
"string",
"styles",
"terminal",
"test",
"text",
"tty",
"xterm"
],
"license": "MIT",
"maintainers": [
{
"name": "dthree",
"email": "threedeecee@gmail.com"
},
{
"name": "qix",
"email": "i.am.qix@gmail.com"
},
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"name": "ansi-regex",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/ansi-regex.git"
},
"scripts": {
"test": "xo && ava",
"view-supported": "node fixtures/view-codes.js"
},
"version": "3.0.0"
}
+46
View File
@@ -0,0 +1,46 @@
# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex)
> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install ansi-regex
```
## Usage
```js
const ansiRegex = require('ansi-regex');
ansiRegex().test('\u001B[4mcake\u001B[0m');
//=> true
ansiRegex().test('cake');
//=> false
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
//=> ['\u001B[4m', '\u001B[0m']
```
## FAQ
### Why do you test for codes not in the ECMA 48 standard?
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT
+64
View File
@@ -0,0 +1,64 @@
'use strict';
function preserveCamelCase(str) {
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for (let i = 0; i < str.length; i++) {
const c = str[i];
if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) {
str = str.substr(0, i) + '-' + str.substr(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(c) && c.toLowerCase() === c) {
str = str.substr(0, i - 1) + '-' + str.substr(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = c.toLowerCase() === c;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = c.toUpperCase() === c;
}
}
return str;
}
module.exports = function (str) {
if (arguments.length > 1) {
str = Array.from(arguments)
.map(x => x.trim())
.filter(x => x.length)
.join('-');
} else {
str = str.trim();
}
if (str.length === 0) {
return '';
}
if (str.length === 1) {
return str.toLowerCase();
}
if (/^[a-z0-9]+$/.test(str)) {
return str;
}
const hasUpperCase = str !== str.toLowerCase();
if (hasUpperCase) {
str = preserveCamelCase(str);
}
return str
.replace(/^[_.\- ]+/, '')
.toLowerCase()
.replace(/[_.\- ]+(\w|$)/g, (m, p1) => p1.toUpperCase());
};
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+102
View File
@@ -0,0 +1,102 @@
{
"_args": [
[
"camelcase@^4.1.0",
"/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs-parser"
]
],
"_from": "camelcase@>=4.1.0 <5.0.0",
"_id": "camelcase@4.1.0",
"_inCache": true,
"_installable": true,
"_location": "/ts2fable/camelcase",
"_nodeVersion": "7.8.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/camelcase-4.1.0.tgz_1490865362489_0.433825216954574"
},
"_npmUser": {
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
},
"_npmVersion": "4.2.0",
"_phantomChildren": {},
"_requested": {
"name": "camelcase",
"raw": "camelcase@^4.1.0",
"rawSpec": "^4.1.0",
"scope": null,
"spec": ">=4.1.0 <5.0.0",
"type": "range"
},
"_requiredBy": [
"/ts2fable/yargs-parser"
],
"_resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz",
"_shasum": "d545635be1e33c542649c69173e5de6acfae34dd",
"_shrinkwrap": null,
"_spec": "camelcase@^4.1.0",
"_where": "/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs-parser",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/camelcase/issues"
},
"dependencies": {},
"description": "Convert a dash/dot/underscore/space separated string to camelCase: foo-bar → fooBar",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"directories": {},
"dist": {
"shasum": "d545635be1e33c542649c69173e5de6acfae34dd",
"tarball": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"gitHead": "0e6e4a2752aa013b8e9477145c7b8132c95a82ef",
"homepage": "https://github.com/sindresorhus/camelcase#readme",
"keywords": [
"camel",
"camel-case",
"camelcase",
"case",
"convert",
"dash",
"dot",
"hyphen",
"separator",
"string",
"text",
"underscore"
],
"license": "MIT",
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"name": "camelcase",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/camelcase.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "4.1.0",
"xo": {
"esnext": true
}
}
+57
View File
@@ -0,0 +1,57 @@
# camelcase [![Build Status](https://travis-ci.org/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase)
> Convert a dash/dot/underscore/space separated string to camelCase: `foo-bar` → `fooBar`
## Install
```
$ npm install --save camelcase
```
## Usage
```js
const camelCase = require('camelcase');
camelCase('foo-bar');
//=> 'fooBar'
camelCase('foo_bar');
//=> 'fooBar'
camelCase('Foo-Bar');
//=> 'fooBar'
camelCase('--foo.bar');
//=> 'fooBar'
camelCase('__foo__bar__');
//=> 'fooBar'
camelCase('foo bar');
//=> 'fooBar'
console.log(process.argv[3]);
//=> '--foo-bar'
camelCase(process.argv[3]);
//=> 'fooBar'
camelCase('foo', 'bar');
//=> 'fooBar'
camelCase('__foo__', '--bar');
//=> 'fooBar'
```
## Related
- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module
- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+51
View File
@@ -0,0 +1,51 @@
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="4.1.0"></a>
# [4.1.0](https://github.com/yargs/cliui/compare/v4.0.0...v4.1.0) (2018-04-23)
### Features
* add resetOutput method ([#57](https://github.com/yargs/cliui/issues/57)) ([7246902](https://github.com/yargs/cliui/commit/7246902))
<a name="4.0.0"></a>
# [4.0.0](https://github.com/yargs/cliui/compare/v3.2.0...v4.0.0) (2017-12-18)
### Bug Fixes
* downgrades strip-ansi to version 3.0.1 ([#54](https://github.com/yargs/cliui/issues/54)) ([5764c46](https://github.com/yargs/cliui/commit/5764c46))
* set env variable FORCE_COLOR. ([#56](https://github.com/yargs/cliui/issues/56)) ([7350e36](https://github.com/yargs/cliui/commit/7350e36))
### Chores
* drop support for node < 4 ([#53](https://github.com/yargs/cliui/issues/53)) ([b105376](https://github.com/yargs/cliui/commit/b105376))
### Features
* add fallback for window width ([#45](https://github.com/yargs/cliui/issues/45)) ([d064922](https://github.com/yargs/cliui/commit/d064922))
### BREAKING CHANGES
* officially drop support for Node < 4
<a name="3.2.0"></a>
# [3.2.0](https://github.com/yargs/cliui/compare/v3.1.2...v3.2.0) (2016-04-11)
### Bug Fixes
* reduces tarball size ([acc6c33](https://github.com/yargs/cliui/commit/acc6c33))
### Features
* adds standard-version for release management ([ff84e32](https://github.com/yargs/cliui/commit/ff84e32))
+14
View File
@@ -0,0 +1,14 @@
Copyright (c) 2015, Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice
appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+115
View File
@@ -0,0 +1,115 @@
# cliui
[![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui)
[![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=)
[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui)
[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version)
easily create complex multi-column command-line-interfaces.
## Example
```js
var ui = require('cliui')()
ui.div('Usage: $0 [command] [options]')
ui.div({
text: 'Options:',
padding: [2, 0, 2, 0]
})
ui.div(
{
text: "-f, --file",
width: 20,
padding: [0, 4, 0, 4]
},
{
text: "the file to load." +
chalk.green("(if this description is long it wraps).")
,
width: 20
},
{
text: chalk.red("[required]"),
align: 'right'
}
)
console.log(ui.toString())
```
<img width="500" src="screenshot.png">
## Layout DSL
cliui exposes a simple layout DSL:
If you create a single `ui.row`, passing a string rather than an
object:
* `\n`: characters will be interpreted as new rows.
* `\t`: characters will be interpreted as new columns.
* `\s`: characters will be interpreted as padding.
**as an example...**
```js
var ui = require('./')({
width: 60
})
ui.div(
'Usage: node ./bin/foo.js\n' +
' <regex>\t provide a regex\n' +
' <glob>\t provide a glob\t [required]'
)
console.log(ui.toString())
```
**will output:**
```shell
Usage: node ./bin/foo.js
<regex> provide a regex
<glob> provide a glob [required]
```
## Methods
```js
cliui = require('cliui')
```
### cliui({width: integer})
Specify the maximum width of the UI being generated.
If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`.
### cliui({wrap: boolean})
Enable or disable the wrapping of text in a column.
### cliui.div(column, column, column)
Create a row with any number of columns, a column
can either be a string, or an object with the following
options:
* **text:** some text to place in the column.
* **width:** the width of a column.
* **align:** alignment, `right` or `center`.
* **padding:** `[top, right, bottom, left]`.
* **border:** should a border be placed around the div?
### cliui.span(column, column, column)
Similar to `div`, except the next row will be appended without
a new line being created.
### cliui.resetOutput()
Resets the UI elements of the current cliui instance, maintaining the values
set for `width` and `wrap`.
+324
View File
@@ -0,0 +1,324 @@
var stringWidth = require('string-width')
var stripAnsi = require('strip-ansi')
var wrap = require('wrap-ansi')
var align = {
right: alignRight,
center: alignCenter
}
var top = 0
var right = 1
var bottom = 2
var left = 3
function UI (opts) {
this.width = opts.width
this.wrap = opts.wrap
this.rows = []
}
UI.prototype.span = function () {
var cols = this.div.apply(this, arguments)
cols.span = true
}
UI.prototype.resetOutput = function () {
this.rows = []
}
UI.prototype.div = function () {
if (arguments.length === 0) this.div('')
if (this.wrap && this._shouldApplyLayoutDSL.apply(this, arguments)) {
return this._applyLayoutDSL(arguments[0])
}
var cols = []
for (var i = 0, arg; (arg = arguments[i]) !== undefined; i++) {
if (typeof arg === 'string') cols.push(this._colFromString(arg))
else cols.push(arg)
}
this.rows.push(cols)
return cols
}
UI.prototype._shouldApplyLayoutDSL = function () {
return arguments.length === 1 && typeof arguments[0] === 'string' &&
/[\t\n]/.test(arguments[0])
}
UI.prototype._applyLayoutDSL = function (str) {
var _this = this
var rows = str.split('\n')
var leftColumnWidth = 0
// simple heuristic for layout, make sure the
// second column lines up along the left-hand.
// don't allow the first column to take up more
// than 50% of the screen.
rows.forEach(function (row) {
var columns = row.split('\t')
if (columns.length > 1 && stringWidth(columns[0]) > leftColumnWidth) {
leftColumnWidth = Math.min(
Math.floor(_this.width * 0.5),
stringWidth(columns[0])
)
}
})
// generate a table:
// replacing ' ' with padding calculations.
// using the algorithmically generated width.
rows.forEach(function (row) {
var columns = row.split('\t')
_this.div.apply(_this, columns.map(function (r, i) {
return {
text: r.trim(),
padding: _this._measurePadding(r),
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
}
}))
})
return this.rows[this.rows.length - 1]
}
UI.prototype._colFromString = function (str) {
return {
text: str,
padding: this._measurePadding(str)
}
}
UI.prototype._measurePadding = function (str) {
// measure padding without ansi escape codes
var noAnsi = stripAnsi(str)
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]
}
UI.prototype.toString = function () {
var _this = this
var lines = []
_this.rows.forEach(function (row, i) {
_this.rowToString(row, lines)
})
// don't display any lines with the
// hidden flag set.
lines = lines.filter(function (line) {
return !line.hidden
})
return lines.map(function (line) {
return line.text
}).join('\n')
}
UI.prototype.rowToString = function (row, lines) {
var _this = this
var padding
var rrows = this._rasterize(row)
var str = ''
var ts
var width
var wrapWidth
rrows.forEach(function (rrow, r) {
str = ''
rrow.forEach(function (col, c) {
ts = '' // temporary string used during alignment/padding.
width = row[c].width // the width with padding.
wrapWidth = _this._negatePadding(row[c]) // the width without padding.
ts += col
for (var i = 0; i < wrapWidth - stringWidth(col); i++) {
ts += ' '
}
// align the string within its column.
if (row[c].align && row[c].align !== 'left' && _this.wrap) {
ts = align[row[c].align](ts, wrapWidth)
if (stringWidth(ts) < wrapWidth) ts += new Array(width - stringWidth(ts)).join(' ')
}
// apply border and padding to string.
padding = row[c].padding || [0, 0, 0, 0]
if (padding[left]) str += new Array(padding[left] + 1).join(' ')
str += addBorder(row[c], ts, '| ')
str += ts
str += addBorder(row[c], ts, ' |')
if (padding[right]) str += new Array(padding[right] + 1).join(' ')
// if prior row is span, try to render the
// current row on the prior line.
if (r === 0 && lines.length > 0) {
str = _this._renderInline(str, lines[lines.length - 1])
}
})
// remove trailing whitespace.
lines.push({
text: str.replace(/ +$/, ''),
span: row.span
})
})
return lines
}
function addBorder (col, ts, style) {
if (col.border) {
if (/[.']-+[.']/.test(ts)) return ''
else if (ts.trim().length) return style
else return ' '
}
return ''
}
// if the full 'source' can render in
// the target line, do so.
UI.prototype._renderInline = function (source, previousLine) {
var leadingWhitespace = source.match(/^ */)[0].length
var target = previousLine.text
var targetTextWidth = stringWidth(target.trimRight())
if (!previousLine.span) return source
// if we're not applying wrapping logic,
// just always append to the span.
if (!this.wrap) {
previousLine.hidden = true
return target + source
}
if (leadingWhitespace < targetTextWidth) return source
previousLine.hidden = true
return target.trimRight() + new Array(leadingWhitespace - targetTextWidth + 1).join(' ') + source.trimLeft()
}
UI.prototype._rasterize = function (row) {
var _this = this
var i
var rrow
var rrows = []
var widths = this._columnWidths(row)
var wrapped
// word wrap all columns, and create
// a data-structure that is easy to rasterize.
row.forEach(function (col, c) {
// leave room for left and right padding.
col.width = widths[c]
if (_this.wrap) wrapped = wrap(col.text, _this._negatePadding(col), { hard: true }).split('\n')
else wrapped = col.text.split('\n')
if (col.border) {
wrapped.unshift('.' + new Array(_this._negatePadding(col) + 3).join('-') + '.')
wrapped.push("'" + new Array(_this._negatePadding(col) + 3).join('-') + "'")
}
// add top and bottom padding.
if (col.padding) {
for (i = 0; i < (col.padding[top] || 0); i++) wrapped.unshift('')
for (i = 0; i < (col.padding[bottom] || 0); i++) wrapped.push('')
}
wrapped.forEach(function (str, r) {
if (!rrows[r]) rrows.push([])
rrow = rrows[r]
for (var i = 0; i < c; i++) {
if (rrow[i] === undefined) rrow.push('')
}
rrow.push(str)
})
})
return rrows
}
UI.prototype._negatePadding = function (col) {
var wrapWidth = col.width
if (col.padding) wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0)
if (col.border) wrapWidth -= 4
return wrapWidth
}
UI.prototype._columnWidths = function (row) {
var _this = this
var widths = []
var unset = row.length
var unsetWidth
var remainingWidth = this.width
// column widths can be set in config.
row.forEach(function (col, i) {
if (col.width) {
unset--
widths[i] = col.width
remainingWidth -= col.width
} else {
widths[i] = undefined
}
})
// any unset widths should be calculated.
if (unset) unsetWidth = Math.floor(remainingWidth / unset)
widths.forEach(function (w, i) {
if (!_this.wrap) widths[i] = row[i].width || stringWidth(row[i].text)
else if (w === undefined) widths[i] = Math.max(unsetWidth, _minWidth(row[i]))
})
return widths
}
// calculates the minimum width of
// a column, based on padding preferences.
function _minWidth (col) {
var padding = col.padding || []
var minWidth = 1 + (padding[left] || 0) + (padding[right] || 0)
if (col.border) minWidth += 4
return minWidth
}
function getWindowWidth () {
if (typeof process === 'object' && process.stdout && process.stdout.columns) return process.stdout.columns
}
function alignRight (str, width) {
str = str.trim()
var padding = ''
var strWidth = stringWidth(str)
if (strWidth < width) {
padding = new Array(width - strWidth + 1).join(' ')
}
return padding + str
}
function alignCenter (str, width) {
str = str.trim()
var padding = ''
var strWidth = stringWidth(str.trim())
if (strWidth < width) {
padding = new Array(parseInt((width - strWidth) / 2, 10) + 1).join(' ')
}
return padding + str
}
module.exports = function (opts) {
opts = opts || {}
return new UI({
width: (opts || {}).width || getWindowWidth() || 80,
wrap: typeof opts.wrap === 'boolean' ? opts.wrap : true
})
}
+131
View File
@@ -0,0 +1,131 @@
{
"_args": [
[
"cliui@^4.0.0",
"/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs"
]
],
"_from": "cliui@>=4.0.0 <5.0.0",
"_hasShrinkwrap": false,
"_id": "cliui@4.1.0",
"_inCache": true,
"_installable": true,
"_location": "/ts2fable/cliui",
"_nodeVersion": "8.8.1",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/cliui_4.1.0_1524450515410_0.021997836619508382"
},
"_npmUser": {
"email": "ben@npmjs.com",
"name": "bcoe"
},
"_npmVersion": "5.8.0",
"_phantomChildren": {},
"_requested": {
"name": "cliui",
"raw": "cliui@^4.0.0",
"rawSpec": "^4.0.0",
"scope": null,
"spec": ">=4.0.0 <5.0.0",
"type": "range"
},
"_requiredBy": [
"/ts2fable/yargs"
],
"_resolved": "https://registry.npmjs.org/cliui/-/cliui-4.1.0.tgz",
"_shasum": "348422dbe82d800b3022eef4f6ac10bf2e4d1b49",
"_shrinkwrap": null,
"_spec": "cliui@^4.0.0",
"_where": "/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs",
"author": {
"email": "ben@npmjs.com",
"name": "Ben Coe"
},
"bugs": {
"url": "https://github.com/yargs/cliui/issues"
},
"config": {
"blanket": {
"data-cover-never": [
"node_modules",
"test"
],
"output-reporter": "spec",
"pattern": [
"index.js"
]
}
},
"dependencies": {
"string-width": "^2.1.1",
"strip-ansi": "^4.0.0",
"wrap-ansi": "^2.0.0"
},
"description": "easily create complex multi-column command-line-interfaces",
"devDependencies": {
"chai": "^3.5.0",
"chalk": "^1.1.2",
"coveralls": "^2.11.8",
"mocha": "^3.0.0",
"nyc": "^10.0.0",
"standard": "^8.0.0",
"standard-version": "^3.0.0"
},
"directories": {},
"dist": {
"fileCount": 5,
"integrity": "sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ==",
"npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJa3UTUCRA9TVsSAnZWagAAQBYP/21PAh+wIPQktq2XDuQ+\ntMjuDek2ebHLK5M4RyNM6TAJioGf5uHwUmqV7rHAhm9gRJn+dIIqkIukvLZy\ntln2x5GkDmYIxOC2wsj8Lbyc0k1cxoynJt8v8F/oE6EEaa6mRHuk3SJQU5Yy\nim1ofDj95s/mWcHeyrjdcfyvKJ4e6GZwylinGspAk1hR6UO33RoiWL4c2YIY\n7jYvi4HNVwv52cqGyoI78QZ8Js90rOCyZQz8QP6tZ1NMo1SwUC3jPauspGsn\npMgHslY1s0fZWp70Ac/MziJdx2XTFzYJZKkiuyJCxsyBuX7f1kUTD/Za235A\nDlpUmgj5a9UKpVtptlJ3nMRmgqXBClnIjvmm9NG2nJ8Egt3QxFdBZaxgJNbM\nMFss+LSZNnxBvmgnAC37sMvie06xwV2UOB/+eiK1EWBdVILV7END0hyRSyuM\naFsVZpqDAaXSVS4hwUFQvPA4biDGncxwDmktuOuJHSGVbIqRJJ7EEfVVBbFl\nH2KZQ8gxFT93Gg6x3tFuXlXQdPaHKvtZTkKJCLtigINk1Rr9PlUzstLRayay\nG55YvsSlDm1P2FMYosbMUrNHe0f8SVgyLsZk/tQ40htjK7zMthyAamxq+JpT\nl63y6KDYrtAwAE41206ry1QyNvlCyp+ZHv5KSZdxcUW25ZK5kwJDCMs1Sbkw\nn7bO\r\n=CsbE\r\n-----END PGP SIGNATURE-----\r\n",
"shasum": "348422dbe82d800b3022eef4f6ac10bf2e4d1b49",
"tarball": "https://registry.npmjs.org/cliui/-/cliui-4.1.0.tgz",
"unpackedSize": 14471
},
"engine": {
"node": ">=4"
},
"files": [
"index.js"
],
"gitHead": "83ada4a595ad60fff4fb962a3288eccbe163bccf",
"homepage": "https://github.com/yargs/cliui#readme",
"keywords": [
"cli",
"command-line",
"console",
"design",
"layout",
"table",
"wrap"
],
"license": "ISC",
"main": "index.js",
"maintainers": [
{
"name": "bcoe",
"email": "ben@npmjs.com"
}
],
"name": "cliui",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/yargs/cliui.git"
},
"scripts": {
"coverage": "nyc --reporter=text-lcov mocha | coveralls",
"pretest": "standard",
"release": "standard-version",
"test": "nyc mocha"
},
"standard": {
"globals": [
"it"
],
"ignore": [
"**/example/**"
]
},
"version": "4.1.0"
}
@@ -0,0 +1,46 @@
'use strict';
/* eslint-disable yoda */
module.exports = x => {
if (Number.isNaN(x)) {
return false;
}
// code points are derived from:
// http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
if (
x >= 0x1100 && (
x <= 0x115f || // Hangul Jamo
x === 0x2329 || // LEFT-POINTING ANGLE BRACKET
x === 0x232a || // RIGHT-POINTING ANGLE BRACKET
// CJK Radicals Supplement .. Enclosed CJK Letters and Months
(0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||
// Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
(0x3250 <= x && x <= 0x4dbf) ||
// CJK Unified Ideographs .. Yi Radicals
(0x4e00 <= x && x <= 0xa4c6) ||
// Hangul Jamo Extended-A
(0xa960 <= x && x <= 0xa97c) ||
// Hangul Syllables
(0xac00 <= x && x <= 0xd7a3) ||
// CJK Compatibility Ideographs
(0xf900 <= x && x <= 0xfaff) ||
// Vertical Forms
(0xfe10 <= x && x <= 0xfe19) ||
// CJK Compatibility Forms .. Small Form Variants
(0xfe30 <= x && x <= 0xfe6b) ||
// Halfwidth and Fullwidth Forms
(0xff01 <= x && x <= 0xff60) ||
(0xffe0 <= x && x <= 0xffe6) ||
// Kana Supplement
(0x1b000 <= x && x <= 0x1b001) ||
// Enclosed Ideographic Supplement
(0x1f200 <= x && x <= 0x1f251) ||
// CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
(0x20000 <= x && x <= 0x3fffd)
)
) {
return true;
}
return false;
};
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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,105 @@
{
"_args": [
[
"is-fullwidth-code-point@^2.0.0",
"/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/string-width"
]
],
"_from": "is-fullwidth-code-point@>=2.0.0 <3.0.0",
"_id": "is-fullwidth-code-point@2.0.0",
"_inCache": true,
"_installable": true,
"_location": "/ts2fable/is-fullwidth-code-point",
"_nodeVersion": "4.5.0",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/is-fullwidth-code-point-2.0.0.tgz_1474526567505_0.299921662081033"
},
"_npmUser": {
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
},
"_npmVersion": "3.10.7",
"_phantomChildren": {},
"_requested": {
"name": "is-fullwidth-code-point",
"raw": "is-fullwidth-code-point@^2.0.0",
"rawSpec": "^2.0.0",
"scope": null,
"spec": ">=2.0.0 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/ts2fable/string-width"
],
"_resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz",
"_shasum": "a3b30a5c4f199183167aaab93beefae3ddfb654f",
"_shrinkwrap": null,
"_spec": "is-fullwidth-code-point@^2.0.0",
"_where": "/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/string-width",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/is-fullwidth-code-point/issues"
},
"dependencies": {},
"description": "Check if the character represented by a given Unicode code point is fullwidth",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"directories": {},
"dist": {
"shasum": "a3b30a5c4f199183167aaab93beefae3ddfb654f",
"tarball": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"gitHead": "e94a78056056c5546f2bf4c4cf812a2163a46dae",
"homepage": "https://github.com/sindresorhus/is-fullwidth-code-point#readme",
"keywords": [
"char",
"character",
"check",
"code",
"codepoint",
"detect",
"full",
"full-width",
"fullwidth",
"is",
"point",
"str",
"string",
"unicode",
"width"
],
"license": "MIT",
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"name": "is-fullwidth-code-point",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/is-fullwidth-code-point.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.0.0",
"xo": {
"esnext": true
}
}
@@ -0,0 +1,39 @@
# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point)
> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms)
## Install
```
$ npm install --save is-fullwidth-code-point
```
## Usage
```js
const isFullwidthCodePoint = require('is-fullwidth-code-point');
isFullwidthCodePoint('谢'.codePointAt());
//=> true
isFullwidthCodePoint('a'.codePointAt());
//=> false
```
## API
### isFullwidthCodePoint(input)
#### input
Type: `number`
[Code point](https://en.wikipedia.org/wiki/Code_point) of a character.
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+101
View File
@@ -0,0 +1,101 @@
'use strict';
const execa = require('execa');
const lcid = require('lcid');
const mem = require('mem');
const defaultOpts = {spawn: true};
const defaultLocale = 'en_US';
function getEnvLocale(env) {
env = env || process.env;
return env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE;
}
function parseLocale(x) {
const env = x.split('\n').reduce((env, def) => {
def = def.split('=');
env[def[0]] = def[1].replace(/^"|"$/g, '');
return env;
}, {});
return getEnvLocale(env);
}
function getLocale(str) {
return (str && str.replace(/[.:].*/, ''));
}
function getAppleLocale() {
return execa.stdout('defaults', ['read', '-g', 'AppleLocale']);
}
function getAppleLocaleSync() {
return execa.sync('defaults', ['read', '-g', 'AppleLocale']).stdout;
}
function getUnixLocale() {
if (process.platform === 'darwin') {
return getAppleLocale();
}
return execa.stdout('locale')
.then(stdout => getLocale(parseLocale(stdout)));
}
function getUnixLocaleSync() {
if (process.platform === 'darwin') {
return getAppleLocaleSync();
}
return getLocale(parseLocale(execa.sync('locale').stdout));
}
function getWinLocale() {
return execa.stdout('wmic', ['os', 'get', 'locale'])
.then(stdout => {
const lcidCode = parseInt(stdout.replace('Locale', ''), 16);
return lcid.from(lcidCode);
});
}
function getWinLocaleSync() {
const stdout = execa.sync('wmic', ['os', 'get', 'locale']).stdout;
const lcidCode = parseInt(stdout.replace('Locale', ''), 16);
return lcid.from(lcidCode);
}
module.exports = mem(opts => {
opts = opts || defaultOpts;
const envLocale = getEnvLocale();
let thenable;
if (envLocale || opts.spawn === false) {
thenable = Promise.resolve(getLocale(envLocale));
} else if (process.platform === 'win32') {
thenable = getWinLocale();
} else {
thenable = getUnixLocale();
}
return thenable.then(locale => locale || defaultLocale)
.catch(() => defaultLocale);
});
module.exports.sync = mem(opts => {
opts = opts || defaultOpts;
const envLocale = getEnvLocale();
let res;
if (envLocale || opts.spawn === false) {
res = getLocale(envLocale);
} else {
try {
if (process.platform === 'win32') {
res = getWinLocaleSync();
} else {
res = getUnixLocaleSync();
}
} catch (err) {}
}
return res || defaultLocale;
});
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+113
View File
@@ -0,0 +1,113 @@
{
"_args": [
[
"os-locale@^2.0.0",
"/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs"
]
],
"_from": "os-locale@>=2.0.0 <3.0.0",
"_id": "os-locale@2.1.0",
"_inCache": true,
"_installable": true,
"_location": "/ts2fable/os-locale",
"_nodeVersion": "8.0.0",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/os-locale-2.1.0.tgz_1500667149329_0.6210105223581195"
},
"_npmUser": {
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
},
"_npmVersion": "5.0.0",
"_phantomChildren": {},
"_requested": {
"name": "os-locale",
"raw": "os-locale@^2.0.0",
"rawSpec": "^2.0.0",
"scope": null,
"spec": ">=2.0.0 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/ts2fable/yargs"
],
"_resolved": "https://registry.npmjs.org/os-locale/-/os-locale-2.1.0.tgz",
"_shasum": "42bc2900a6b5b8bd17376c8e882b65afccf24bf2",
"_shrinkwrap": null,
"_spec": "os-locale@^2.0.0",
"_where": "/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/os-locale/issues"
},
"dependencies": {
"execa": "^0.7.0",
"lcid": "^1.0.0",
"mem": "^1.1.0"
},
"description": "Get the system locale",
"devDependencies": {
"ava": "*",
"import-fresh": "^2.0.0",
"xo": "*"
},
"directories": {},
"dist": {
"integrity": "sha512-3sslG3zJbEYcaC4YVAvDorjGxc7tv6KVATnLPZONiljsUncvihe9BQoVCEs0RZ1kmf4Hk9OBqlZfJZWI4GanKA==",
"shasum": "42bc2900a6b5b8bd17376c8e882b65afccf24bf2",
"tarball": "https://registry.npmjs.org/os-locale/-/os-locale-2.1.0.tgz"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"gitHead": "7322d9e8db79bbf153906e6b2870832893f5e1e5",
"homepage": "https://github.com/sindresorhus/os-locale#readme",
"keywords": [
"country",
"id",
"identifier",
"lang",
"language",
"locale",
"os",
"region",
"str",
"string",
"system",
"user"
],
"license": "MIT",
"maintainers": [
{
"name": "bcoe",
"email": "ben@npmjs.com"
},
{
"name": "nexdrew",
"email": "andrew@npmjs.com"
},
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"name": "os-locale",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/os-locale.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.1.0"
}
+53
View File
@@ -0,0 +1,53 @@
# os-locale [![Build Status](https://travis-ci.org/sindresorhus/os-locale.svg?branch=master)](https://travis-ci.org/sindresorhus/os-locale)
> Get the system [locale](https://en.wikipedia.org/wiki/Locale_(computer_software))
Useful for localizing your module or app.
POSIX systems: The returned locale refers to the [`LC_MESSAGE`](http://www.gnu.org/software/libc/manual/html_node/Locale-Categories.html#Locale-Categories) category, suitable for selecting the language used in the user interface for message translation.
## Install
```
$ npm install --save os-locale
```
## Usage
```js
const osLocale = require('os-locale');
osLocale().then(locale => {
console.log(locale);
//=> 'en_US'
});
```
## API
### osLocale([options])
Returns a `Promise` for the locale.
### osLocale.sync([options])
Returns the locale.
#### options
Type: `Object`
##### spawn
Type: `boolean`<br>
Default: `true`
Set to `false` to avoid spawning subprocesses and instead only resolve the locale from environment variables.
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+36
View File
@@ -0,0 +1,36 @@
'use strict';
const stripAnsi = require('strip-ansi');
const isFullwidthCodePoint = require('is-fullwidth-code-point');
module.exports = str => {
if (typeof str !== 'string' || str.length === 0) {
return 0;
}
str = stripAnsi(str);
let width = 0;
for (let i = 0; i < str.length; i++) {
const code = str.codePointAt(i);
// Ignore control characters
if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
continue;
}
// Ignore combining characters
if (code >= 0x300 && code <= 0x36F) {
continue;
}
// Surrogates
if (code > 0xFFFF) {
i++;
}
width += isFullwidthCodePoint(code) ? 2 : 1;
}
return width;
};
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+116
View File
@@ -0,0 +1,116 @@
{
"_args": [
[
"string-width@^2.0.0",
"/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs"
]
],
"_from": "string-width@>=2.0.0 <3.0.0",
"_id": "string-width@2.1.1",
"_inCache": true,
"_installable": true,
"_location": "/ts2fable/string-width",
"_nodeVersion": "8.0.0",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/string-width-2.1.1.tgz_1500376154382_0.7171604454051703"
},
"_npmUser": {
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
},
"_npmVersion": "5.0.0",
"_phantomChildren": {},
"_requested": {
"name": "string-width",
"raw": "string-width@^2.0.0",
"rawSpec": "^2.0.0",
"scope": null,
"spec": ">=2.0.0 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/ts2fable/cliui",
"/ts2fable/yargs"
],
"_resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
"_shasum": "ab93f27a8dc13d28cac815c462143a6d9012ae9e",
"_shrinkwrap": null,
"_spec": "string-width@^2.0.0",
"_where": "/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/string-width/issues"
},
"dependencies": {
"is-fullwidth-code-point": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"description": "Get the visual width of a string - the number of columns required to display it",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"directories": {},
"dist": {
"integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==",
"shasum": "ab93f27a8dc13d28cac815c462143a6d9012ae9e",
"tarball": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"gitHead": "74d8d552b465692790c41169b123409669d41079",
"homepage": "https://github.com/sindresorhus/string-width#readme",
"keywords": [
"ansi",
"char",
"character",
"chinese",
"cjk",
"cli",
"codes",
"column",
"columns",
"command-line",
"console",
"escape",
"fixed-width",
"full",
"full-width",
"fullwidth",
"japanese",
"korean",
"str",
"string",
"terminal",
"unicode",
"visual",
"width"
],
"license": "MIT",
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"name": "string-width",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/string-width.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.1.1"
}
+42
View File
@@ -0,0 +1,42 @@
# string-width [![Build Status](https://travis-ci.org/sindresorhus/string-width.svg?branch=master)](https://travis-ci.org/sindresorhus/string-width)
> Get the visual width of a string - the number of columns required to display it
Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width.
Useful to be able to measure the actual width of command-line output.
## Install
```
$ npm install string-width
```
## Usage
```js
const stringWidth = require('string-width');
stringWidth('古');
//=> 2
stringWidth('\u001b[1m古\u001b[22m');
//=> 2
stringWidth('a');
//=> 1
```
## Related
- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module
- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string
- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+4
View File
@@ -0,0 +1,4 @@
'use strict';
const ansiRegex = require('ansi-regex');
module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input;
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+120
View File
@@ -0,0 +1,120 @@
{
"_args": [
[
"strip-ansi@^4.0.0",
"/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/cliui"
]
],
"_from": "strip-ansi@>=4.0.0 <5.0.0",
"_id": "strip-ansi@4.0.0",
"_inCache": true,
"_installable": true,
"_location": "/ts2fable/strip-ansi",
"_nodeVersion": "4.8.3",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/strip-ansi-4.0.0.tgz_1497986904730_0.4528853143565357"
},
"_npmUser": {
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
},
"_npmVersion": "2.15.11",
"_phantomChildren": {},
"_requested": {
"name": "strip-ansi",
"raw": "strip-ansi@^4.0.0",
"rawSpec": "^4.0.0",
"scope": null,
"spec": ">=4.0.0 <5.0.0",
"type": "range"
},
"_requiredBy": [
"/ts2fable/cliui",
"/ts2fable/string-width"
],
"_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
"_shasum": "a8479022eb1ac368a871389b635262c505ee368f",
"_shrinkwrap": null,
"_spec": "strip-ansi@^4.0.0",
"_where": "/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/cliui",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/strip-ansi/issues"
},
"dependencies": {
"ansi-regex": "^3.0.0"
},
"description": "Strip ANSI escape codes",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"directories": {},
"dist": {
"shasum": "a8479022eb1ac368a871389b635262c505ee368f",
"tarball": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"gitHead": "c299056a42b31d7a479d6a89b41318b2a2462cc7",
"homepage": "https://github.com/chalk/strip-ansi#readme",
"keywords": [
"256",
"ansi",
"color",
"colors",
"colour",
"command-line",
"console",
"escape",
"formatting",
"log",
"logging",
"remove",
"rgb",
"shell",
"string",
"strip",
"styles",
"terminal",
"text",
"trim",
"tty",
"xterm"
],
"license": "MIT",
"maintainers": [
{
"name": "dthree",
"email": "threedeecee@gmail.com"
},
{
"name": "qix",
"email": "i.am.qix@gmail.com"
},
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"name": "strip-ansi",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/strip-ansi.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "4.0.0"
}
+39
View File
@@ -0,0 +1,39 @@
# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi)
> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install strip-ansi
```
## Usage
```js
const stripAnsi = require('strip-ansi');
stripAnsi('\u001B[4mUnicorn\u001B[0m');
//=> 'Unicorn'
```
## Related
- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT
+26
View File
@@ -0,0 +1,26 @@
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="2.0.0"></a>
# [2.0.0](https://github.com/nexdrew/which-module/compare/v1.0.0...v2.0.0) (2017-05-01)
### Features
* remove Node < 4 from official testing/support ([#22](https://github.com/nexdrew/which-module/issues/22)) ([ee7aff4](https://github.com/nexdrew/which-module/commit/ee7aff4))
### BREAKING CHANGES
* Node 0.10 or 0.12 no longer supported, please update to Node 4+ or use which-module@1.0.0
<a name="1.0.0"></a>
# 1.0.0 (2016-06-06)
### Features
* initial code ([08074cd](https://github.com/nexdrew/which-module/commit/08074cd))
+13
View File
@@ -0,0 +1,13 @@
Copyright (c) 2016, Contributors
Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
+55
View File
@@ -0,0 +1,55 @@
# which-module
> Find the module object for something that was require()d
[![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module)
[![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master)
[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version)
Find the `module` object in `require.cache` for something that was `require()`d
or `import`ed - essentially a reverse `require()` lookup.
Useful for libs that want to e.g. lookup a filename for a module or submodule
that it did not `require()` itself.
## Install and Usage
```
npm install --save which-module
```
```js
const whichModule = require('which-module')
console.log(whichModule(require('something')))
// Module {
// id: '/path/to/project/node_modules/something/index.js',
// exports: [Function],
// parent: ...,
// filename: '/path/to/project/node_modules/something/index.js',
// loaded: true,
// children: [],
// paths: [ '/path/to/project/node_modules/something/node_modules',
// '/path/to/project/node_modules',
// '/path/to/node_modules',
// '/path/node_modules',
// '/node_modules' ] }
```
## API
### `whichModule(exported)`
Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object),
if any, that represents the given argument in the `require.cache`.
`exported` can be anything that was previously `require()`d or `import`ed as a
module, submodule, or dependency - which means `exported` is identical to the
`module.exports` returned by this method.
If `exported` did not come from the `exports` of a `module` in `require.cache`,
then this method returns `null`.
## License
ISC © Contributors
+9
View File
@@ -0,0 +1,9 @@
'use strict'
module.exports = function whichModule (exported) {
for (var i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
mod = require.cache[files[i]]
if (mod.exports === exported) return mod
}
return null
}
+96
View File
@@ -0,0 +1,96 @@
{
"_args": [
[
"which-module@^2.0.0",
"/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs"
]
],
"_from": "which-module@>=2.0.0 <3.0.0",
"_id": "which-module@2.0.0",
"_inCache": true,
"_installable": true,
"_location": "/ts2fable/which-module",
"_nodeVersion": "7.9.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/which-module-2.0.0.tgz_1493670259112_0.19386909971944988"
},
"_npmUser": {
"email": "andrew@npmjs.com",
"name": "nexdrew"
},
"_npmVersion": "4.2.0",
"_phantomChildren": {},
"_requested": {
"name": "which-module",
"raw": "which-module@^2.0.0",
"rawSpec": "^2.0.0",
"scope": null,
"spec": ">=2.0.0 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/ts2fable/yargs"
],
"_resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz",
"_shasum": "d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a",
"_shrinkwrap": null,
"_spec": "which-module@^2.0.0",
"_where": "/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs",
"author": {
"name": "nexdrew"
},
"bugs": {
"url": "https://github.com/nexdrew/which-module/issues"
},
"dependencies": {},
"description": "Find the module object for something that was require()d",
"devDependencies": {
"ava": "^0.19.1",
"coveralls": "^2.13.1",
"nyc": "^10.3.0",
"standard": "^10.0.2",
"standard-version": "^4.0.0"
},
"directories": {},
"dist": {
"shasum": "d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a",
"tarball": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz"
},
"files": [
"index.js"
],
"gitHead": "7f78f42d0761133263c3947a3b24dde324a467ce",
"homepage": "https://github.com/nexdrew/which-module#readme",
"keywords": [
"exports",
"filename",
"lookup",
"module",
"require",
"reverse",
"which"
],
"license": "ISC",
"main": "index.js",
"maintainers": [
{
"name": "nexdrew",
"email": "andrew@npmjs.com"
}
],
"name": "which-module",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/nexdrew/which-module.git"
},
"scripts": {
"coverage": "nyc report --reporter=text-lcov | coveralls",
"pretest": "standard",
"release": "standard-version",
"test": "nyc ava"
},
"version": "2.0.0"
}
+265
View File
@@ -0,0 +1,265 @@
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="8.1.0"></a>
# [8.1.0](https://github.com/yargs/yargs-parser/compare/v8.0.0...v8.1.0) (2017-12-20)
### Bug Fixes
* allow null config values ([#108](https://github.com/yargs/yargs-parser/issues/108)) ([d8b14f9](https://github.com/yargs/yargs-parser/commit/d8b14f9))
* ensure consistent parsing of dot-notation arguments ([#102](https://github.com/yargs/yargs-parser/issues/102)) ([c9bd79c](https://github.com/yargs/yargs-parser/commit/c9bd79c))
* implement [@antoniom](https://github.com/antoniom)'s fix for camel-case expansion ([3087e1d](https://github.com/yargs/yargs-parser/commit/3087e1d))
* only run coercion functions once, despite aliases. ([#76](https://github.com/yargs/yargs-parser/issues/76)) ([#103](https://github.com/yargs/yargs-parser/issues/103)) ([507aaef](https://github.com/yargs/yargs-parser/commit/507aaef))
* scientific notation circumvented bounds check ([#110](https://github.com/yargs/yargs-parser/issues/110)) ([3571f57](https://github.com/yargs/yargs-parser/commit/3571f57))
* tokenizer should ignore spaces at the beginning of the argString ([#106](https://github.com/yargs/yargs-parser/issues/106)) ([f34ead9](https://github.com/yargs/yargs-parser/commit/f34ead9))
### Features
* make combining arrays a configurable option ([#111](https://github.com/yargs/yargs-parser/issues/111)) ([c8bf536](https://github.com/yargs/yargs-parser/commit/c8bf536))
* merge array from arguments with array from config ([#83](https://github.com/yargs/yargs-parser/issues/83)) ([806ddd6](https://github.com/yargs/yargs-parser/commit/806ddd6))
<a name="8.0.0"></a>
# [8.0.0](https://github.com/yargs/yargs-parser/compare/v7.0.0...v8.0.0) (2017-10-05)
### Bug Fixes
* Ignore multiple spaces between arguments. ([#100](https://github.com/yargs/yargs-parser/issues/100)) ([d137227](https://github.com/yargs/yargs-parser/commit/d137227))
### Features
* allow configuration of prefix for boolean negation ([#94](https://github.com/yargs/yargs-parser/issues/94)) ([00bde7d](https://github.com/yargs/yargs-parser/commit/00bde7d))
* reworking how numbers are parsed ([#104](https://github.com/yargs/yargs-parser/issues/104)) ([fba00eb](https://github.com/yargs/yargs-parser/commit/fba00eb))
### BREAKING CHANGES
* strings that fail `Number.isSafeInteger()` are no longer coerced into numbers.
<a name="7.0.0"></a>
# [7.0.0](https://github.com/yargs/yargs-parser/compare/v6.0.1...v7.0.0) (2017-05-02)
### Chores
* revert populate-- logic ([#91](https://github.com/yargs/yargs-parser/issues/91)) ([6003e6d](https://github.com/yargs/yargs-parser/commit/6003e6d))
### BREAKING CHANGES
* populate-- now defaults to false.
<a name="6.0.1"></a>
## [6.0.1](https://github.com/yargs/yargs-parser/compare/v6.0.0...v6.0.1) (2017-05-01)
### Bug Fixes
* default '--' to undefined when not provided; this is closer to the array API ([#90](https://github.com/yargs/yargs-parser/issues/90)) ([4e739cc](https://github.com/yargs/yargs-parser/commit/4e739cc))
<a name="6.0.0"></a>
# [6.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v6.0.0) (2017-05-01)
### Bug Fixes
* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f))
* parsing hints should apply for dot notation keys ([#86](https://github.com/yargs/yargs-parser/issues/86)) ([3e47d62](https://github.com/yargs/yargs-parser/commit/3e47d62))
### Chores
* upgrade to newest version of camelcase ([#87](https://github.com/yargs/yargs-parser/issues/87)) ([f1903aa](https://github.com/yargs/yargs-parser/commit/f1903aa))
### Features
* add -- option which allows arguments after the -- flag to be returned separated from positional arguments ([#84](https://github.com/yargs/yargs-parser/issues/84)) ([2572ca8](https://github.com/yargs/yargs-parser/commit/2572ca8))
* when parsing stops, we now populate "--" by default ([#88](https://github.com/yargs/yargs-parser/issues/88)) ([cd666db](https://github.com/yargs/yargs-parser/commit/cd666db))
### BREAKING CHANGES
* rather than placing arguments in "_", when parsing is stopped via "--"; we now populate an array called "--" by default.
* camelcase now requires Node 4+.
* environment variables will now override config files (args, env, config-file, config-object)
<a name="5.0.0"></a>
# [5.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v5.0.0) (2017-02-18)
### Bug Fixes
* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f))
### BREAKING CHANGES
* environment variables will now override config files (args, env, config-file, config-object)
<a name="4.2.1"></a>
## [4.2.1](https://github.com/yargs/yargs-parser/compare/v4.2.0...v4.2.1) (2017-01-02)
### Bug Fixes
* flatten/duplicate regression ([#75](https://github.com/yargs/yargs-parser/issues/75)) ([68d68a0](https://github.com/yargs/yargs-parser/commit/68d68a0))
<a name="4.2.0"></a>
# [4.2.0](https://github.com/yargs/yargs-parser/compare/v4.1.0...v4.2.0) (2016-12-01)
### Bug Fixes
* inner objects in configs had their keys appended to top-level key when dot-notation was disabled ([#72](https://github.com/yargs/yargs-parser/issues/72)) ([0b1b5f9](https://github.com/yargs/yargs-parser/commit/0b1b5f9))
### Features
* allow multiple arrays to be provided, rather than always combining ([#71](https://github.com/yargs/yargs-parser/issues/71)) ([0f0fb2d](https://github.com/yargs/yargs-parser/commit/0f0fb2d))
<a name="4.1.0"></a>
# [4.1.0](https://github.com/yargs/yargs-parser/compare/v4.0.2...v4.1.0) (2016-11-07)
### Features
* apply coercions to default options ([#65](https://github.com/yargs/yargs-parser/issues/65)) ([c79052b](https://github.com/yargs/yargs-parser/commit/c79052b))
* handle dot notation boolean options ([#63](https://github.com/yargs/yargs-parser/issues/63)) ([02c3545](https://github.com/yargs/yargs-parser/commit/02c3545))
<a name="4.0.2"></a>
## [4.0.2](https://github.com/yargs/yargs-parser/compare/v4.0.1...v4.0.2) (2016-09-30)
### Bug Fixes
* whoops, let's make the assign not change the Object key order ([29d069a](https://github.com/yargs/yargs-parser/commit/29d069a))
<a name="4.0.1"></a>
## [4.0.1](https://github.com/yargs/yargs-parser/compare/v4.0.0...v4.0.1) (2016-09-30)
### Bug Fixes
* lodash.assign was deprecated ([#59](https://github.com/yargs/yargs-parser/issues/59)) ([5e7eb11](https://github.com/yargs/yargs-parser/commit/5e7eb11))
<a name="4.0.0"></a>
# [4.0.0](https://github.com/yargs/yargs-parser/compare/v3.2.0...v4.0.0) (2016-09-26)
### Bug Fixes
* coerce should be applied to the final objects and arrays created ([#57](https://github.com/yargs/yargs-parser/issues/57)) ([4ca69da](https://github.com/yargs/yargs-parser/commit/4ca69da))
### BREAKING CHANGES
* coerce is no longer applied to individual arguments in an implicit array.
<a name="3.2.0"></a>
# [3.2.0](https://github.com/yargs/yargs-parser/compare/v3.1.0...v3.2.0) (2016-08-13)
### Features
* coerce full array instead of each element ([#51](https://github.com/yargs/yargs-parser/issues/51)) ([cc4dc56](https://github.com/yargs/yargs-parser/commit/cc4dc56))
<a name="3.1.0"></a>
# [3.1.0](https://github.com/yargs/yargs-parser/compare/v3.0.0...v3.1.0) (2016-08-09)
### Bug Fixes
* address pkgConf parsing bug outlined in [#37](https://github.com/yargs/yargs-parser/issues/37) ([#45](https://github.com/yargs/yargs-parser/issues/45)) ([be76ee6](https://github.com/yargs/yargs-parser/commit/be76ee6))
* better parsing of negative values ([#44](https://github.com/yargs/yargs-parser/issues/44)) ([2e43692](https://github.com/yargs/yargs-parser/commit/2e43692))
* check aliases when guessing defaults for arguments fixes [#41](https://github.com/yargs/yargs-parser/issues/41) ([#43](https://github.com/yargs/yargs-parser/issues/43)) ([f3e4616](https://github.com/yargs/yargs-parser/commit/f3e4616))
### Features
* added coerce option, for providing specialized argument parsing ([#42](https://github.com/yargs/yargs-parser/issues/42)) ([7b49cd2](https://github.com/yargs/yargs-parser/commit/7b49cd2))
<a name="3.0.0"></a>
# [3.0.0](https://github.com/yargs/yargs-parser/compare/v2.4.1...v3.0.0) (2016-08-07)
### Bug Fixes
* parsing issue with numeric character in group of options ([#19](https://github.com/yargs/yargs-parser/issues/19)) ([f743236](https://github.com/yargs/yargs-parser/commit/f743236))
* upgraded lodash.assign ([5d7fdf4](https://github.com/yargs/yargs-parser/commit/5d7fdf4))
### BREAKING CHANGES
* subtle change to how values are parsed in a group of single-character arguments.
* _first released in 3.1.0, better handling of negative values should be considered a breaking change._
<a name="2.4.1"></a>
## [2.4.1](https://github.com/yargs/yargs-parser/compare/v2.4.0...v2.4.1) (2016-07-16)
### Bug Fixes
* **count:** do not increment a default value ([#39](https://github.com/yargs/yargs-parser/issues/39)) ([b04a189](https://github.com/yargs/yargs-parser/commit/b04a189))
<a name="2.4.0"></a>
# [2.4.0](https://github.com/yargs/yargs-parser/compare/v2.3.0...v2.4.0) (2016-04-11)
### Features
* **environment:** Support nested options in environment variables ([#26](https://github.com/yargs/yargs-parser/issues/26)) thanks [@elas7](https://github.com/elas7) \o/ ([020778b](https://github.com/yargs/yargs-parser/commit/020778b))
<a name="2.3.0"></a>
# [2.3.0](https://github.com/yargs/yargs-parser/compare/v2.2.0...v2.3.0) (2016-04-09)
### Bug Fixes
* **boolean:** fix for boolean options with non boolean defaults (#20) ([2dbe86b](https://github.com/yargs/yargs-parser/commit/2dbe86b)), closes [(#20](https://github.com/(/issues/20)
* **package:** remove tests from tarball ([0353c0d](https://github.com/yargs/yargs-parser/commit/0353c0d))
* **parsing:** handle calling short option with an empty string as the next value. ([a867165](https://github.com/yargs/yargs-parser/commit/a867165))
* boolean flag when next value contains the strings 'true' or 'false'. ([69941a6](https://github.com/yargs/yargs-parser/commit/69941a6))
* update dependencies; add standard-version bin for next release (#24) ([822d9d5](https://github.com/yargs/yargs-parser/commit/822d9d5))
### Features
* **configuration:** Allow to pass configuration objects to yargs-parser ([0780900](https://github.com/yargs/yargs-parser/commit/0780900))
* **normalize:** allow normalize to work with arrays ([e0eaa1a](https://github.com/yargs/yargs-parser/commit/e0eaa1a))
+14
View File
@@ -0,0 +1,14 @@
Copyright (c) 2016, Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice
appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+308
View File
@@ -0,0 +1,308 @@
# yargs-parser
[![Build Status](https://travis-ci.org/yargs/yargs-parser.png)](https://travis-ci.org/yargs/yargs-parser)
[![Coverage Status](https://coveralls.io/repos/yargs/yargs-parser/badge.svg?branch=)](https://coveralls.io/r/yargs/yargs-parser?branch=master)
[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser)
[![Windows Tests](https://img.shields.io/appveyor/ci/bcoe/yargs-parser/master.svg?label=Windows%20Tests)](https://ci.appveyor.com/project/bcoe/yargs-parser)
[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version)
The mighty option parser used by [yargs](https://github.com/yargs/yargs).
visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions.
<img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png">
## Example
```sh
npm i yargs-parser --save
```
```js
var argv = require('yargs-parser')(process.argv.slice(2))
console.log(argv)
```
```sh
node example.js --foo=33 --bar hello
{ _: [], foo: 33, bar: 'hello' }
```
_or parse a string!_
```js
var argv = require('./')('--foo=99 --bar=33')
console.log(argv)
```
```sh
{ _: [], foo: 99, bar: 33 }
```
Convert an array of mixed types before passing to `yargs-parser`:
```js
var parse = require('yargs-parser')
parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string
parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings
```
## API
### require('yargs-parser')(args, opts={})
Parses command line arguments returning a simple mapping of keys and values.
**expects:**
* `args`: a string or array of strings representing the options to parse.
* `opts`: provide a set of hints indicating how `args` should be parsed:
* `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`.
* `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.
* `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`.
* `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed).
* `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided
(or throws an error), e.g. `{coerce: {foo: function (arg) {return modifiedArg}}}`.
* `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`.
* `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`.
* `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed.
* `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`.
* `opts.normalize`: `path.normalize()` will be applied to values set to this key.
* `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`).
* `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)).
* `opts.number`: keys should be treated as numbers.
* `opts['--']`: arguments after the end-of-options flag `--` will be set to the `argv.['--']` array instead of being set to the `argv._` array.
**returns:**
* `obj`: an object representing the parsed value of `args`
* `key/value`: key value pairs for each argument and their aliases.
* `_`: an array representing the positional arguments.
* [optional] `--`: an array with arguments after the end-of-options flag `--`.
### require('yargs-parser').detailed(args, opts={})
Parses a command line string, returning detailed information required by the
yargs engine.
**expects:**
* `args`: a string or array of strings representing options to parse.
* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`.
**returns:**
* `argv`: an object representing the parsed value of `args`
* `key/value`: key value pairs for each argument and their aliases.
* `_`: an array representing the positional arguments.
* `error`: populated with an error object if an exception occurred during parsing.
* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`.
* `newAliases`: any new aliases added via camel-case expansion.
* `configuration`: the configuration loaded from the `yargs` stanza in package.json.
<a name="configuration"></a>
### Configuration
The yargs-parser applies several automated transformations on the keys provided
in `args`. These features can be turned on and off using the `configuration` field
of `opts`.
```js
var parsed = parser(['--no-dice'], {
configuration: {
'boolean-negation': false
}
})
```
### short option groups
* default: `true`.
* key: `short-option-groups`.
Should a group of short-options be treated as boolean flags?
```sh
node example.js -abc
{ _: [], a: true, b: true, c: true }
```
_if disabled:_
```sh
node example.js -abc
{ _: [], abc: true }
```
### camel-case expansion
* default: `true`.
* key: `camel-case-expansion`.
Should hyphenated arguments be expanded into camel-case aliases?
```sh
node example.js --foo-bar
{ _: [], 'foo-bar': true, fooBar: true }
```
_if disabled:_
```sh
node example.js --foo-bar
{ _: [], 'foo-bar': true }
```
### dot-notation
* default: `true`
* key: `dot-notation`
Should keys that contain `.` be treated as objects?
```sh
node example.js --foo.bar
{ _: [], foo: { bar: true } }
```
_if disabled:_
```sh
node example.js --foo.bar
{ _: [], "foo.bar": true }
```
### parse numbers
* default: `true`
* key: `parse-numbers`
Should keys that look like numbers be treated as such?
```sh
node example.js --foo=99.3
{ _: [], foo: 99.3 }
```
_if disabled:_
```sh
node example.js --foo=99.3
{ _: [], foo: "99.3" }
```
### boolean negation
* default: `true`
* key: `boolean-negation`
Should variables prefixed with `--no` be treated as negations?
```sh
node example.js --no-foo
{ _: [], foo: false }
```
_if disabled:_
```sh
node example.js --no-foo
{ _: [], "no-foo": true }
```
### combine arrays
* default: `false`
* key: `combine-arrays`
Should arrays be combined when provided by both command line arguments and
a configuration file.
### duplicate arguments array
* default: `true`
* key: `duplicate-arguments-array`
Should arguments be coerced into an array when duplicated:
```sh
node example.js -x 1 -x 2
{ _: [], x: [1, 2] }
```
_if disabled:_
```sh
node example.js -x 1 -x 2
{ _: [], x: 2 }
```
### flatten duplicate arrays
* default: `true`
* key: `flatten-duplicate-arrays`
Should array arguments be coerced into a single array when duplicated:
```sh
node example.js -x 1 2 -x 3 4
{ _: [], x: [1, 2, 3, 4] }
```
_if disabled:_
```sh
node example.js -x 1 2 -x 3 4
{ _: [], x: [[1, 2], [3, 4]] }
```
### negation prefix
* default: `no-`
* key: `negation-prefix`
The prefix to use for negated boolean variables.
```sh
node example.js --no-foo
{ _: [], foo: false }
```
_if set to `quux`:_
```sh
node example.js --quuxfoo
{ _: [], foo: false }
```
### populate --
* default: `false`.
* key: `populate--`
Should unparsed flags be stored in `--` or `_`.
_If disabled:_
```sh
node example.js a -b -- x y
{ _: [ 'a', 'x', 'y' ], b: true }
```
_If enabled:_
```sh
node example.js a -b -- x y
{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true }
```
## Special Thanks
The yargs project evolves from optimist and minimist. It owes its
existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/
## License
ISC
+801
View File
@@ -0,0 +1,801 @@
var camelCase = require('camelcase')
var path = require('path')
var tokenizeArgString = require('./lib/tokenize-arg-string')
var util = require('util')
function parse (args, opts) {
if (!opts) opts = {}
// allow a string argument to be passed in rather
// than an argv array.
args = tokenizeArgString(args)
// aliases might have transitive relationships, normalize this.
var aliases = combineAliases(opts.alias || {})
var configuration = assign({
'short-option-groups': true,
'camel-case-expansion': true,
'dot-notation': true,
'parse-numbers': true,
'boolean-negation': true,
'negation-prefix': 'no-',
'duplicate-arguments-array': true,
'flatten-duplicate-arrays': true,
'populate--': false,
'combine-arrays': false
}, opts.configuration)
var defaults = opts.default || {}
var configObjects = opts.configObjects || []
var envPrefix = opts.envPrefix
var notFlagsOption = configuration['populate--']
var notFlagsArgv = notFlagsOption ? '--' : '_'
var newAliases = {}
// allow a i18n handler to be passed in, default to a fake one (util.format).
var __ = opts.__ || function (str) {
return util.format.apply(util, Array.prototype.slice.call(arguments))
}
var error = null
var flags = {
aliases: {},
arrays: {},
bools: {},
strings: {},
numbers: {},
counts: {},
normalize: {},
configs: {},
defaulted: {},
nargs: {},
coercions: {}
}
var negative = /^-[0-9]+(\.[0-9]+)?/
var negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)')
;[].concat(opts.array).filter(Boolean).forEach(function (key) {
flags.arrays[key] = true
})
;[].concat(opts.boolean).filter(Boolean).forEach(function (key) {
flags.bools[key] = true
})
;[].concat(opts.string).filter(Boolean).forEach(function (key) {
flags.strings[key] = true
})
;[].concat(opts.number).filter(Boolean).forEach(function (key) {
flags.numbers[key] = true
})
;[].concat(opts.count).filter(Boolean).forEach(function (key) {
flags.counts[key] = true
})
;[].concat(opts.normalize).filter(Boolean).forEach(function (key) {
flags.normalize[key] = true
})
Object.keys(opts.narg || {}).forEach(function (k) {
flags.nargs[k] = opts.narg[k]
})
Object.keys(opts.coerce || {}).forEach(function (k) {
flags.coercions[k] = opts.coerce[k]
})
if (Array.isArray(opts.config) || typeof opts.config === 'string') {
;[].concat(opts.config).filter(Boolean).forEach(function (key) {
flags.configs[key] = true
})
} else {
Object.keys(opts.config || {}).forEach(function (k) {
flags.configs[k] = opts.config[k]
})
}
// create a lookup table that takes into account all
// combinations of aliases: {f: ['foo'], foo: ['f']}
extendAliases(opts.key, aliases, opts.default, flags.arrays)
// apply default values to all aliases.
Object.keys(defaults).forEach(function (key) {
(flags.aliases[key] || []).forEach(function (alias) {
defaults[alias] = defaults[key]
})
})
var argv = { _: [] }
Object.keys(flags.bools).forEach(function (key) {
setArg(key, !(key in defaults) ? false : defaults[key])
setDefaulted(key)
})
var notFlags = []
if (args.indexOf('--') !== -1) {
notFlags = args.slice(args.indexOf('--') + 1)
args = args.slice(0, args.indexOf('--'))
}
for (var i = 0; i < args.length; i++) {
var arg = args[i]
var broken
var key
var letters
var m
var next
var value
// -- seperated by =
if (arg.match(/^--.+=/) || (
!configuration['short-option-groups'] && arg.match(/^-.+=/)
)) {
// Using [\s\S] instead of . because js doesn't support the
// 'dotall' regex modifier. See:
// http://stackoverflow.com/a/1068308/13216
m = arg.match(/^--?([^=]+)=([\s\S]*)$/)
// nargs format = '--f=monkey washing cat'
if (checkAllAliases(m[1], flags.nargs)) {
args.splice(i + 1, 0, m[2])
i = eatNargs(i, m[1], args)
// arrays format = '--f=a b c'
} else if (checkAllAliases(m[1], flags.arrays) && args.length > i + 1) {
args.splice(i + 1, 0, m[2])
i = eatArray(i, m[1], args)
} else {
setArg(m[1], m[2])
}
} else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
key = arg.match(negatedBoolean)[1]
setArg(key, false)
// -- seperated by space.
} else if (arg.match(/^--.+/) || (
!configuration['short-option-groups'] && arg.match(/^-.+/)
)) {
key = arg.match(/^--?(.+)/)[1]
// nargs format = '--foo a b c'
if (checkAllAliases(key, flags.nargs)) {
i = eatNargs(i, key, args)
// array format = '--foo a b c'
} else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
i = eatArray(i, key, args)
} else {
next = args[i + 1]
if (next !== undefined && (!next.match(/^-/) ||
next.match(negative)) &&
!checkAllAliases(key, flags.bools) &&
!checkAllAliases(key, flags.counts)) {
setArg(key, next)
i++
} else if (/^(true|false)$/.test(next)) {
setArg(key, next)
i++
} else {
setArg(key, defaultForType(guessType(key, flags)))
}
}
// dot-notation flag seperated by '='.
} else if (arg.match(/^-.\..+=/)) {
m = arg.match(/^-([^=]+)=([\s\S]*)$/)
setArg(m[1], m[2])
// dot-notation flag seperated by space.
} else if (arg.match(/^-.\..+/)) {
next = args[i + 1]
key = arg.match(/^-(.\..+)/)[1]
if (next !== undefined && !next.match(/^-/) &&
!checkAllAliases(key, flags.bools) &&
!checkAllAliases(key, flags.counts)) {
setArg(key, next)
i++
} else {
setArg(key, defaultForType(guessType(key, flags)))
}
} else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
letters = arg.slice(1, -1).split('')
broken = false
for (var j = 0; j < letters.length; j++) {
next = arg.slice(j + 2)
if (letters[j + 1] && letters[j + 1] === '=') {
value = arg.slice(j + 3)
key = letters[j]
// nargs format = '-f=monkey washing cat'
if (checkAllAliases(key, flags.nargs)) {
args.splice(i + 1, 0, value)
i = eatNargs(i, key, args)
// array format = '-f=a b c'
} else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
args.splice(i + 1, 0, value)
i = eatArray(i, key, args)
} else {
setArg(key, value)
}
broken = true
break
}
if (next === '-') {
setArg(letters[j], next)
continue
}
// current letter is an alphabetic character and next value is a number
if (/[A-Za-z]/.test(letters[j]) &&
/^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j], next)
broken = true
break
}
if (letters[j + 1] && letters[j + 1].match(/\W/)) {
setArg(letters[j], next)
broken = true
break
} else {
setArg(letters[j], defaultForType(guessType(letters[j], flags)))
}
}
key = arg.slice(-1)[0]
if (!broken && key !== '-') {
// nargs format = '-f a b c'
if (checkAllAliases(key, flags.nargs)) {
i = eatNargs(i, key, args)
// array format = '-f a b c'
} else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
i = eatArray(i, key, args)
} else {
next = args[i + 1]
if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
next.match(negative)) &&
!checkAllAliases(key, flags.bools) &&
!checkAllAliases(key, flags.counts)) {
setArg(key, next)
i++
} else if (/^(true|false)$/.test(next)) {
setArg(key, next)
i++
} else {
setArg(key, defaultForType(guessType(key, flags)))
}
}
}
} else {
argv._.push(maybeCoerceNumber('_', arg))
}
}
// order of precedence:
// 1. command line arg
// 2. value from env var
// 3. value from config file
// 4. value from config objects
// 5. configured default value
applyEnvVars(argv, true) // special case: check env vars that point to config file
applyEnvVars(argv, false)
setConfig(argv)
setConfigObjects()
applyDefaultsAndAliases(argv, flags.aliases, defaults)
applyCoercions(argv)
// for any counts either not in args or without an explicit default, set to 0
Object.keys(flags.counts).forEach(function (key) {
if (!hasKey(argv, key.split('.'))) setArg(key, 0)
})
// '--' defaults to undefined.
if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = []
notFlags.forEach(function (key) {
argv[notFlagsArgv].push(key)
})
// how many arguments should we consume, based
// on the nargs option?
function eatNargs (i, key, args) {
var toEat = checkAllAliases(key, flags.nargs)
if (args.length - (i + 1) < toEat) error = Error(__('Not enough arguments following: %s', key))
for (var ii = i + 1; ii < (toEat + i + 1); ii++) {
setArg(key, args[ii])
}
return (i + toEat)
}
// if an option is an array, eat all non-hyphenated arguments
// following it... YUM!
// e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
function eatArray (i, key, args) {
var start = i + 1
var argsToSet = []
var multipleArrayFlag = i > 0
for (var ii = i + 1; ii < args.length; ii++) {
if (/^-/.test(args[ii]) && !negative.test(args[ii])) {
if (ii === start) {
setArg(key, defaultForType('array'))
}
multipleArrayFlag = true
break
}
i = ii
argsToSet.push(args[ii])
}
if (multipleArrayFlag) {
setArg(key, argsToSet.map(function (arg) {
return processValue(key, arg)
}))
} else {
argsToSet.forEach(function (arg) {
setArg(key, arg)
})
}
return i
}
function setArg (key, val) {
unsetDefaulted(key)
if (/-/.test(key) && configuration['camel-case-expansion']) {
addNewAlias(key, camelCase(key))
}
var value = processValue(key, val)
var splitKey = key.split('.')
setKey(argv, splitKey, value)
// handle populating aliases of the full key
if (flags.aliases[key]) {
flags.aliases[key].forEach(function (x) {
x = x.split('.')
setKey(argv, x, value)
})
}
// handle populating aliases of the first element of the dot-notation key
if (splitKey.length > 1 && configuration['dot-notation']) {
;(flags.aliases[splitKey[0]] || []).forEach(function (x) {
x = x.split('.')
// expand alias with nested objects in key
var a = [].concat(splitKey)
a.shift() // nuke the old key.
x = x.concat(a)
setKey(argv, x, value)
})
}
// Set normalize getter and setter when key is in 'normalize' but isn't an array
if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
var keys = [key].concat(flags.aliases[key] || [])
keys.forEach(function (key) {
argv.__defineSetter__(key, function (v) {
val = path.normalize(v)
})
argv.__defineGetter__(key, function () {
return typeof val === 'string' ? path.normalize(val) : val
})
})
}
}
function addNewAlias (key, alias) {
if (!(flags.aliases[key] && flags.aliases[key].length)) {
flags.aliases[key] = [alias]
newAliases[alias] = true
}
if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
addNewAlias(alias, key)
}
}
function processValue (key, val) {
// handle parsing boolean arguments --foo=true --bar false.
if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
if (typeof val === 'string') val = val === 'true'
}
var value = maybeCoerceNumber(key, val)
// increment a count given as arg (either no value or value parsed as boolean)
if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
value = increment
}
// Set normalized value when key is in 'normalize' and in 'arrays'
if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
if (Array.isArray(val)) value = val.map(path.normalize)
else value = path.normalize(val)
}
return value
}
function maybeCoerceNumber (key, value) {
if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.coercions)) {
const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && (
Number.isSafeInteger(Math.floor(value))
)
if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) value = Number(value)
}
return value
}
// set args from config.json file, this should be
// applied last so that defaults can be applied.
function setConfig (argv) {
var configLookup = {}
// expand defaults/aliases, in-case any happen to reference
// the config.json file.
applyDefaultsAndAliases(configLookup, flags.aliases, defaults)
Object.keys(flags.configs).forEach(function (configKey) {
var configPath = argv[configKey] || configLookup[configKey]
if (configPath) {
try {
var config = null
var resolvedConfigPath = path.resolve(process.cwd(), configPath)
if (typeof flags.configs[configKey] === 'function') {
try {
config = flags.configs[configKey](resolvedConfigPath)
} catch (e) {
config = e
}
if (config instanceof Error) {
error = config
return
}
} else {
config = require(resolvedConfigPath)
}
setConfigObject(config)
} catch (ex) {
if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath))
}
}
})
}
// set args from config object.
// it recursively checks nested objects.
function setConfigObject (config, prev) {
Object.keys(config).forEach(function (key) {
var value = config[key]
var fullKey = prev ? prev + '.' + key : key
// if the value is an inner object and we have dot-notation
// enabled, treat inner objects in config the same as
// heavily nested dot notations (foo.bar.apple).
if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
// if the value is an object but not an array, check nested object
setConfigObject(value, fullKey)
} else {
// setting arguments via CLI takes precedence over
// values within the config file.
if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey]) || (flags.arrays[fullKey] && configuration['combine-arrays'])) {
setArg(fullKey, value)
}
}
})
}
// set all config objects passed in opts
function setConfigObjects () {
if (typeof configObjects === 'undefined') return
configObjects.forEach(function (configObject) {
setConfigObject(configObject)
})
}
function applyEnvVars (argv, configOnly) {
if (typeof envPrefix === 'undefined') return
var prefix = typeof envPrefix === 'string' ? envPrefix : ''
Object.keys(process.env).forEach(function (envVar) {
if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
// get array of nested keys and convert them to camel case
var keys = envVar.split('__').map(function (key, i) {
if (i === 0) {
key = key.substring(prefix.length)
}
return camelCase(key)
})
if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && (!hasKey(argv, keys) || flags.defaulted[keys.join('.')])) {
setArg(keys.join('.'), process.env[envVar])
}
}
})
}
function applyCoercions (argv) {
var coerce
var applied = {}
Object.keys(argv).forEach(function (key) {
if (!applied.hasOwnProperty(key)) { // If we haven't already coerced this option via one of its aliases
coerce = checkAllAliases(key, flags.coercions)
if (typeof coerce === 'function') {
try {
var value = coerce(argv[key])
;([].concat(flags.aliases[key] || [], key)).forEach(ali => {
applied[ali] = argv[ali] = value
})
} catch (err) {
error = err
}
}
}
})
}
function applyDefaultsAndAliases (obj, aliases, defaults) {
Object.keys(defaults).forEach(function (key) {
if (!hasKey(obj, key.split('.'))) {
setKey(obj, key.split('.'), defaults[key])
;(aliases[key] || []).forEach(function (x) {
if (hasKey(obj, x.split('.'))) return
setKey(obj, x.split('.'), defaults[key])
})
}
})
}
function hasKey (obj, keys) {
var o = obj
if (!configuration['dot-notation']) keys = [keys.join('.')]
keys.slice(0, -1).forEach(function (key) {
o = (o[key] || {})
})
var key = keys[keys.length - 1]
if (typeof o !== 'object') return false
else return key in o
}
function setKey (obj, keys, value) {
var o = obj
if (!configuration['dot-notation']) keys = [keys.join('.')]
keys.slice(0, -1).forEach(function (key, index) {
if (typeof o === 'object' && o[key] === undefined) {
o[key] = {}
}
if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
// ensure that o[key] is an array, and that the last item is an empty object.
if (Array.isArray(o[key])) {
o[key].push({})
} else {
o[key] = [o[key], {}]
}
// we want to update the empty object at the end of the o[key] array, so set o to that object
o = o[key][o[key].length - 1]
} else {
o = o[key]
}
})
var key = keys[keys.length - 1]
var isTypeArray = checkAllAliases(keys.join('.'), flags.arrays)
var isValueArray = Array.isArray(value)
var duplicate = configuration['duplicate-arguments-array']
if (value === increment) {
o[key] = increment(o[key])
} else if (Array.isArray(o[key])) {
if (duplicate && isTypeArray && isValueArray) {
o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : [o[key]].concat([value])
} else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
o[key] = value
} else {
o[key] = o[key].concat([value])
}
} else if (o[key] === undefined && isTypeArray) {
o[key] = isValueArray ? value : [value]
} else if (duplicate && !(o[key] === undefined || checkAllAliases(key, flags.bools) || checkAllAliases(keys.join('.'), flags.bools) || checkAllAliases(key, flags.counts))) {
o[key] = [ o[key], value ]
} else {
o[key] = value
}
}
// extend the aliases list with inferred aliases.
function extendAliases () {
Array.prototype.slice.call(arguments).forEach(function (obj) {
Object.keys(obj || {}).forEach(function (key) {
// short-circuit if we've already added a key
// to the aliases array, for example it might
// exist in both 'opts.default' and 'opts.key'.
if (flags.aliases[key]) return
flags.aliases[key] = [].concat(aliases[key] || [])
// For "--option-name", also set argv.optionName
flags.aliases[key].concat(key).forEach(function (x) {
if (/-/.test(x) && configuration['camel-case-expansion']) {
var c = camelCase(x)
if (c !== key && flags.aliases[key].indexOf(c) === -1) {
flags.aliases[key].push(c)
newAliases[c] = true
}
}
})
flags.aliases[key].forEach(function (x) {
flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
return x !== y
}))
})
})
})
}
// check if a flag is set for any of a key's aliases.
function checkAllAliases (key, flag) {
var isSet = false
var toCheck = [].concat(flags.aliases[key] || [], key)
toCheck.forEach(function (key) {
if (flag[key]) isSet = flag[key]
})
return isSet
}
function setDefaulted (key) {
[].concat(flags.aliases[key] || [], key).forEach(function (k) {
flags.defaulted[k] = true
})
}
function unsetDefaulted (key) {
[].concat(flags.aliases[key] || [], key).forEach(function (k) {
delete flags.defaulted[k]
})
}
// return a default value, given the type of a flag.,
// e.g., key of type 'string' will default to '', rather than 'true'.
function defaultForType (type) {
var def = {
boolean: true,
string: '',
number: undefined,
array: []
}
return def[type]
}
// given a flag, enforce a default type.
function guessType (key, flags) {
var type = 'boolean'
if (checkAllAliases(key, flags.strings)) type = 'string'
else if (checkAllAliases(key, flags.numbers)) type = 'number'
else if (checkAllAliases(key, flags.arrays)) type = 'array'
return type
}
function isNumber (x) {
if (typeof x === 'number') return true
if (/^0x[0-9a-f]+$/i.test(x)) return true
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)
}
function isUndefined (num) {
return num === undefined
}
return {
argv: argv,
error: error,
aliases: flags.aliases,
newAliases: newAliases,
configuration: configuration
}
}
// if any aliases reference each other, we should
// merge them together.
function combineAliases (aliases) {
var aliasArrays = []
var change = true
var combined = {}
// turn alias lookup hash {key: ['alias1', 'alias2']} into
// a simple array ['key', 'alias1', 'alias2']
Object.keys(aliases).forEach(function (key) {
aliasArrays.push(
[].concat(aliases[key], key)
)
})
// combine arrays until zero changes are
// made in an iteration.
while (change) {
change = false
for (var i = 0; i < aliasArrays.length; i++) {
for (var ii = i + 1; ii < aliasArrays.length; ii++) {
var intersect = aliasArrays[i].filter(function (v) {
return aliasArrays[ii].indexOf(v) !== -1
})
if (intersect.length) {
aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii])
aliasArrays.splice(ii, 1)
change = true
break
}
}
}
}
// map arrays back to the hash-lookup (de-dupe while
// we're at it).
aliasArrays.forEach(function (aliasArray) {
aliasArray = aliasArray.filter(function (v, i, self) {
return self.indexOf(v) === i
})
combined[aliasArray.pop()] = aliasArray
})
return combined
}
function assign (defaults, configuration) {
var o = {}
configuration = configuration || {}
Object.keys(defaults).forEach(function (k) {
o[k] = defaults[k]
})
Object.keys(configuration).forEach(function (k) {
o[k] = configuration[k]
})
return o
}
// this function should only be called when a count is given as an arg
// it is NOT called to set a default value
// thus we can start the count at 1 instead of 0
function increment (orig) {
return orig !== undefined ? orig + 1 : 1
}
function Parser (args, opts) {
var result = parse(args.slice(), opts)
return result.argv
}
// parse arguments and return detailed
// meta information, aliases, etc.
Parser.detailed = function (args, opts) {
return parse(args.slice(), opts)
}
module.exports = Parser
@@ -0,0 +1,40 @@
// take an un-split argv string and tokenize it.
module.exports = function (argString) {
if (Array.isArray(argString)) return argString
argString = argString.trim()
var i = 0
var prevC = null
var c = null
var opening = null
var args = []
for (var ii = 0; ii < argString.length; ii++) {
prevC = c
c = argString.charAt(ii)
// split on spaces unless we're in quotes.
if (c === ' ' && !opening) {
if (!(prevC === ' ')) {
i++
}
continue
}
// don't split the string if we're in matching
// opening or closing single and double quotes.
if (c === opening) {
opening = null
continue
} else if ((c === "'" || c === '"') && !opening) {
opening = c
continue
}
if (!args[i]) args[i] = ''
args[i] += c
}
return args
}
+107
View File
@@ -0,0 +1,107 @@
{
"_args": [
[
"yargs-parser@^8.1.0",
"/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs"
]
],
"_from": "yargs-parser@>=8.1.0 <9.0.0",
"_id": "yargs-parser@8.1.0",
"_inCache": true,
"_installable": true,
"_location": "/ts2fable/yargs-parser",
"_nodeVersion": "9.3.0",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/yargs-parser-8.1.0.tgz_1513750813446_0.41336237522773445"
},
"_npmUser": {
"email": "ben@npmjs.com",
"name": "bcoe"
},
"_npmVersion": "5.5.1",
"_phantomChildren": {},
"_requested": {
"name": "yargs-parser",
"raw": "yargs-parser@^8.1.0",
"rawSpec": "^8.1.0",
"scope": null,
"spec": ">=8.1.0 <9.0.0",
"type": "range"
},
"_requiredBy": [
"/ts2fable/yargs"
],
"_resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-8.1.0.tgz",
"_shasum": "f1376a33b6629a5d063782944da732631e966950",
"_shrinkwrap": null,
"_spec": "yargs-parser@^8.1.0",
"_where": "/home/ppinto/Dropbox/bts/spark/src/web/ui/node_modules/ts2fable/node_modules/yargs",
"author": {
"email": "ben@npmjs.com",
"name": "Ben Coe"
},
"bugs": {
"url": "https://github.com/yargs/yargs-parser/issues"
},
"dependencies": {
"camelcase": "^4.1.0"
},
"description": "the mighty option parser used by yargs",
"devDependencies": {
"chai": "^3.5.0",
"coveralls": "^2.11.12",
"mocha": "^3.0.1",
"nyc": "^11.4.1",
"standard": "^10.0.2",
"standard-version": "^4.3.0-candidate.0"
},
"directories": {},
"dist": {
"integrity": "sha512-yP+6QqN8BmrgW2ggLtTbdrOyBNSI7zBa4IykmiV5R1wl1JWNxQvWhMfMdmzIYtKU7oP3OOInY/tl2ov3BDjnJQ==",
"shasum": "f1376a33b6629a5d063782944da732631e966950",
"tarball": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-8.1.0.tgz"
},
"files": [
"index.js",
"lib"
],
"gitHead": "29b02489b2111be89de94bf24f36e8ec8a6ba9e2",
"homepage": "https://github.com/yargs/yargs-parser#readme",
"keywords": [
"args",
"argument",
"argument",
"cli",
"command",
"option",
"parser",
"parsing",
"yargs"
],
"license": "ISC",
"main": "index.js",
"maintainers": [
{
"name": "nexdrew",
"email": "andrewbgoode@gmail.com"
},
{
"name": "bcoe",
"email": "ben@npmjs.com"
}
],
"name": "yargs-parser",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"url": "git+ssh://git@github.com/yargs/yargs-parser.git"
},
"scripts": {
"coverage": "nyc report --reporter=text-lcov | coveralls",
"pretest": "standard",
"release": "standard-version",
"test": "nyc mocha test/*.js"
},
"version": "8.1.0"
}
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
Copyright 2010 James Halliday (mail@substack.net)
Modified work Copyright 2014 Contributors (ben@npmjs.com)
This project is free software released under the MIT/X11 license:
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.
+107
View File
@@ -0,0 +1,107 @@
# Yargs
[![Build Status][travis-image]][travis-url]
[![Coverage Status][coveralls-image]][coveralls-url]
[![NPM version][npm-image]][npm-url]
[![Windows Tests][windows-image]][windows-url]
[![js-standard-style][standard-image]][standard-url]
[![Conventional Commits][conventional-commits-image]][conventional-commits-url]
[![Slack][slack-image]][slack-url]
_Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com)_.
> Yargs be a node.js library fer hearties tryin' ter parse optstrings.
<img width="250" src="/yargs-logo.png">
Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you:
* commands and (grouped) options (`my-program.js serve --port=5000`).
* a dynamically generated help menu based on your arguments.
> <img width="400" src="/screen.png">
* bash-completion shortcuts for commands and options.
* and [tons more](/docs/api.md).
## Installation
```bash
npm i yargs --save
```
## Simple Example
````javascript
#!/usr/bin/env node
const argv = require('yargs').argv
if (argv.ships > 3 && argv.distance < 53.5) {
console.log('Plunder more riffiwobbles!')
} else {
console.log('Retreat from the xupptumblers!')
}
````
```bash
$ ./plunder.js --ships=4 --distance=22
Plunder more riffiwobbles!
$ ./plunder.js --ships 12 --distance 98.7
Retreat from the xupptumblers!
```
## Complex Example
```js
#!/usr/bin/env node
require('yargs') // eslint-disable-line
.command('serve [port]', 'start the server', (yargs) => {
yargs
.positional('port', {
describe: 'port to bind on',
default: 5000
})
}, (argv) => {
if (argv.verbose) console.info(`start server on :${argv.port}`)
serve(argv.port)
})
.option('verbose', {
alias: 'v',
default: false
})
.argv
```
Run the example above with `--help` to see the help for the application.
## Table of Contents
* [Yargs' API](/docs/api.md)
* [Examples](/docs/examples.md)
* [Parsing Tricks](/docs/tricks.md)
* [Stop the Parser](/docs/tricks.md#stop)
* [Negating Boolean Arguments](/docs/tricks.md#negate)
* [Numbers](/docs/tricks.md#numbers)
* [Arrays](/docs/tricks.md#arrays)
* [Objects](/docs/tricks.md#objects)
* [Advanced Topics](/docs/advanced.md)
* [Composing Your App Using Commands](/docs/advanced.md#commands)
* [Building Configurable CLI Apps](/docs/advanced.md#configuration)
* [Customizing Yargs' Parser](/docs/advanced.md#customizing)
* [Contributing](/contributing.md)
[travis-url]: https://travis-ci.org/yargs/yargs
[travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg
[coveralls-url]: https://coveralls.io/github/yargs/yargs
[coveralls-image]: https://img.shields.io/coveralls/yargs/yargs.svg
[npm-url]: https://www.npmjs.com/package/yargs
[npm-image]: https://img.shields.io/npm/v/yargs.svg
[windows-url]: https://ci.appveyor.com/project/bcoe/yargs-ljwvf
[windows-image]: https://img.shields.io/appveyor/ci/bcoe/yargs-ljwvf/master.svg?label=Windows%20Tests
[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
[standard-url]: http://standardjs.com/
[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg
[conventional-commits-url]: https://conventionalcommits.org/
[slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg
[slack-url]: http://devtoolscommunity.herokuapp.com
+28
View File
@@ -0,0 +1,28 @@
###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
#
_yargs_completions()
{
local cur_word args type_list
cur_word="${COMP_WORDS[COMP_CWORD]}"
args=("${COMP_WORDS[@]}")
# ask yargs to generate completions.
type_list=$({{app_path}} --get-yargs-completions "${args[@]}")
COMPREPLY=( $(compgen -W "${type_list}" -- ${cur_word}) )
# if no match was found, fall back to filename completion
if [ ${#COMPREPLY[@]} -eq 0 ]; then
COMPREPLY=( $(compgen -f -- "${cur_word}" ) )
fi
return 0
}
complete -F _yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
+32
View File
@@ -0,0 +1,32 @@
'use strict'
// classic singleton yargs API, to use yargs
// without running as a singleton do:
// require('yargs/yargs')(process.argv.slice(2))
const yargs = require('./yargs')
Argv(process.argv.slice(2))
module.exports = Argv
function Argv (processArgs, cwd) {
const argv = yargs(processArgs, cwd, require)
singletonify(argv)
return argv
}
/* Hack an instance of Argv with process.argv into Argv
so people can do
require('yargs')(['--beeble=1','-z','zizzle']).argv
to parse a list of args and
require('yargs').argv
to get a parsed version of process.argv.
*/
function singletonify (inst) {
Object.keys(inst).forEach((key) => {
if (key === 'argv') {
Argv.__defineGetter__(key, inst.__lookupGetter__(key))
} else {
Argv[key] = typeof inst[key] === 'function' ? inst[key].bind(inst) : inst[key]
}
})
}
+53
View File
@@ -0,0 +1,53 @@
'use strict'
const fs = require('fs')
const path = require('path')
const YError = require('./yerror')
let previouslyVisitedConfigs = []
function checkForCircularExtends (path) {
if (previouslyVisitedConfigs.indexOf(path) > -1) {
throw new YError(`Circular extended configurations: '${path}'.`)
}
}
function getPathToDefaultConfig (cwd, pathToExtend) {
return path.resolve(cwd, pathToExtend)
}
function applyExtends (config, cwd) {
let defaultConfig = {}
if (config.hasOwnProperty('extends')) {
if (typeof config.extends !== 'string') return defaultConfig
const isPath = /\.json$/.test(config.extends)
let pathToDefault = null
if (!isPath) {
try {
pathToDefault = require.resolve(config.extends)
} catch (err) {
// most likely this simply isn't a module.
}
} else {
pathToDefault = getPathToDefaultConfig(cwd, config.extends)
}
// maybe the module uses key for some other reason,
// err on side of caution.
if (!pathToDefault && !isPath) return config
checkForCircularExtends(pathToDefault)
previouslyVisitedConfigs.push(pathToDefault)
defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends)
delete config.extends
defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault))
}
previouslyVisitedConfigs = []
return Object.assign({}, defaultConfig, config)
}
module.exports = applyExtends
+66
View File
@@ -0,0 +1,66 @@
'use strict'
const command = require('./command')()
const YError = require('./yerror')
const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
module.exports = function argsert (expected, callerArguments, length) {
// TODO: should this eventually raise an exception.
try {
// preface the argument description with "cmd", so
// that we can run it through yargs' command parser.
let position = 0
let parsed = {demanded: [], optional: []}
if (typeof expected === 'object') {
length = callerArguments
callerArguments = expected
} else {
parsed = command.parseCommand(`cmd ${expected}`)
}
const args = [].slice.call(callerArguments)
while (args.length && args[args.length - 1] === undefined) args.pop()
length = length || args.length
if (length < parsed.demanded.length) {
throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`)
}
const totalCommands = parsed.demanded.length + parsed.optional.length
if (length > totalCommands) {
throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`)
}
parsed.demanded.forEach((demanded) => {
const arg = args.shift()
const observedType = guessType(arg)
const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*')
if (matchingTypes.length === 0) argumentTypeError(observedType, demanded.cmd, position, false)
position += 1
})
parsed.optional.forEach((optional) => {
if (args.length === 0) return
const arg = args.shift()
const observedType = guessType(arg)
const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*')
if (matchingTypes.length === 0) argumentTypeError(observedType, optional.cmd, position, true)
position += 1
})
} catch (err) {
console.warn(err.stack)
}
}
function guessType (arg) {
if (Array.isArray(arg)) {
return 'array'
} else if (arg === null) {
return 'null'
}
return typeof arg
}
function argumentTypeError (observedType, allowedTypes, position, optional) {
throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`)
}
+426
View File
@@ -0,0 +1,426 @@
'use strict'
const inspect = require('util').inspect
const path = require('path')
const Parser = require('yargs-parser')
const DEFAULT_MARKER = /(^\*)|(^\$0)/
// handles parsing positional arguments,
// and populating argv with said positional
// arguments.
module.exports = function command (yargs, usage, validation) {
const self = {}
let handlers = {}
let aliasMap = {}
let defaultCommand
self.addHandler = function addHandler (cmd, description, builder, handler, middlewares) {
let aliases = []
handler = handler || (() => {})
middlewares = middlewares || []
if (Array.isArray(cmd)) {
aliases = cmd.slice(1)
cmd = cmd[0]
} else if (typeof cmd === 'object') {
let command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd)
if (cmd.aliases) command = [].concat(command).concat(cmd.aliases)
self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares)
return
}
// allow a module to be provided instead of separate builder and handler
if (typeof builder === 'object' && builder.builder && typeof builder.handler === 'function') {
self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares)
return
}
// parse positionals out of cmd string
const parsedCommand = self.parseCommand(cmd)
// remove positional args from aliases only
aliases = aliases.map(alias => self.parseCommand(alias).cmd)
// check for default and filter out '*''
let isDefault = false
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => {
if (DEFAULT_MARKER.test(c)) {
isDefault = true
return false
}
return true
})
// standardize on $0 for default command.
if (parsedAliases.length === 0 && isDefault) parsedAliases.push('$0')
// shift cmd and aliases after filtering out '*'
if (isDefault) {
parsedCommand.cmd = parsedAliases[0]
aliases = parsedAliases.slice(1)
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd)
}
// populate aliasMap
aliases.forEach((alias) => {
aliasMap[alias] = parsedCommand.cmd
})
if (description !== false) {
usage.command(cmd, description, isDefault, aliases)
}
handlers[parsedCommand.cmd] = {
original: cmd,
description: description,
handler,
builder: builder || {},
middlewares: middlewares || [],
demanded: parsedCommand.demanded,
optional: parsedCommand.optional
}
if (isDefault) defaultCommand = handlers[parsedCommand.cmd]
}
self.addDirectory = function addDirectory (dir, context, req, callerFile, opts) {
opts = opts || {}
// disable recursion to support nested directories of subcommands
if (typeof opts.recurse !== 'boolean') opts.recurse = false
// exclude 'json', 'coffee' from require-directory defaults
if (!Array.isArray(opts.extensions)) opts.extensions = ['js']
// allow consumer to define their own visitor function
const parentVisit = typeof opts.visit === 'function' ? opts.visit : o => o
// call addHandler via visitor function
opts.visit = function visit (obj, joined, filename) {
const visited = parentVisit(obj, joined, filename)
// allow consumer to skip modules with their own visitor
if (visited) {
// check for cyclic reference
// each command file path should only be seen once per execution
if (~context.files.indexOf(joined)) return visited
// keep track of visited files in context.files
context.files.push(joined)
self.addHandler(visited)
}
return visited
}
require('require-directory')({ require: req, filename: callerFile }, dir, opts)
}
// lookup module object from require()d command and derive name
// if module was not require()d and no name given, throw error
function moduleName (obj) {
const mod = require('which-module')(obj)
if (!mod) throw new Error(`No command name given for module: ${inspect(obj)}`)
return commandFromFilename(mod.filename)
}
// derive command name from filename
function commandFromFilename (filename) {
return path.basename(filename, path.extname(filename))
}
function extractDesc (obj) {
for (let keys = ['describe', 'description', 'desc'], i = 0, l = keys.length, test; i < l; i++) {
test = obj[keys[i]]
if (typeof test === 'string' || typeof test === 'boolean') return test
}
return false
}
self.parseCommand = function parseCommand (cmd) {
const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ')
const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/)
const bregex = /\.*[\][<>]/g
const parsedCommand = {
cmd: (splitCommand.shift()).replace(bregex, ''),
demanded: [],
optional: []
}
splitCommand.forEach((cmd, i) => {
let variadic = false
cmd = cmd.replace(/\s/g, '')
if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) variadic = true
if (/^\[/.test(cmd)) {
parsedCommand.optional.push({
cmd: cmd.replace(bregex, '').split('|'),
variadic
})
} else {
parsedCommand.demanded.push({
cmd: cmd.replace(bregex, '').split('|'),
variadic
})
}
})
return parsedCommand
}
self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap))
self.getCommandHandlers = () => handlers
self.hasDefaultCommand = () => !!defaultCommand
self.runCommand = function runCommand (command, yargs, parsed, commandIndex) {
let aliases = parsed.aliases
const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand
const currentContext = yargs.getContext()
let numFiles = currentContext.files.length
const parentCommands = currentContext.commands.slice()
// what does yargs look like after the buidler is run?
let innerArgv = parsed.argv
let innerYargs = null
let positionalMap = {}
if (command) {
currentContext.commands.push(command)
currentContext.fullCommands.push(commandHandler.original)
}
if (typeof commandHandler.builder === 'function') {
// a function can be provided, which builds
// up a yargs chain and possibly returns it.
innerYargs = commandHandler.builder(yargs.reset(parsed.aliases))
// if the builder function did not yet parse argv with reset yargs
// and did not explicitly set a usage() string, then apply the
// original command string as usage() for consistent behavior with
// options object below.
if (yargs.parsed === false) {
if (shouldUpdateUsage(yargs)) {
yargs.getUsageInstance().usage(
usageFromParentCommandsCommandHandler(parentCommands, commandHandler),
commandHandler.description
)
}
innerArgv = innerYargs ? innerYargs._parseArgs(null, null, true, commandIndex) : yargs._parseArgs(null, null, true, commandIndex)
} else {
innerArgv = yargs.parsed.argv
}
if (innerYargs && yargs.parsed === false) aliases = innerYargs.parsed.aliases
else aliases = yargs.parsed.aliases
} else if (typeof commandHandler.builder === 'object') {
// as a short hand, an object can instead be provided, specifying
// the options that a command takes.
innerYargs = yargs.reset(parsed.aliases)
if (shouldUpdateUsage(innerYargs)) {
innerYargs.getUsageInstance().usage(
usageFromParentCommandsCommandHandler(parentCommands, commandHandler),
commandHandler.description
)
}
Object.keys(commandHandler.builder).forEach((key) => {
innerYargs.option(key, commandHandler.builder[key])
})
innerArgv = innerYargs._parseArgs(null, null, true, commandIndex)
aliases = innerYargs.parsed.aliases
}
if (!yargs._hasOutput()) {
positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs)
}
// we apply validation post-hoc, so that custom
// checks get passed populated positional arguments.
if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error)
if (commandHandler.handler && !yargs._hasOutput()) {
yargs._setHasOutput()
if (commandHandler.middlewares.length > 0) {
const middlewareArgs = commandHandler.middlewares.reduce(function (initialObj, middleware) {
return Object.assign(initialObj, middleware(innerArgv))
}, {})
Object.assign(innerArgv, middlewareArgs)
}
const handlerResult = commandHandler.handler(innerArgv)
if (handlerResult && typeof handlerResult.then === 'function') {
handlerResult.then(
null,
(error) => yargs.getUsageInstance().fail(null, error)
)
}
}
if (command) {
currentContext.commands.pop()
currentContext.fullCommands.pop()
}
numFiles = currentContext.files.length - numFiles
if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles)
return innerArgv
}
function shouldUpdateUsage (yargs) {
return !yargs.getUsageInstance().getUsageDisabled() &&
yargs.getUsageInstance().getUsage().length === 0
}
function usageFromParentCommandsCommandHandler (parentCommands, commandHandler) {
const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() : commandHandler.original
const pc = parentCommands.filter((c) => { return !DEFAULT_MARKER.test(c) })
pc.push(c)
return `$0 ${pc.join(' ')}`
}
self.runDefaultBuilderOn = function (yargs) {
if (shouldUpdateUsage(yargs)) {
// build the root-level command string from the default string.
const commandString = DEFAULT_MARKER.test(defaultCommand.original)
? defaultCommand.original : defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ')
yargs.getUsageInstance().usage(
commandString,
defaultCommand.description
)
}
const builder = defaultCommand.builder
if (typeof builder === 'function') {
builder(yargs)
} else {
Object.keys(builder).forEach((key) => {
yargs.option(key, builder[key])
})
}
}
// transcribe all positional arguments "command <foo> <bar> [apple]"
// onto argv.
function populatePositionals (commandHandler, argv, context, yargs) {
argv._ = argv._.slice(context.commands.length) // nuke the current commands
const demanded = commandHandler.demanded.slice(0)
const optional = commandHandler.optional.slice(0)
const positionalMap = {}
validation.positionalCount(demanded.length, argv._.length)
while (demanded.length) {
const demand = demanded.shift()
populatePositional(demand, argv, positionalMap)
}
while (optional.length) {
const maybe = optional.shift()
populatePositional(maybe, argv, positionalMap)
}
argv._ = context.commands.concat(argv._)
postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original))
return positionalMap
}
function populatePositional (positional, argv, positionalMap, parseOptions) {
const cmd = positional.cmd[0]
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String)
} else {
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())]
}
}
// we run yargs-parser against the positional arguments
// applying the same parsing logic used for flags.
function postProcessPositionals (argv, positionalMap, parseOptions) {
// combine the parsing hints we've inferred from the command
// string with explicitly configured parsing hints.
const options = Object.assign({}, yargs.getOptions())
options.default = Object.assign(parseOptions.default, options.default)
options.alias = Object.assign(parseOptions.alias, options.alias)
options.array = options.array.concat(parseOptions.array)
const unparsed = []
Object.keys(positionalMap).forEach((key) => {
positionalMap[key].map((value) => {
unparsed.push(`--${key}`)
unparsed.push(value)
})
})
// short-circuit parse.
if (!unparsed.length) return
const parsed = Parser.detailed(unparsed, options)
if (parsed.error) {
yargs.getUsageInstance().fail(parsed.error.message, parsed.error)
} else {
// only copy over positional keys (don't overwrite
// flag arguments that were already parsed).
const positionalKeys = Object.keys(positionalMap)
Object.keys(positionalMap).forEach((key) => {
[].push.apply(positionalKeys, parsed.aliases[key])
})
Object.keys(parsed.argv).forEach((key) => {
if (positionalKeys.indexOf(key) !== -1) {
argv[key] = parsed.argv[key]
}
})
}
}
self.cmdToParseOptions = function (cmdString) {
const parseOptions = {
array: [],
default: {},
alias: {},
demand: {}
}
const parsed = self.parseCommand(cmdString)
parsed.demanded.forEach((d) => {
const cmds = d.cmd.slice(0)
const cmd = cmds.shift()
if (d.variadic) {
parseOptions.array.push(cmd)
parseOptions.default[cmd] = []
}
cmds.forEach((c) => {
parseOptions.alias[cmd] = c
})
parseOptions.demand[cmd] = true
})
parsed.optional.forEach((o) => {
const cmds = o.cmd.slice(0)
const cmd = cmds.shift()
if (o.variadic) {
parseOptions.array.push(cmd)
parseOptions.default[cmd] = []
}
cmds.forEach((c) => {
parseOptions.alias[cmd] = c
})
})
return parseOptions
}
self.reset = () => {
handlers = {}
aliasMap = {}
defaultCommand = undefined
return self
}
// used by yargs.parse() to freeze
// the state of commands such that
// we can apply .parse() multiple times
// with the same yargs instance.
let frozen
self.freeze = () => {
frozen = {}
frozen.handlers = handlers
frozen.aliasMap = aliasMap
frozen.defaultCommand = defaultCommand
}
self.unfreeze = () => {
handlers = frozen.handlers
aliasMap = frozen.aliasMap
defaultCommand = frozen.defaultCommand
frozen = undefined
}
return self
}
+105
View File
@@ -0,0 +1,105 @@
'use strict'
const fs = require('fs')
const path = require('path')
// add bash completions to your
// yargs-powered applications.
module.exports = function completion (yargs, usage, command) {
const self = {
completionKey: 'get-yargs-completions'
}
// get a list of completion commands.
// 'args' is the array of strings from the line to be completed
self.getCompletion = function getCompletion (args, done) {
const completions = []
const current = args.length ? args[args.length - 1] : ''
const argv = yargs.parse(args, true)
const aliases = yargs.parsed.aliases
// a custom completion function can be provided
// to completion().
if (completionFunction) {
if (completionFunction.length < 3) {
const result = completionFunction(current, argv)
// promise based completion function.
if (typeof result.then === 'function') {
return result.then((list) => {
process.nextTick(() => { done(list) })
}).catch((err) => {
process.nextTick(() => { throw err })
})
}
// synchronous completion function.
return done(result)
} else {
// asynchronous completion function
return completionFunction(current, argv, (completions) => {
done(completions)
})
}
}
const handlers = command.getCommandHandlers()
for (let i = 0, ii = args.length; i < ii; ++i) {
if (handlers[args[i]] && handlers[args[i]].builder) {
const builder = handlers[args[i]].builder
if (typeof builder === 'function') {
const y = yargs.reset()
builder(y)
return y.argv
}
}
}
if (!current.match(/^-/)) {
usage.getCommands().forEach((usageCommand) => {
const commandName = command.parseCommand(usageCommand[0]).cmd
if (args.indexOf(commandName) === -1) {
completions.push(commandName)
}
})
}
if (current.match(/^-/)) {
Object.keys(yargs.getOptions().key).forEach((key) => {
// If the key and its aliases aren't in 'args', add the key to 'completions'
const keyAndAliases = [key].concat(aliases[key] || [])
const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1)
if (notInArgs) {
completions.push(`--${key}`)
}
})
}
done(completions)
}
// generate the completion script to add to your .bashrc.
self.generateCompletionScript = function generateCompletionScript ($0, cmd) {
let script = fs.readFileSync(
path.resolve(__dirname, '../completion.sh.hbs'),
'utf-8'
)
const name = path.basename($0)
// add ./to applications not yet installed as bin.
if ($0.match(/\.js$/)) $0 = `./${$0}`
script = script.replace(/{{app_name}}/g, name)
script = script.replace(/{{completion_command}}/g, cmd)
return script.replace(/{{app_path}}/g, $0)
}
// register a function to perform your own custom
// completions., this function can be either
// synchrnous or asynchronous.
let completionFunction = null
self.registerFunction = (fn) => {
completionFunction = fn
}
return self
}
+47
View File
@@ -0,0 +1,47 @@
/*
Copyright (c) 2011 Andrei Mackenzie
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.
*/
// levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed.
// gist, which can be found here: https://gist.github.com/andrei-m/982927
'use strict'
// Compute the edit distance between the two given strings
module.exports = function levenshtein (a, b) {
if (a.length === 0) return b.length
if (b.length === 0) return a.length
const matrix = []
// increment along the first column of each row
let i
for (i = 0; i <= b.length; i++) {
matrix[i] = [i]
}
// increment each column in the first row
let j
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j
}
// Fill in the rest of the matrix
for (i = 1; i <= b.length; i++) {
for (j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1]
} else {
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
Math.min(matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1)) // deletion
}
}
}
return matrix[b.length][a.length]
}
+11
View File
@@ -0,0 +1,11 @@
'use strict'
module.exports = function objFilter (original, filter) {
const obj = {}
filter = filter || ((k, v) => true)
Object.keys(original || {}).forEach((key) => {
if (filter(key, original[key])) {
obj[key] = original[key]
}
})
return obj
}
+524
View File
@@ -0,0 +1,524 @@
'use strict'
// this file handles outputting usage instructions,
// failures, etc. keeps logging in one place.
const stringWidth = require('string-width')
const objFilter = require('./obj-filter')
const path = require('path')
const setBlocking = require('set-blocking')
const YError = require('./yerror')
module.exports = function usage (yargs, y18n) {
const __ = y18n.__
const self = {}
// methods for ouputting/building failure message.
const fails = []
self.failFn = function failFn (f) {
fails.push(f)
}
let failMessage = null
let showHelpOnFail = true
self.showHelpOnFail = function showHelpOnFailFn (enabled, message) {
if (typeof enabled === 'string') {
message = enabled
enabled = true
} else if (typeof enabled === 'undefined') {
enabled = true
}
failMessage = message
showHelpOnFail = enabled
return self
}
let failureOutput = false
self.fail = function fail (msg, err) {
const logger = yargs._getLoggerInstance()
if (fails.length) {
for (let i = fails.length - 1; i >= 0; --i) {
fails[i](msg, err, self)
}
} else {
if (yargs.getExitProcess()) setBlocking(true)
// don't output failure message more than once
if (!failureOutput) {
failureOutput = true
if (showHelpOnFail) yargs.showHelp('error')
if (msg || err) logger.error(msg || err)
if (failMessage) {
if (msg || err) logger.error('')
logger.error(failMessage)
}
}
err = err || new YError(msg)
if (yargs.getExitProcess()) {
return yargs.exit(1)
} else if (yargs._hasParseCallback()) {
return yargs.exit(1, err)
} else {
throw err
}
}
}
// methods for ouputting/building help (usage) message.
let usages = []
let usageDisabled = false
self.usage = (msg, description) => {
if (msg === null) {
usageDisabled = true
usages = []
return
}
usageDisabled = false
usages.push([msg, description || ''])
return self
}
self.getUsage = () => {
return usages
}
self.getUsageDisabled = () => {
return usageDisabled
}
self.getPositionalGroupName = () => {
return __('Positionals:')
}
let examples = []
self.example = (cmd, description) => {
examples.push([cmd, description || ''])
}
let commands = []
self.command = function command (cmd, description, isDefault, aliases) {
// the last default wins, so cancel out any previously set default
if (isDefault) {
commands = commands.map((cmdArray) => {
cmdArray[2] = false
return cmdArray
})
}
commands.push([cmd, description || '', isDefault, aliases])
}
self.getCommands = () => commands
let descriptions = {}
self.describe = function describe (key, desc) {
if (typeof key === 'object') {
Object.keys(key).forEach((k) => {
self.describe(k, key[k])
})
} else {
descriptions[key] = desc
}
}
self.getDescriptions = () => descriptions
let epilog
self.epilog = (msg) => {
epilog = msg
}
let wrapSet = false
let wrap
self.wrap = (cols) => {
wrapSet = true
wrap = cols
}
function getWrap () {
if (!wrapSet) {
wrap = windowWidth()
wrapSet = true
}
return wrap
}
const deferY18nLookupPrefix = '__yargsString__:'
self.deferY18nLookup = str => deferY18nLookupPrefix + str
const defaultGroup = 'Options:'
self.help = function help () {
normalizeAliases()
// handle old demanded API
const base$0 = path.basename(yargs.$0)
const demandedOptions = yargs.getDemandedOptions()
const demandedCommands = yargs.getDemandedCommands()
const groups = yargs.getGroups()
const options = yargs.getOptions()
let keys = Object.keys(
Object.keys(descriptions)
.concat(Object.keys(demandedOptions))
.concat(Object.keys(demandedCommands))
.concat(Object.keys(options.default))
.reduce((acc, key) => {
if (key !== '_') acc[key] = true
return acc
}, {})
)
const theWrap = getWrap()
const ui = require('cliui')({
width: theWrap,
wrap: !!theWrap
})
// the usage string.
if (!usageDisabled) {
if (usages.length) {
// user-defined usage.
usages.forEach((usage) => {
ui.div(`${usage[0].replace(/\$0/g, base$0)}`)
if (usage[1]) {
ui.div({text: `${usage[1]}`, padding: [1, 0, 0, 0]})
}
})
ui.div()
} else if (commands.length) {
let u = null
// demonstrate how commands are used.
if (demandedCommands._) {
u = `${base$0} <${__('command')}>\n`
} else {
u = `${base$0} [${__('command')}]\n`
}
ui.div(`${u}`)
}
}
// your application's commands, i.e., non-option
// arguments populated in '_'.
if (commands.length) {
ui.div(__('Commands:'))
const context = yargs.getContext()
const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : ''
commands.forEach((command) => {
const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}` // drop $0 from default commands.
ui.span(
{
text: commandString,
padding: [0, 2, 0, 2],
width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
},
{text: command[1]}
)
const hints = []
if (command[2]) hints.push(`[${__('default:').slice(0, -1)}]`) // TODO hacking around i18n here
if (command[3] && command[3].length) {
hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`)
}
if (hints.length) {
ui.div({text: hints.join(' '), padding: [0, 0, 0, 2], align: 'right'})
} else {
ui.div()
}
})
ui.div()
}
// perform some cleanup on the keys array, making it
// only include top-level keys not their aliases.
const aliasKeys = (Object.keys(options.alias) || [])
.concat(Object.keys(yargs.parsed.newAliases) || [])
keys = keys.filter(key => !yargs.parsed.newAliases[key] && aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1))
// populate 'Options:' group with any keys that have not
// explicitly had a group set.
if (!groups[defaultGroup]) groups[defaultGroup] = []
addUngroupedKeys(keys, options.alias, groups)
// display 'Options:' table along with any custom tables:
Object.keys(groups).forEach((groupName) => {
if (!groups[groupName].length) return
ui.div(__(groupName))
// if we've grouped the key 'f', but 'f' aliases 'foobar',
// normalizedKeys should contain only 'foobar'.
const normalizedKeys = groups[groupName].map((key) => {
if (~aliasKeys.indexOf(key)) return key
for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
if (~(options.alias[aliasKey] || []).indexOf(key)) return aliasKey
}
return key
})
// actually generate the switches string --foo, -f, --bar.
const switches = normalizedKeys.reduce((acc, key) => {
acc[key] = [ key ].concat(options.alias[key] || [])
.map(sw => {
// for the special positional group don't
// add '--' or '-' prefix.
if (groupName === self.getPositionalGroupName()) return sw
else return (sw.length > 1 ? '--' : '-') + sw
})
.join(', ')
return acc
}, {})
normalizedKeys.forEach((key) => {
const kswitch = switches[key]
let desc = descriptions[key] || ''
let type = null
if (~desc.lastIndexOf(deferY18nLookupPrefix)) desc = __(desc.substring(deferY18nLookupPrefix.length))
if (~options.boolean.indexOf(key)) type = `[${__('boolean')}]`
if (~options.count.indexOf(key)) type = `[${__('count')}]`
if (~options.string.indexOf(key)) type = `[${__('string')}]`
if (~options.normalize.indexOf(key)) type = `[${__('string')}]`
if (~options.array.indexOf(key)) type = `[${__('array')}]`
if (~options.number.indexOf(key)) type = `[${__('number')}]`
const extra = [
type,
(key in demandedOptions) ? `[${__('required')}]` : null,
options.choices && options.choices[key] ? `[${__('choices:')} ${
self.stringifiedValues(options.choices[key])}]` : null,
defaultString(options.default[key], options.defaultDescription[key])
].filter(Boolean).join(' ')
ui.span(
{text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4},
desc
)
if (extra) ui.div({text: extra, padding: [0, 0, 0, 2], align: 'right'})
else ui.div()
})
ui.div()
})
// describe some common use-cases for your application.
if (examples.length) {
ui.div(__('Examples:'))
examples.forEach((example) => {
example[0] = example[0].replace(/\$0/g, base$0)
})
examples.forEach((example) => {
if (example[1] === '') {
ui.div(
{
text: example[0],
padding: [0, 2, 0, 2]
}
)
} else {
ui.div(
{
text: example[0],
padding: [0, 2, 0, 2],
width: maxWidth(examples, theWrap) + 4
}, {
text: example[1]
}
)
}
})
ui.div()
}
// the usage string.
if (epilog) {
const e = epilog.replace(/\$0/g, base$0)
ui.div(`${e}\n`)
}
return ui.toString()
}
// return the maximum width of a string
// in the left-hand column of a table.
function maxWidth (table, theWrap, modifier) {
let width = 0
// table might be of the form [leftColumn],
// or {key: leftColumn}
if (!Array.isArray(table)) {
table = Object.keys(table).map(key => [table[key]])
}
table.forEach((v) => {
width = Math.max(
stringWidth(modifier ? `${modifier} ${v[0]}` : v[0]),
width
)
})
// if we've enabled 'wrap' we should limit
// the max-width of the left-column.
if (theWrap) width = Math.min(width, parseInt(theWrap * 0.5, 10))
return width
}
// make sure any options set for aliases,
// are copied to the keys being aliased.
function normalizeAliases () {
// handle old demanded API
const demandedOptions = yargs.getDemandedOptions()
const options = yargs.getOptions()
;(Object.keys(options.alias) || []).forEach((key) => {
options.alias[key].forEach((alias) => {
// copy descriptions.
if (descriptions[alias]) self.describe(key, descriptions[alias])
// copy demanded.
if (alias in demandedOptions) yargs.demandOption(key, demandedOptions[alias])
// type messages.
if (~options.boolean.indexOf(alias)) yargs.boolean(key)
if (~options.count.indexOf(alias)) yargs.count(key)
if (~options.string.indexOf(alias)) yargs.string(key)
if (~options.normalize.indexOf(alias)) yargs.normalize(key)
if (~options.array.indexOf(alias)) yargs.array(key)
if (~options.number.indexOf(alias)) yargs.number(key)
})
})
}
// given a set of keys, place any keys that are
// ungrouped under the 'Options:' grouping.
function addUngroupedKeys (keys, aliases, groups) {
let groupedKeys = []
let toCheck = null
Object.keys(groups).forEach((group) => {
groupedKeys = groupedKeys.concat(groups[group])
})
keys.forEach((key) => {
toCheck = [key].concat(aliases[key])
if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
groups[defaultGroup].push(key)
}
})
return groupedKeys
}
self.showHelp = (level) => {
const logger = yargs._getLoggerInstance()
if (!level) level = 'error'
const emit = typeof level === 'function' ? level : logger[level]
emit(self.help())
}
self.functionDescription = (fn) => {
const description = fn.name ? require('decamelize')(fn.name, '-') : __('generated-value')
return ['(', description, ')'].join('')
}
self.stringifiedValues = function stringifiedValues (values, separator) {
let string = ''
const sep = separator || ', '
const array = [].concat(values)
if (!values || !array.length) return string
array.forEach((value) => {
if (string.length) string += sep
string += JSON.stringify(value)
})
return string
}
// format the default-value-string displayed in
// the right-hand column.
function defaultString (value, defaultDescription) {
let string = `[${__('default:')} `
if (value === undefined && !defaultDescription) return null
if (defaultDescription) {
string += defaultDescription
} else {
switch (typeof value) {
case 'string':
string += `"${value}"`
break
case 'object':
string += JSON.stringify(value)
break
default:
string += value
}
}
return `${string}]`
}
// guess the width of the console window, max-width 80.
function windowWidth () {
const maxWidth = 80
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
return Math.min(maxWidth, process.stdout.columns)
} else {
return maxWidth
}
}
// logic for displaying application version.
let version = null
self.version = (ver) => {
version = ver
}
self.showVersion = () => {
const logger = yargs._getLoggerInstance()
logger.log(version)
}
self.reset = function reset (localLookup) {
// do not reset wrap here
// do not reset fails here
failMessage = null
failureOutput = false
usages = []
usageDisabled = false
epilog = undefined
examples = []
commands = []
descriptions = objFilter(descriptions, (k, v) => !localLookup[k])
return self
}
let frozen
self.freeze = function freeze () {
frozen = {}
frozen.failMessage = failMessage
frozen.failureOutput = failureOutput
frozen.usages = usages
frozen.usageDisabled = usageDisabled
frozen.epilog = epilog
frozen.examples = examples
frozen.commands = commands
frozen.descriptions = descriptions
}
self.unfreeze = function unfreeze () {
failMessage = frozen.failMessage
failureOutput = frozen.failureOutput
usages = frozen.usages
usageDisabled = frozen.usageDisabled
epilog = frozen.epilog
examples = frozen.examples
commands = frozen.commands
descriptions = frozen.descriptions
frozen = undefined
}
return self
}
+375
View File
@@ -0,0 +1,375 @@
'use strict'
const argsert = require('./argsert')
const objFilter = require('./obj-filter')
const specialKeys = ['$0', '--', '_']
// validation-type-stuff, missing params,
// bad implications, custom checks.
module.exports = function validation (yargs, usage, y18n) {
const __ = y18n.__
const __n = y18n.__n
const self = {}
// validate appropriate # of non-option
// arguments were provided, i.e., '_'.
self.nonOptionCount = function nonOptionCount (argv) {
const demandedCommands = yargs.getDemandedCommands()
// don't count currently executing commands
const _s = argv._.length - yargs.getContext().commands.length
if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
if (_s < demandedCommands._.min) {
if (demandedCommands._.minMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.min) : null
)
} else {
usage.fail(
__('Not enough non-option arguments: got %s, need at least %s', _s, demandedCommands._.min)
)
}
} else if (_s > demandedCommands._.max) {
if (demandedCommands._.maxMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.max) : null
)
} else {
usage.fail(
__('Too many non-option arguments: got %s, maximum of %s', _s, demandedCommands._.max)
)
}
}
}
}
// validate the appropriate # of <required>
// positional arguments were provided:
self.positionalCount = function positionalCount (required, observed) {
if (observed < required) {
usage.fail(
__('Not enough non-option arguments: got %s, need at least %s', observed, required)
)
}
}
// make sure that any args that require an
// value (--foo=bar), have a value.
self.missingArgumentValue = function missingArgumentValue (argv) {
const defaultValues = [true, false, '', undefined]
const options = yargs.getOptions()
if (options.requiresArg.length > 0) {
const missingRequiredArgs = []
options.requiresArg.forEach((key) => {
// if the argument is not set in argv no need to check
// whether a right-hand-side has been provided.
if (!argv.hasOwnProperty(key)) return
const value = argv[key]
// if a value is explicitly requested,
// flag argument as missing if it does not
// look like foo=bar was entered.
if (~defaultValues.indexOf(value) ||
(Array.isArray(value) && !value.length)) {
missingRequiredArgs.push(key)
}
})
if (missingRequiredArgs.length > 0) {
usage.fail(__n(
'Missing argument value: %s',
'Missing argument values: %s',
missingRequiredArgs.length,
missingRequiredArgs.join(', ')
))
}
}
}
// make sure all the required arguments are present.
self.requiredArguments = function requiredArguments (argv) {
const demandedOptions = yargs.getDemandedOptions()
let missing = null
Object.keys(demandedOptions).forEach((key) => {
if (!argv.hasOwnProperty(key) || typeof argv[key] === 'undefined') {
missing = missing || {}
missing[key] = demandedOptions[key]
}
})
if (missing) {
const customMsgs = []
Object.keys(missing).forEach((key) => {
const msg = missing[key]
if (msg && customMsgs.indexOf(msg) < 0) {
customMsgs.push(msg)
}
})
const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''
usage.fail(__n(
'Missing required argument: %s',
'Missing required arguments: %s',
Object.keys(missing).length,
Object.keys(missing).join(', ') + customMsg
))
}
}
// check for unknown arguments (strict-mode).
self.unknownArguments = function unknownArguments (argv, aliases, positionalMap) {
const commandKeys = yargs.getCommandInstance().getCommands()
const unknown = []
const currentContext = yargs.getContext()
Object.keys(argv).forEach((key) => {
if (specialKeys.indexOf(key) === -1 &&
!positionalMap.hasOwnProperty(key) &&
!yargs._getParseContext().hasOwnProperty(key) &&
!aliases.hasOwnProperty(key)
) {
unknown.push(key)
}
})
if (commandKeys.length > 0) {
argv._.slice(currentContext.commands.length).forEach((key) => {
if (commandKeys.indexOf(key) === -1) {
unknown.push(key)
}
})
}
if (unknown.length > 0) {
usage.fail(__n(
'Unknown argument: %s',
'Unknown arguments: %s',
unknown.length,
unknown.join(', ')
))
}
}
// validate arguments limited to enumerated choices
self.limitedChoices = function limitedChoices (argv) {
const options = yargs.getOptions()
const invalid = {}
if (!Object.keys(options.choices).length) return
Object.keys(argv).forEach((key) => {
if (specialKeys.indexOf(key) === -1 &&
options.choices.hasOwnProperty(key)) {
[].concat(argv[key]).forEach((value) => {
// TODO case-insensitive configurability
if (options.choices[key].indexOf(value) === -1 &&
value !== undefined) {
invalid[key] = (invalid[key] || []).concat(value)
}
})
}
})
const invalidKeys = Object.keys(invalid)
if (!invalidKeys.length) return
let msg = __('Invalid values:')
invalidKeys.forEach((key) => {
msg += `\n ${__(
'Argument: %s, Given: %s, Choices: %s',
key,
usage.stringifiedValues(invalid[key]),
usage.stringifiedValues(options.choices[key])
)}`
})
usage.fail(msg)
}
// custom checks, added using the `check` option on yargs.
let checks = []
self.check = function check (f, global) {
checks.push({
func: f,
global
})
}
self.customChecks = function customChecks (argv, aliases) {
for (let i = 0, f; (f = checks[i]) !== undefined; i++) {
const func = f.func
let result = null
try {
result = func(argv, aliases)
} catch (err) {
usage.fail(err.message ? err.message : err, err)
continue
}
if (!result) {
usage.fail(__('Argument check failed: %s', func.toString()))
} else if (typeof result === 'string' || result instanceof Error) {
usage.fail(result.toString(), result)
}
}
}
// check implications, argument foo implies => argument bar.
let implied = {}
self.implies = function implies (key, value) {
argsert('<string|object> [array|number|string]', [key, value], arguments.length)
if (typeof key === 'object') {
Object.keys(key).forEach((k) => {
self.implies(k, key[k])
})
} else {
yargs.global(key)
if (!implied[key]) {
implied[key] = []
}
if (Array.isArray(value)) {
value.forEach((i) => self.implies(key, i))
} else {
implied[key].push(value)
}
}
}
self.getImplied = function getImplied () {
return implied
}
self.implications = function implications (argv) {
const implyFail = []
Object.keys(implied).forEach((key) => {
const origKey = key
;(implied[key] || []).forEach((value) => {
let num
let key = origKey
const origValue = value
// convert string '1' to number 1
num = Number(key)
key = isNaN(num) ? key : num
if (typeof key === 'number') {
// check length of argv._
key = argv._.length >= key
} else if (key.match(/^--no-.+/)) {
// check if key doesn't exist
key = key.match(/^--no-(.+)/)[1]
key = !argv[key]
} else {
// check if key exists
key = argv[key]
}
num = Number(value)
value = isNaN(num) ? value : num
if (typeof value === 'number') {
value = argv._.length >= value
} else if (value.match(/^--no-.+/)) {
value = value.match(/^--no-(.+)/)[1]
value = !argv[value]
} else {
value = argv[value]
}
if (key && !value) {
implyFail.push(` ${origKey} -> ${origValue}`)
}
})
})
if (implyFail.length) {
let msg = `${__('Implications failed:')}\n`
implyFail.forEach((value) => {
msg += (value)
})
usage.fail(msg)
}
}
let conflicting = {}
self.conflicts = function conflicts (key, value) {
argsert('<string|object> [array|string]', [key, value], arguments.length)
if (typeof key === 'object') {
Object.keys(key).forEach((k) => {
self.conflicts(k, key[k])
})
} else {
yargs.global(key)
if (!conflicting[key]) {
conflicting[key] = []
}
if (Array.isArray(value)) {
value.forEach((i) => self.conflicts(key, i))
} else {
conflicting[key].push(value)
}
}
}
self.getConflicting = () => conflicting
self.conflicting = function conflictingFn (argv) {
Object.keys(argv).forEach((key) => {
if (conflicting[key]) {
conflicting[key].forEach((value) => {
// we default keys to 'undefined' that have been configured, we should not
// apply conflicting check unless they are a value other than 'undefined'.
if (value && argv[key] !== undefined && argv[value] !== undefined) {
usage.fail(__(`Arguments ${key} and ${value} are mutually exclusive`))
}
})
}
})
}
self.recommendCommands = function recommendCommands (cmd, potentialCommands) {
const distance = require('./levenshtein')
const threshold = 3 // if it takes more than three edits, let's move on.
potentialCommands = potentialCommands.sort((a, b) => b.length - a.length)
let recommended = null
let bestDistance = Infinity
for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
const d = distance(cmd, candidate)
if (d <= threshold && d < bestDistance) {
bestDistance = d
recommended = candidate
}
}
if (recommended) usage.fail(__('Did you mean %s?', recommended))
}
self.reset = function reset (localLookup) {
implied = objFilter(implied, (k, v) => !localLookup[k])
conflicting = objFilter(conflicting, (k, v) => !localLookup[k])
checks = checks.filter(c => c.global)
return self
}
let frozen
self.freeze = function freeze () {
frozen = {}
frozen.implied = implied
frozen.checks = checks
frozen.conflicting = conflicting
}
self.unfreeze = function unfreeze () {
implied = frozen.implied
checks = frozen.checks
conflicting = frozen.conflicting
frozen = undefined
}
return self
}
+11
View File
@@ -0,0 +1,11 @@
'use strict'
function YError (msg) {
this.name = 'YError'
this.message = msg || 'yargs error'
Error.captureStackTrace(this, YError)
}
YError.prototype = Object.create(Error.prototype)
YError.prototype.constructor = YError
module.exports = YError
+39
View File
@@ -0,0 +1,39 @@
{
"Commands:": "Каманды:",
"Options:": "Опцыі:",
"Examples:": "Прыклады:",
"boolean": "булевы тып",
"count": "падлік",
"string": "радковы тып",
"number": "лік",
"array": "масіў",
"required": "неабходна",
"default:": "па змаўчанні:",
"choices:": "магчымасці:",
"aliases:": "аліасы:",
"generated-value": "згенераванае значэнне",
"Not enough non-option arguments: got %s, need at least %s": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s",
"Too many non-option arguments: got %s, maximum of %s": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s",
"Missing argument value: %s": {
"one": "Не хапае значэння аргументу: %s",
"other": "Не хапае значэнняў аргументаў: %s"
},
"Missing required argument: %s": {
"one": "Не хапае неабходнага аргументу: %s",
"other": "Не хапае неабходных аргументаў: %s"
},
"Unknown argument: %s": {
"one": "Невядомы аргумент: %s",
"other": "Невядомыя аргументы: %s"
},
"Invalid values:": "Несапраўдныя значэння:",
"Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Дадзенае значэнне: %s, Магчымасці: %s",
"Argument check failed: %s": "Праверка аргументаў не ўдалася: %s",
"Implications failed:": "Дадзены аргумент патрабуе наступны дадатковы аргумент:",
"Not enough arguments following: %s": "Недастаткова наступных аргументаў: %s",
"Invalid JSON config file: %s": "Несапраўдны файл канфігурацыі JSON: %s",
"Path to JSON config file": "Шлях да файла канфігурацыі JSON",
"Show help": "Паказаць дапамогу",
"Show version number": "Паказаць нумар версіі",
"Did you mean %s?": "Вы мелі на ўвазе %s?"
}
+39
View File
@@ -0,0 +1,39 @@
{
"Commands:": "Kommandos:",
"Options:": "Optionen:",
"Examples:": "Beispiele:",
"boolean": "boolean",
"count": "Zähler",
"string": "string",
"number": "Zahl",
"array": "array",
"required": "erforderlich",
"default:": "Standard:",
"choices:": "Möglichkeiten:",
"aliases:": "Aliase:",
"generated-value": "Generierter-Wert",
"Not enough non-option arguments: got %s, need at least %s": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt",
"Too many non-option arguments: got %s, maximum of %s": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt",
"Missing argument value: %s": {
"one": "Fehlender Argumentwert: %s",
"other": "Fehlende Argumentwerte: %s"
},
"Missing required argument: %s": {
"one": "Fehlendes Argument: %s",
"other": "Fehlende Argumente: %s"
},
"Unknown argument: %s": {
"one": "Unbekanntes Argument: %s",
"other": "Unbekannte Argumente: %s"
},
"Invalid values:": "Unzulässige Werte:",
"Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeben: %s, Möglichkeiten: %s",
"Argument check failed: %s": "Argumente-Check fehlgeschlagen: %s",
"Implications failed:": "Implikationen fehlgeschlagen:",
"Not enough arguments following: %s": "Nicht genügend Argumente nach: %s",
"Invalid JSON config file: %s": "Fehlerhafte JSON-Config Datei: %s",
"Path to JSON config file": "Pfad zur JSON-Config Datei",
"Show help": "Hilfe anzeigen",
"Show version number": "Version anzeigen",
"Did you mean %s?": "Meintest du %s?"
}
+42
View File
@@ -0,0 +1,42 @@
{
"Commands:": "Commands:",
"Options:": "Options:",
"Examples:": "Examples:",
"boolean": "boolean",
"count": "count",
"string": "string",
"number": "number",
"array": "array",
"required": "required",
"default:": "default:",
"choices:": "choices:",
"aliases:": "aliases:",
"generated-value": "generated-value",
"Not enough non-option arguments: got %s, need at least %s": "Not enough non-option arguments: got %s, need at least %s",
"Too many non-option arguments: got %s, maximum of %s": "Too many non-option arguments: got %s, maximum of %s",
"Missing argument value: %s": {
"one": "Missing argument value: %s",
"other": "Missing argument values: %s"
},
"Missing required argument: %s": {
"one": "Missing required argument: %s",
"other": "Missing required arguments: %s"
},
"Unknown argument: %s": {
"one": "Unknown argument: %s",
"other": "Unknown arguments: %s"
},
"Invalid values:": "Invalid values:",
"Argument: %s, Given: %s, Choices: %s": "Argument: %s, Given: %s, Choices: %s",
"Argument check failed: %s": "Argument check failed: %s",
"Implications failed:": "Implications failed:",
"Not enough arguments following: %s": "Not enough arguments following: %s",
"Invalid JSON config file: %s": "Invalid JSON config file: %s",
"Path to JSON config file": "Path to JSON config file",
"Show help": "Show help",
"Show version number": "Show version number",
"Did you mean %s?": "Did you mean %s?",
"Arguments %s and %s are mutually exclusive" : "Arguments %s and %s are mutually exclusive",
"Positionals:": "Positionals:",
"command": "command"
}
+39
View File
@@ -0,0 +1,39 @@
{
"Commands:": "Comandos:",
"Options:": "Opciones:",
"Examples:": "Ejemplos:",
"boolean": "booleano",
"count": "cuenta",
"string": "cadena de caracteres",
"number": "número",
"array": "tabla",
"required": "requerido",
"default:": "defecto:",
"choices:": "selección:",
"aliases:": "alias:",
"generated-value": "valor-generado",
"Not enough non-option arguments: got %s, need at least %s": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s",
"Too many non-option arguments: got %s, maximum of %s": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s",
"Missing argument value: %s": {
"one": "Falta argumento: %s",
"other": "Faltan argumentos: %s"
},
"Missing required argument: %s": {
"one": "Falta argumento requerido: %s",
"other": "Faltan argumentos requeridos: %s"
},
"Unknown argument: %s": {
"one": "Argumento desconocido: %s",
"other": "Argumentos desconocidos: %s"
},
"Invalid values:": "Valores inválidos:",
"Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Recibido: %s, Seleccionados: %s",
"Argument check failed: %s": "Verificación de argumento ha fallado: %s",
"Implications failed:": "Implicaciones fallidas:",
"Not enough arguments following: %s": "No hay suficientes argumentos después de: %s",
"Invalid JSON config file: %s": "Archivo de configuración JSON inválido: %s",
"Path to JSON config file": "Ruta al archivo de configuración JSON",
"Show help": "Muestra ayuda",
"Show version number": "Muestra número de versión",
"Did you mean %s?": "Quisiste decir %s?"
}
+37
View File
@@ -0,0 +1,37 @@
{
"Commands:": "Commandes:",
"Options:": "Options:",
"Examples:": "Exemples:",
"boolean": "booléen",
"count": "comptage",
"string": "chaine de caractère",
"number": "nombre",
"array": "tableau",
"required": "requis",
"default:": "défaut:",
"choices:": "choix:",
"generated-value": "valeur générée",
"Not enough non-option arguments: got %s, need at least %s": "Pas assez d'arguments non-option: reçu %s, besoin d'au moins %s",
"Too many non-option arguments: got %s, maximum of %s": "Trop d'arguments non-option: reçu %s, maximum %s",
"Missing argument value: %s": {
"one": "Argument manquant: %s",
"other": "Arguments manquants: %s"
},
"Missing required argument: %s": {
"one": "Argument requis manquant: %s",
"other": "Arguments requis manquants: %s"
},
"Unknown argument: %s": {
"one": "Argument inconnu: %s",
"other": "Arguments inconnus: %s"
},
"Invalid values:": "Valeurs invalides:",
"Argument: %s, Given: %s, Choices: %s": "Argument: %s, Donné: %s, Choix: %s",
"Argument check failed: %s": "Echec de la vérification de l'argument: %s",
"Implications failed:": "Implications échouées:",
"Not enough arguments following: %s": "Pas assez d'arguments suivant: %s",
"Invalid JSON config file: %s": "Fichier de configuration JSON invalide: %s",
"Path to JSON config file": "Chemin du fichier de configuration JSON",
"Show help": "Affiche de l'aide",
"Show version number": "Affiche le numéro de version"
}
+42
View File
@@ -0,0 +1,42 @@
{
"Commands:": "आदेश:",
"Options:": "विकल्प:",
"Examples:": "उदाहरण:",
"boolean": "सत्यता",
"count": "संख्या",
"string": "वर्णों का तार ",
"number": "अंक",
"array": "सरणी",
"required": "आवश्यक",
"default:": "डिफॉल्ट:",
"choices:": "विकल्प:",
"aliases:": "उपनाम:",
"generated-value": "उत्पन्न-मूल्य",
"Not enough non-option arguments: got %s, need at least %s": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है",
"Too many non-option arguments: got %s, maximum of %s": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य",
"Missing argument value: %s": {
"one": "कुछ तर्को के मूल्य गुम हैं: %s",
"other": "कुछ तर्को के मूल्य गुम हैं: %s"
},
"Missing required argument: %s": {
"one": "आवश्यक तर्क गुम हैं: %s",
"other": "आवश्यक तर्क गुम हैं: %s"
},
"Unknown argument: %s": {
"one": "अज्ञात तर्क प्राप्त: %s",
"other": "अज्ञात तर्क प्राप्त: %s"
},
"Invalid values:": "अमान्य मूल्य:",
"Argument: %s, Given: %s, Choices: %s": "तर्क: %s, प्राप्त: %s, विकल्प: %s",
"Argument check failed: %s": "तर्क जांच विफल: %s",
"Implications failed:": "दिए गए तर्क के लिए अतिरिक्त तर्क की अपेक्षा है:",
"Not enough arguments following: %s": "निम्नलिखित के बाद पर्याप्त तर्क नहीं प्राप्त: %s",
"Invalid JSON config file: %s": "अमान्य JSON config फाइल: %s",
"Path to JSON config file": "JSON config फाइल का पथ",
"Show help": "सहायता दिखाएँ",
"Show version number": "Version संख्या दिखाएँ",
"Did you mean %s?": "क्या आपका मतलब है %s?",
"Arguments %s and %s are mutually exclusive" : "तर्क %s और %s परस्पर अनन्य हैं",
"Positionals:": "स्थानीय:",
"command": "आदेश"
}
+39
View File
@@ -0,0 +1,39 @@
{
"Commands:": "Parancsok:",
"Options:": "Opciók:",
"Examples:": "Példák:",
"boolean": "boolean",
"count": "számláló",
"string": "szöveg",
"number": "szám",
"array": "tömb",
"required": "kötelező",
"default:": "alapértelmezett:",
"choices:": "lehetőségek:",
"aliases:": "aliaszok:",
"generated-value": "generált-érték",
"Not enough non-option arguments: got %s, need at least %s": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell",
"Too many non-option arguments: got %s, maximum of %s": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet",
"Missing argument value: %s": {
"one": "Hiányzó argumentum érték: %s",
"other": "Hiányzó argumentum értékek: %s"
},
"Missing required argument: %s": {
"one": "Hiányzó kötelező argumentum: %s",
"other": "Hiányzó kötelező argumentumok: %s"
},
"Unknown argument: %s": {
"one": "Ismeretlen argumentum: %s",
"other": "Ismeretlen argumentumok: %s"
},
"Invalid values:": "Érvénytelen érték:",
"Argument: %s, Given: %s, Choices: %s": "Argumentum: %s, Megadott: %s, Lehetőségek: %s",
"Argument check failed: %s": "Argumentum ellenőrzés sikertelen: %s",
"Implications failed:": "Implikációk sikertelenek:",
"Not enough arguments following: %s": "Nem elég argumentum követi: %s",
"Invalid JSON config file: %s": "Érvénytelen JSON konfigurációs file: %s",
"Path to JSON config file": "JSON konfigurációs file helye",
"Show help": "Súgo megjelenítése",
"Show version number": "Verziószám megjelenítése",
"Did you mean %s?": "Erre gondoltál %s?"
}
+43
View File
@@ -0,0 +1,43 @@
{
"Commands:": "Perintah:",
"Options:": "Pilihan:",
"Examples:": "Contoh:",
"boolean": "boolean",
"count": "jumlah",
"number": "nomor",
"string": "string",
"array": "larik",
"required": "diperlukan",
"default:": "bawaan:",
"aliases:": "istilah lain:",
"choices:": "pilihan:",
"generated-value": "nilai-yang-dihasilkan",
"Not enough non-option arguments: got %s, need at least %s": "Argumen wajib kurang: hanya %s, minimal %s",
"Too many non-option arguments: got %s, maximum of %s": "Terlalu banyak argumen wajib: ada %s, maksimal %s",
"Missing argument value: %s": {
"one": "Kurang argumen: %s",
"other": "Kurang argumen: %s"
},
"Missing required argument: %s": {
"one": "Kurang argumen wajib: %s",
"other": "Kurang argumen wajib: %s"
},
"Unknown argument: %s": {
"one": "Argumen tak diketahui: %s",
"other": "Argumen tak diketahui: %s"
},
"Invalid values:": "Nilai-nilai tidak valid:",
"Argument: %s, Given: %s, Choices: %s": "Argumen: %s, Diberikan: %s, Pilihan: %s",
"Argument check failed: %s": "Pemeriksaan argument gagal: %s",
"Implications failed:": "Implikasi gagal:",
"Not enough arguments following: %s": "Kurang argumen untuk: %s",
"Invalid JSON config file: %s": "Berkas konfigurasi JSON tidak valid: %s",
"Path to JSON config file": "Alamat berkas konfigurasi JSON",
"Show help": "Lihat bantuan",
"Show version number": "Lihat nomor versi",
"Did you mean %s?": "Maksud Anda: %s?",
"Arguments %s and %s are mutually exclusive" : "Argumen %s dan %s saling eksklusif",
"Positionals:": "Posisional-posisional:",
"command": "perintah"
}
+39
View File
@@ -0,0 +1,39 @@
{
"Commands:": "Comandi:",
"Options:": "Opzioni:",
"Examples:": "Esempi:",
"boolean": "booleano",
"count": "contatore",
"string": "stringa",
"number": "numero",
"array": "vettore",
"required": "richiesto",
"default:": "predefinito:",
"choices:": "scelte:",
"aliases:": "alias:",
"generated-value": "valore generato",
"Not enough non-option arguments: got %s, need at least %s": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s",
"Too many non-option arguments: got %s, maximum of %s": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s",
"Missing argument value: %s": {
"one": "Argomento mancante: %s",
"other": "Argomenti mancanti: %s"
},
"Missing required argument: %s": {
"one": "Argomento richiesto mancante: %s",
"other": "Argomenti richiesti mancanti: %s"
},
"Unknown argument: %s": {
"one": "Argomento sconosciuto: %s",
"other": "Argomenti sconosciuti: %s"
},
"Invalid values:": "Valori non validi:",
"Argument: %s, Given: %s, Choices: %s": "Argomento: %s, Richiesto: %s, Scelte: %s",
"Argument check failed: %s": "Controllo dell'argomento fallito: %s",
"Implications failed:": "Argomenti impliciti non soddisfatti:",
"Not enough arguments following: %s": "Argomenti insufficienti dopo: %s",
"Invalid JSON config file: %s": "File di configurazione JSON non valido: %s",
"Path to JSON config file": "Percorso del file di configurazione JSON",
"Show help": "Mostra la schermata di aiuto",
"Show version number": "Mostra il numero di versione",
"Did you mean %s?": "Intendi forse %s?"
}
+42
View File
@@ -0,0 +1,42 @@
{
"Commands:": "コマンド:",
"Options:": "オプション:",
"Examples:": "例:",
"boolean": "真偽",
"count": "カウント",
"string": "文字列",
"number": "数値",
"array": "配列",
"required": "必須",
"default:": "デフォルト:",
"choices:": "選択してください:",
"aliases:": "エイリアス:",
"generated-value": "生成された値",
"Not enough non-option arguments: got %s, need at least %s": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:",
"Too many non-option arguments: got %s, maximum of %s": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:",
"Missing argument value: %s": {
"one": "引数が見つかりません: %s",
"other": "引数が見つかりません: %s"
},
"Missing required argument: %s": {
"one": "必須の引数が見つかりません: %s",
"other": "必須の引数が見つかりません: %s"
},
"Unknown argument: %s": {
"one": "未知の引数です: %s",
"other": "未知の引数です: %s"
},
"Invalid values:": "不正な値です:",
"Argument: %s, Given: %s, Choices: %s": "引数は %s です。指定できるのは %s つです。選択してください: %s",
"Argument check failed: %s": "引数のチェックに失敗しました: %s",
"Implications failed:": "オプションの組み合わせで不正が生じました:",
"Not enough arguments following: %s": "次の引数が不足しています。: %s",
"Invalid JSON config file: %s": "JSONの設定ファイルが不正です: %s",
"Path to JSON config file": "JSONの設定ファイルまでのpath",
"Show help": "ヘルプを表示",
"Show version number": "バージョンを表示",
"Did you mean %s?": "もしかして %s?",
"Arguments %s and %s are mutually exclusive" : "引数 %s と %s は同時に指定できません",
"Positionals:": "位置:",
"command": "コマンド"
}
+42
View File
@@ -0,0 +1,42 @@
{
"Commands:": "명령:",
"Options:": "옵션:",
"Examples:": "예시:",
"boolean": "여부",
"count": "개수",
"string": "문자열",
"number": "숫자",
"array": "배열",
"required": "필수",
"default:": "기본:",
"choices:": "선택:",
"aliases:": "별칭:",
"generated-value": "생성된 값",
"Not enough non-option arguments: got %s, need at least %s": "옵션이 아닌 인자가 충분치 않습니다: %s개를 받았지만, 적어도 %s개는 필요합니다",
"Too many non-option arguments: got %s, maximum of %s": "옵션이 아닌 인자가 너무 많습니다: %s개를 받았지만, %s개 이하여야 합니다",
"Missing argument value: %s": {
"one": "인자값을 받지 못했습니다: %s",
"other": "인자값들을 받지 못했습니다: %s"
},
"Missing required argument: %s": {
"one": "필수 인자를 받지 못했습니다: %s",
"other": "필수 인자들을 받지 못했습니다: %s"
},
"Unknown argument: %s": {
"one": "알 수 없는 인자입니다: %s",
"other": "알 수 없는 인자들입니다: %s"
},
"Invalid values:": "잘못된 값입니다:",
"Argument: %s, Given: %s, Choices: %s": "인자: %s, 입력받은 값: %s, 선택지: %s",
"Argument check failed: %s": "유효하지 않은 인자입니다: %s",
"Implications failed:": "옵션의 조합이 잘못되었습니다:",
"Not enough arguments following: %s": "인자가 충분하게 주어지지 않았습니다: %s",
"Invalid JSON config file: %s": "유효하지 않은 JSON 설정파일입니다: %s",
"Path to JSON config file": "JSON 설정파일 경로",
"Show help": "도움말을 보여줍니다",
"Show version number": "버전 넘버를 보여줍니다",
"Did you mean %s?": "찾고계신게 %s입니까?",
"Arguments %s and %s are mutually exclusive" : "%s와 %s 인자는 같이 사용될 수 없습니다",
"Positionals:": "위치:",
"command": "명령"
}
+37
View File
@@ -0,0 +1,37 @@
{
"Commands:": "Kommandoer:",
"Options:": "Alternativer:",
"Examples:": "Eksempler:",
"boolean": "boolsk",
"count": "antall",
"string": "streng",
"number": "nummer",
"array": "matrise",
"required": "obligatorisk",
"default:": "standard:",
"choices:": "valg:",
"generated-value": "generert-verdi",
"Not enough non-option arguments: got %s, need at least %s": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s",
"Too many non-option arguments: got %s, maximum of %s": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s",
"Missing argument value: %s": {
"one": "Mangler argument verdi: %s",
"other": "Mangler argument verdier: %s"
},
"Missing required argument: %s": {
"one": "Mangler obligatorisk argument: %s",
"other": "Mangler obligatoriske argumenter: %s"
},
"Unknown argument: %s": {
"one": "Ukjent argument: %s",
"other": "Ukjente argumenter: %s"
},
"Invalid values:": "Ugyldige verdier:",
"Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gitt: %s, Valg: %s",
"Argument check failed: %s": "Argument sjekk mislyktes: %s",
"Implications failed:": "Konsekvensene mislyktes:",
"Not enough arguments following: %s": "Ikke nok følgende argumenter: %s",
"Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s",
"Path to JSON config file": "Bane til JSON konfigurasjonsfil",
"Show help": "Vis hjelp",
"Show version number": "Vis versjonsnummer"
}
+42
View File
@@ -0,0 +1,42 @@
{
"Commands:": "Opdrachten:",
"Options:": "Opties:",
"Examples:": "Voorbeelden:",
"boolean": "boolean",
"count": "aantal",
"string": "text",
"number": "nummer",
"array": "lijst",
"required": "verplicht",
"default:": "standaard:",
"choices:": "keuzes:",
"aliases:": "aliassen:",
"generated-value": "gegenereerde waarde",
"Not enough non-option arguments: got %s, need at least %s": "Niet genoeg non-optie argumenten. Gekregen: %s, minstens nodig: %s",
"Too many non-option arguments: got %s, maximum of %s": "Te veel non-optie argumenten. Gekregen: %s, maximum: %s",
"Missing argument value: %s": {
"one": "Missing argument value: %s",
"other": "Missing argument values: %s"
},
"Missing required argument: %s": {
"one": "Missend verplichte argument: %s",
"other": "Missende verplichte argumenten: %s"
},
"Unknown argument: %s": {
"one": "Onbekend argument: %s",
"other": "Onbekende argumenten: %s"
},
"Invalid values:": "Ongeldige waardes:",
"Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeven: %s, Keuzes: %s",
"Argument check failed: %s": "Argument check mislukt: %s",
"Implications failed:": "Implicaties mislukt:",
"Not enough arguments following: %s": "Niet genoeg argumenten na: %s",
"Invalid JSON config file: %s": "Ongeldig JSON configuratiebestand: %s",
"Path to JSON config file": "Pad naar JSON configuratiebestand",
"Show help": "Toon help",
"Show version number": "Toon versie nummer",
"Did you mean %s?": "Bedoelde u misschien %s?",
"Arguments %s and %s are mutually exclusive": "Argumenten %s en %s zijn onderling uitsluitend",
"Positionals:": "Positie-afhankelijke argumenten",
"command": "commando"
}
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more