code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
join() {
// get chunk of fork
let chunk = this.finish();
// restore previous state
let prev = this.stack.pop();
if (!prev)
throw new Error('invalid state, fork stack empty');
this.chunks = prev.chunks;
this.buf = prev.buf;
// write length of chunk as varint
this.uint32(chunk.byteLength);
return this.raw(chunk);
} | Join the last fork. Write its length and bytes, then
return to the previous state. | join ( ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
tag(fieldNo, type) {
return this.uint32((fieldNo << 3 | type) >>> 0);
} | Writes a tag (field number and wire type).
Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
Generated code should compute the tag ahead of time and call `uint32()`. | tag ( fieldNo , type ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
uint32(value) {
assertUInt32(value);
// write value as varint 32, inlined for speed
while (value > 0x7f) {
this.buf.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
this.buf.push(value);
return this;
} | Write a `uint32` value, an unsigned 32 bit varint. | uint32 ( value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
int32(value) {
assertInt32(value);
varint32write(value, this.buf);
return this;
} | Write a `int32` value, a signed 32 bit varint. | int32 ( value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
sfixed64(value) {
let chunk = new Uint8Array(8);
let view = new DataView(chunk.buffer);
let long = PbLong.from(value);
view.setInt32(0, long.lo, true);
view.setInt32(4, long.hi, true);
return this.raw(chunk);
} | Write a `fixed64` value, a signed, fixed-length 64-bit integer. | sfixed64 ( value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
fixed64(value) {
let chunk = new Uint8Array(8);
let view = new DataView(chunk.buffer);
let long = PbULong.from(value);
view.setInt32(0, long.lo, true);
view.setInt32(4, long.hi, true);
return this.raw(chunk);
} | Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. | fixed64 ( value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
int64(value) {
let long = PbLong.from(value);
varint64write(long.lo, long.hi, this.buf);
return this;
} | Write a `int64` value, a signed 64-bit varint. | int64 ( value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
sint64(value) {
let long = PbLong.from(value),
// zigzag encode
sign = long.hi >> 31, lo = (long.lo << 1) ^ sign, hi = ((long.hi << 1) | (long.lo >>> 31)) ^ sign;
varint64write(lo, hi, this.buf);
return this;
} | Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. | sint64 ( value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
uint64(value) {
let long = PbULong.from(value);
varint64write(long.lo, long.hi, this.buf);
return this;
} | Write a `uint64` value, an unsigned 64-bit varint. | uint64 ( value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function jsonReadOptions(options) {
return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead;
} | Make options for reading JSON data from partial options. | jsonReadOptions ( options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function jsonWriteOptions(options) {
return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite;
} | Make options for writing JSON data from partial options. | jsonWriteOptions ( options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function lowerCamelCase(snakeCase) {
let capNext = false;
const sb = [];
for (let i = 0; i < snakeCase.length; i++) {
let next = snakeCase.charAt(i);
if (next == '_') {
capNext = true;
}
else if (/\d/.test(next)) {
sb.push(next);
capNext = true;
}
else if (capNext) {
sb.push(next.toUpperCase());
capNext = false;
}
else if (i == 0) {
sb.push(next.toLowerCase());
}
else {
sb.push(next);
}
}
return sb.join('');
} | Converts snake_case to lowerCamelCase.
Should behave like protoc:
https://github.com/protocolbuffers/protobuf/blob/e8ae137c96444ea313485ed1118c5e43b2099cf1/src/google/protobuf/compiler/java/java_helpers.cc#L118 | lowerCamelCase ( snakeCase ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function normalizeFieldInfo(field) {
var _a, _b, _c, _d;
field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lowerCamelCase(field.name);
field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lowerCamelCase(field.name);
field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO;
field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : (field.repeat ? false : field.oneof ? false : field.kind == "message");
return field;
} | Turns PartialFieldInfo into FieldInfo. | normalizeFieldInfo ( field ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function isOneofGroup(any) {
if (typeof any != 'object' || any === null || !any.hasOwnProperty('oneofKind')) {
return false;
}
switch (typeof any.oneofKind) {
case "string":
if (any[any.oneofKind] === undefined)
return false;
return Object.keys(any).length == 2;
case "undefined":
return Object.keys(any).length == 1;
default:
return false;
}
} | Is the given value a valid oneof group?
We represent protobuf `oneof` as algebraic data types (ADT) in generated
code. But when working with messages of unknown type, the ADT does not
help us.
This type guard checks if the given object adheres to the ADT rules, which
are as follows:
1) Must be an object.
2) Must have a "oneofKind" discriminator property.
3) If "oneofKind" is `undefined`, no member field is selected. The object
must not have any other properties.
4) If "oneofKind" is a `string`, the member field with this name is
selected.
5) If a member field is selected, the object must have a second property
with this name. The property must not be `undefined`.
6) No extra properties are allowed. The object has either one property
(no selection) or two properties (selection). | isOneofGroup ( any ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
is(message, depth, allowExcessProperties = false) {
if (depth < 0)
return true;
if (message === null || message === undefined || typeof message != 'object')
return false;
this.prepare();
let keys = Object.keys(message), data = this.data;
// if a required field is missing in arg, this cannot be a T
if (keys.length < data.req.length || data.req.some(n => !keys.includes(n)))
return false;
if (!allowExcessProperties) {
// if the arg contains a key we dont know, this is not a literal T
if (keys.some(k => !data.known.includes(k)))
return false;
}
// "With a depth of 0, only the presence and absence of fields is checked."
// "With a depth of 1 or more, the field types are checked."
if (depth < 1) {
return true;
}
// check oneof group
for (const name of data.oneofs) {
const group = message[name];
if (!isOneofGroup(group))
return false;
if (group.oneofKind === undefined)
continue;
const field = this.fields.find(f => f.localName === group.oneofKind);
if (!field)
return false; // we found no field, but have a kind, something is wrong
if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth))
return false;
}
// check types
for (const field of this.fields) {
if (field.oneof !== undefined)
continue;
if (!this.field(message[field.localName], field, allowExcessProperties, depth))
return false;
}
return true;
} | Is the argument a valid message as specified by the
reflection information?
Checks all field types recursively. The `depth`
specifies how deep into the structure the check will be.
With a depth of 0, only the presence of fields
is checked.
With a depth of 1 or more, the field types are checked.
With a depth of 2 or more, the members of map, repeated
and message fields are checked.
Message fields will be checked recursively with depth - 1.
The number of map entries / repeated values being checked
is < depth. | is ( message , depth , allowExcessProperties = false ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function reflectionLongConvert(long, type) {
switch (type) {
case LongType.BIGINT:
return long.toBigInt();
case LongType.NUMBER:
return long.toNumber();
default:
// case undefined:
// case LongType.STRING:
return long.toString();
}
} | Utility method to convert a PbLong or PbUlong to a JavaScript
representation during runtime.
Works with generated field information, `undefined` is equivalent
to `STRING`. | reflectionLongConvert ( long , type ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
enum(type, json, fieldName, ignoreUnknownFields) {
if (type[0] == 'google.protobuf.NullValue')
assert(json === null || json === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} only accepts null.`);
if (json === null)
// we require 0 to be default value for all enums
return 0;
switch (typeof json) {
case "number":
assert(Number.isInteger(json), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json}.`);
return json;
case "string":
let localEnumName = json;
if (type[2] && json.substring(0, type[2].length) === type[2])
// lookup without the shared prefix
localEnumName = json.substring(type[2].length);
let enumNumber = type[1][localEnumName];
if (typeof enumNumber === 'undefined' && ignoreUnknownFields) {
return false;
}
assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} has no value for "${json}".`);
return enumNumber;
}
assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json}".`);
} | Returns `false` for unrecognized string representations.
google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). | enum ( type , json , fieldName , ignoreUnknownFields ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
write(message, options) {
const json = {}, source = message;
for (const field of this.fields) {
// field is not part of a oneof, simply write as is
if (!field.oneof) {
let jsonValue = this.field(field, source[field.localName], options);
if (jsonValue !== undefined)
json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue;
continue;
}
// field is part of a oneof
const group = source[field.oneof];
if (group.oneofKind !== field.localName)
continue; // not selected, skip
const opt = field.kind == 'scalar' || field.kind == 'enum'
? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options;
let jsonValue = this.field(field, group[field.localName], opt);
assert(jsonValue !== undefined);
json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue;
}
return json;
} | Converts the message to a JSON object, based on the field descriptors. | write ( message , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
enum(type, value, fieldName, optional, emitDefaultValues, enumAsInteger) {
if (type[0] == 'google.protobuf.NullValue')
return !emitDefaultValues && !optional ? undefined : null;
if (value === undefined) {
assert(optional);
return undefined;
}
if (value === 0 && !emitDefaultValues && !optional)
// we require 0 to be default value for all enums
return undefined;
assert(typeof value == 'number');
assert(Number.isInteger(value));
if (enumAsInteger || !type[1].hasOwnProperty(value))
// if we don't now the enum value, just return the number
return value;
if (type[2])
// restore the dropped prefix
return type[2] + type[1][value];
return type[1][value];
} | Returns `null` as the default for google.protobuf.NullValue. | enum ( type , value , fieldName , optional , emitDefaultValues , enumAsInteger ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function reflectionScalarDefault(type, longType = LongType.STRING) {
switch (type) {
case ScalarType.BOOL:
return false;
case ScalarType.UINT64:
case ScalarType.FIXED64:
return reflectionLongConvert(PbULong.ZERO, longType);
case ScalarType.INT64:
case ScalarType.SFIXED64:
case ScalarType.SINT64:
return reflectionLongConvert(PbLong.ZERO, longType);
case ScalarType.DOUBLE:
case ScalarType.FLOAT:
return 0.0;
case ScalarType.BYTES:
return new Uint8Array(0);
case ScalarType.STRING:
return "";
default:
// case ScalarType.INT32:
// case ScalarType.UINT32:
// case ScalarType.SINT32:
// case ScalarType.FIXED32:
// case ScalarType.SFIXED32:
return 0;
}
} | Creates the default value for a scalar type. | reflectionScalarDefault ( type , longType = LongType . STRING ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
packed(writer, type, fieldNo, value) {
if (!value.length)
return;
assert(type !== ScalarType.BYTES && type !== ScalarType.STRING);
// write tag
writer.tag(fieldNo, WireType.LengthDelimited);
// begin length-delimited
writer.fork();
// write values without tags
let [, method,] = this.scalarInfo(type);
for (let i = 0; i < value.length; i++)
writer[method](value[i]);
// end length delimited
writer.join();
} | Write an array of scalar values in packed format. | packed ( writer , type , fieldNo , value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
scalarInfo(type, value) {
let t = WireType.Varint;
let m;
let i = value === undefined;
let d = value === 0;
switch (type) {
case ScalarType.INT32:
m = "int32";
break;
case ScalarType.STRING:
d = i || !value.length;
t = WireType.LengthDelimited;
m = "string";
break;
case ScalarType.BOOL:
d = value === false;
m = "bool";
break;
case ScalarType.UINT32:
m = "uint32";
break;
case ScalarType.DOUBLE:
t = WireType.Bit64;
m = "double";
break;
case ScalarType.FLOAT:
t = WireType.Bit32;
m = "float";
break;
case ScalarType.INT64:
d = i || PbLong.from(value).isZero();
m = "int64";
break;
case ScalarType.UINT64:
d = i || PbULong.from(value).isZero();
m = "uint64";
break;
case ScalarType.FIXED64:
d = i || PbULong.from(value).isZero();
t = WireType.Bit64;
m = "fixed64";
break;
case ScalarType.BYTES:
d = i || !value.byteLength;
t = WireType.LengthDelimited;
m = "bytes";
break;
case ScalarType.FIXED32:
t = WireType.Bit32;
m = "fixed32";
break;
case ScalarType.SFIXED32:
t = WireType.Bit32;
m = "sfixed32";
break;
case ScalarType.SFIXED64:
d = i || PbLong.from(value).isZero();
t = WireType.Bit64;
m = "sfixed64";
break;
case ScalarType.SINT32:
m = "sint32";
break;
case ScalarType.SINT64:
d = i || PbLong.from(value).isZero();
m = "sint64";
break;
}
return [t, m, i || d];
} | Get information for writing a scalar value.
Returns tuple:
[0]: appropriate WireType
[1]: name of the appropriate method of IBinaryWriter
[2]: whether the given value is a default value
If argument `value` is omitted, [2] is always false. | scalarInfo ( type , value ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function reflectionCreate(type) {
/**
* This ternary can be removed in the next major version.
* The `Object.create()` code path utilizes a new `messagePrototype`
* property on the `IMessageType` which has this same `MESSAGE_TYPE`
* non-enumerable property on it. Doing it this way means that we only
* pay the cost of `Object.defineProperty()` once per `IMessageType`
* class of once per "instance". The falsy code path is only provided
* for backwards compatibility in cases where the runtime library is
* updated without also updating the generated code.
*/
const msg = type.messagePrototype
? Object.create(type.messagePrototype)
: Object.defineProperty({}, MESSAGE_TYPE, { value: type });
for (let field of type.fields) {
let name = field.localName;
if (field.opt)
continue;
if (field.oneof)
msg[field.oneof] = { oneofKind: undefined };
else if (field.repeat)
msg[name] = [];
else
switch (field.kind) {
case "scalar":
msg[name] = reflectionScalarDefault(field.T, field.L);
break;
case "enum":
// we require 0 to be default value for all enums
msg[name] = 0;
break;
case "map":
msg[name] = {};
break;
}
}
return msg;
} | Creates an instance of the generic message, using the field
information. | reflectionCreate ( type ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
function reflectionEquals(info, a, b) {
if (a === b)
return true;
if (!a || !b)
return false;
for (let field of info.fields) {
let localName = field.localName;
let val_a = field.oneof ? a[field.oneof][localName] : a[localName];
let val_b = field.oneof ? b[field.oneof][localName] : b[localName];
switch (field.kind) {
case "enum":
case "scalar":
let t = field.kind == "enum" ? ScalarType.INT32 : field.T;
if (!(field.repeat
? repeatedPrimitiveEq(t, val_a, val_b)
: primitiveEq(t, val_a, val_b)))
return false;
break;
case "map":
if (!(field.V.kind == "message"
? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b))
: repeatedPrimitiveEq(field.V.kind == "enum" ? ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b))))
return false;
break;
case "message":
let T = field.T();
if (!(field.repeat
? repeatedMsgEq(T, val_a, val_b)
: T.equals(val_a, val_b)))
return false;
break;
}
}
return true;
} | Determines whether two message of the same type have the same field values.
Checks for deep equality, traversing repeated fields, oneof groups, maps
and messages recursively.
Will also return true if both messages are `undefined`. | reflectionEquals ( info , a , b ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
clone(message) {
let copy = this.create();
reflectionMergePartial(this, copy, message);
return copy;
} | Clone the message.
Unknown fields are discarded. | clone ( message ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
is(arg, depth = this.defaultCheckDepth) {
return this.refTypeCheck.is(arg, depth, false);
} | Is the given value assignable to our message type
and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? | is ( arg , depth = this . defaultCheckDepth ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
isAssignable(arg, depth = this.defaultCheckDepth) {
return this.refTypeCheck.is(arg, depth, true);
} | Is the given value assignable to our message type,
regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? | isAssignable ( arg , depth = this . defaultCheckDepth ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
mergePartial(target, source) {
reflectionMergePartial(this, target, source);
} | Copy partial data into the target message. | mergePartial ( target , source ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
fromBinary(data, options) {
let opt = binaryReadOptions(options);
return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt);
} | Create a new message from binary format. | fromBinary ( data , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
fromJson(json, options) {
return this.internalJsonRead(json, jsonReadOptions(options));
} | Read a new message from a JSON value. | fromJson ( json , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
fromJsonString(json, options) {
let value = JSON.parse(json);
return this.fromJson(value, options);
} | Read a new message from a JSON string.
This is equivalent to `T.fromJson(JSON.parse(json))`. | fromJsonString ( json , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
toJson(message, options) {
return this.internalJsonWrite(message, jsonWriteOptions(options));
} | Write the message to canonical JSON value. | toJson ( message , options ) | javascript | DualSubs/Universal | archive/js/v1.4/Translate.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Translate.response.beta.js | Apache-2.0 |
class Composite {
constructor(options = {}) {
this.Name = "Composite";
this.Version = "1.0.2";
this.Offset = 0;
this.Tolerance = 0;
this.Position = "Forward";
Object.assign(this, options);
log(`\n🟧 ${this.Name} v${this.Version}\n`); | Composite Subtitles
@param {Object} Sub1 - Sub1
@param {Object} Sub2 - Sub2
@param {Array} Kind - options = ["asr", "captions"]
@param {Number} Offset - Offset
@param {Number} Tolerance - Tolerance
@param {Array} Position - Position = ["Forward", "Reverse"]
@return {String} DualSub | constructor ( options = { } ) | javascript | DualSubs/Universal | archive/js/v1.4/Composite.Subtitles.response.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v1.4/Composite.Subtitles.response.beta.js | Apache-2.0 |
async function getENV(t,e,n){let i=$.getjson(t,n),s={};if("undefined"!=typeof $argument&&Boolean($argument)){let t=Object.fromEntries($argument.split("&").map((t=>t.split("="))));for(let e in t)f(s,e,t[e])}let g={...n?.Default?.Settings,...n?.[e]?.Settings,...i?.[e]?.Settings,...s},o={...n?.Default?.Configs,...n?.[e]?.Configs,...i?.[e]?.Configs},a=i?.[e]?.Caches||void 0;return"string"==typeof a&&(a=JSON.parse(a)),{Settings:g,Caches:a,Configs:o};function f(t,e,n){e.split(".").reduce(((t,i,s)=>t[i]=e.split(".").length===++s?n:t[i]||{}),t)}} | Get Environment Variables
@link https://github.com/VirgilClyne/VirgilClyne/blob/main/function/getENV/getENV.min.js
@author VirgilClyne
@param {String} t - Persistent Store Key
@param {String} e - Platform Name
@param {Object} n - Default Database
@return {Promise<*>} | (anonymous) | javascript | DualSubs/Universal | archive/js/v0.7/DualSubs.SUB.TTML.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.7/DualSubs.SUB.TTML.beta.js | Apache-2.0 |
async function setENV(name, url, database) {
$.log(`⚠ ${$.name}, Set Environment Variables`, "");
/***************** Verify *****************/
const { Settings: Verify } = await getENV(name, "Verify", database);
/***************** Advanced *****************/
let { Settings: Advanced } = await getENV(name, "Advanced", database);
Advanced.Translator.Times = parseInt(Advanced.Translator?.Times, 10) // BoxJs字符串转数字
Advanced.Translator.Interval = parseInt(Advanced.Translator?.Interval, 10) // BoxJs字符串转数字
Advanced.Translator.Exponential = JSON.parse(Advanced.Translator?.Exponential) // BoxJs字符串转Boolean
/***************** Platform *****************/
const Platform = /\.apple\.com/i.test(url) ? "Apple"
: /\.(dssott|starott)\.com/i.test(url) ? "Disney_Plus"
: /\.(hls\.row\.aiv-cdn|akamaihd|cloudfront)\.net/i.test(url) ? "Prime_Video"
: /\.(api\.hbo|hbomaxcdn)\.com/i.test(url) ? "HBO_Max"
: /\.(hulustream|huluim)\.com/i.test(url) ? "Hulu"
: /\.(cbsaavideo|cbsivideo|cbs)\.com/i.test(url) ? "Paramount_Plus"
: /dplus-ph-/i.test(url) ? "Discovery_Plus_Ph"
: /\.peacocktv\.com/i.test(url) ? "Peacock_TV"
: /\.uplynk\.com/i.test(url) ? "Discovery_Plus"
: /\.fubo\.tv/i.test(url) ? "Fubo_TV"
: /(\.youtube|youtubei\.googleapis)\.com/i.test(url) ? "YouTube"
: /\.(netflix\.com|nflxvideo\.net)/i.test(url) ? "Netflix"
: "Universal"
$.log(`🚧 ${$.name}, Set Environment Variables`, `Platform: ${Platform}`, "");
/***************** Settings *****************/
let { Settings, Caches = [], Configs } = await getENV(name, Platform, database);
if (Platform == "Apple") {
let platform = /\.itunes\.apple\.com\/WebObjects\/(MZPlay|MZPlayLocal)\.woa\/hls\/subscription\//i.test(url) ? "Apple_TV_Plus"
: /\.itunes\.apple\.com\/WebObjects\/(MZPlay|MZPlayLocal)\.woa\/hls\/workout\//i.test(url) ? "Apple_Fitness"
: /\.itunes\.apple\.com\/WebObjects\/(MZPlay|MZPlayLocal)\.woa\/hls\//i.test(url) ? "Apple_TV"
: /vod-.*-aoc\.tv\.apple\.com/i.test(url) ? "Apple_TV_Plus"
: /vod-.*-amt\.tv\.apple\.com/i.test(url) ? "Apple_TV"
: /(hls|hls-svod)\.itunes\.apple\.com/i.test(url) ? "Apple_Fitness"
: "Apple"
$.log(`🚧 ${$.name}, Set Environment Variables`, `platform: ${platform}`, "");
Settings = await getENV(name, platform, database).then(v=> v.Settings);
};
//Settings.Switch = JSON.parse(Settings.Switch) // BoxJs字符串转Boolean
if (typeof Settings.Types === "string") Settings.Types = Settings.Types.split(",") // BoxJs字符串转数组
if (Array.isArray(Settings.Types)) {
if (!Verify.GoogleCloud.Auth) Settings.Types = Settings.Types.filter(e => e !== "GoogleCloud"); // 移除不可用类型
if (!Verify.Azure.Auth) Settings.Types = Settings.Types.filter(e => e !== "Azure");
if (!Verify.DeepL.Auth) Settings.Types = Settings.Types.filter(e => e !== "DeepL");
}
Settings.External.Offset = parseInt(Settings.External?.Offset, 10) // BoxJs字符串转数字
Settings.External.ShowOnly = JSON.parse(Settings.External?.ShowOnly) // BoxJs字符串转Boolean
Settings.CacheSize = parseInt(Settings.CacheSize, 10) // BoxJs字符串转数字
Settings.Tolerance = parseInt(Settings.Tolerance, 10) // BoxJs字符串转数字
$.log(`🎉 ${$.name}, Set Environment Variables`, `Settings: ${typeof Settings}`, `Settings内容: ${JSON.stringify(Settings)}`, "");
return { Platform, Verify, Advanced, Settings, Caches, Configs };
}; | Set Environment Variables
@author VirgilClyne
@param {String} name - Persistent Store Key
@param {String} url - Request URL
@param {Object} database - Default DataBase
@return {Promise<*>} | setENV ( name , url , database ) | javascript | DualSubs/Universal | archive/js/v0.7/DualSubs.SUB.TTML.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.7/DualSubs.SUB.TTML.beta.js | Apache-2.0 |
async function getCache(url, type, settings, caches = {}) {
$.log(`⚠ ${$.name}, Get Cache`, "");
let Indices = {};
Indices.Index = await getIndex(url, settings, caches);
if (Indices.Index !== -1) {
for await (var language of settings.Languages) Indices[language] = await getDataIndex(url, Indices.Index, language)
if (type == "Official") {
// 修正缓存
if (Indices[settings.Languages[0]] !== -1) {
Indices[settings.Languages[1]] = caches[Indices.Index][settings.Languages[1]].findIndex(data => {
if (data.OPTION["GROUP-ID"] == caches[Indices.Index][settings.Languages[0]][Indices[settings.Languages[0]]].OPTION["GROUP-ID"] && data.OPTION.CHARACTERISTICS == caches[Indices.Index][settings.Languages[0]][Indices[settings.Languages[0]]].OPTION.CHARACTERISTICS) return true;
});
if (Indices[settings.Languages[1]] == -1) {
Indices[settings.Languages[1]] = caches[Indices.Index][settings.Languages[1]].findIndex(data => {
if (data.OPTION["GROUP-ID"] == caches[Indices.Index][settings.Languages[0]][Indices[settings.Languages[0]]].OPTION["GROUP-ID"]) return true;
});
};
};
};
}
$.log(`🎉 ${$.name}, Get Cache`, `Indices: ${JSON.stringify(Indices)}`, "");
return Indices
/***************** Fuctions *****************/
async function getIndex(url, settings, caches) {
return caches.findIndex(item => {
let URLs = [item?.URL];
for (var language of settings.Languages) URLs.push(item?.[language]?.map(d => getURIs(d)));
//$.log(`🎉 ${$.name}, 调试信息`, " Get Index", `URLs: ${URLs}`, "");
return URLs.flat(Infinity).some(URL => url.includes(URL || null));
})
};
async function getDataIndex(url, index, lang) { return caches?.[index]?.[lang]?.findIndex(item => getURIs(item).flat(Infinity).some(URL => url.includes(URL || null))); };
function getURIs(item) { return [item?.URL, item?.VTTs] }
}; | Get Cache
@author VirgilClyne
@param {String} url - Request URL
@param {String} type - type
@param {Object} settings - settings
@param {Object} cache - cache
@return {Promise<*>} | getCache ( url , type , settings , caches = { } ) | javascript | DualSubs/Universal | archive/js/v0.7/DualSubs.SUB.TTML.beta.js | https://github.com/DualSubs/Universal/blob/master/archive/js/v0.7/DualSubs.SUB.TTML.beta.js | Apache-2.0 |
function getSubtitlesFileName(url, platform) {
Console.log("☑️ Get Subtitles FileName", `url: ${url}`);
let fileName = undefined;
switch (platform) {
case "Apple":
fileName = request.url.match(/.+_(subtitles(_V\d)?-\d+\.webvtt)\?(.*)subtype=/)[1]; // Apple 片段分型序号不同
break;
case "Disney+":
fileName = request.url.match(/([^\/]+\.vtt)\?(.*)subtype=/)[1]; // Disney+ 片段名称相同
break;
case "Hulu":
fileName = request.url.match(/.+_(SEGMENT\d+_.+\.vtt)\?(.*)subtype=/)[1]; // Hulu 片段分型序号相同
break;
case "PrimeVideo":
case "HBOMax":
default:
fileName = null; // Amazon Prime Video HBO_Max不拆分字幕片段
break;
}
Console.log("✅ Get Subtitles FileName", `fileName: ${fileName}`);
return fileName;
} | Get Subtitles FileName
@author VirgilClyne
@param {String} url - Request URL / Subtitles URL
@param {String} platform - Platform Name
@return {String<*>} fileName | getSubtitlesFileName ( url , platform ) | javascript | DualSubs/Universal | src/Composite.Subtitles.response.js | https://github.com/DualSubs/Universal/blob/master/src/Composite.Subtitles.response.js | Apache-2.0 |
function combineText(originText, transText, ShowOnly = false, position = "Forward", lineBreak = "\n") {
let text = "";
switch (ShowOnly) {
case true:
text = transText;
break;
case false:
default:
switch (position) {
case "Forward":
default:
text = `${originText}${lineBreak}${transText}`;
break;
case "Reverse":
text = `${transText}${lineBreak}${originText}`;
break;
}
}
return text;
} | combine two text
@author VirgilClyne
@param {String} originText - original text
@param {String} transText - translate text
@param {Boolean} ShowOnly - only show translate text
@param {String} position - position
@param {String} lineBreak - line break
@return {String} combined text | combineText ( originText , transText , ShowOnly = false , position = "Forward" , lineBreak = "\n" ) | javascript | DualSubs/Universal | src/External.Lyrics.response.dev.js | https://github.com/DualSubs/Universal/blob/master/src/External.Lyrics.response.dev.js | Apache-2.0 |
function chunk(source, length) {
Console.log("☑️ Chunk Array");
let index = 0,
target = [];
while (index < source.length) target.push(source.slice(index, (index += length)));
//Console.log("✅ Chunk Array", `target: ${JSON.stringify(target)}`);
return target;
} | Chunk Array
@author VirgilClyne
@param {Array} source - source
@param {Number} length - number
@return {Array<*>} target | chunk ( source , length ) | javascript | DualSubs/Universal | src/External.Lyrics.response.dev.js | https://github.com/DualSubs/Universal/blob/master/src/External.Lyrics.response.dev.js | Apache-2.0 |
async function retry(fn, retriesLeft = 5, interval = 1000, exponential = false) {
Console.log("☑️ retry", `剩余重试次数:${retriesLeft}`, `时间间隔:${interval}ms`);
try {
const val = await fn();
return val;
} catch (error) {
if (retriesLeft) {
await new Promise(r => setTimeout(r, interval));
return retry(fn, retriesLeft - 1, exponential ? interval * 2 : interval, exponential);
} else throw new Error("❌ retry, 最大重试次数");
}
} | Retries the given function until it succeeds given a number of retries and an interval between them. They are set
by default to retry 5 times with 1sec in between. There's also a flag to make the cooldown time exponential
@link https://gitlab.com/-/snippets/1775781
@author Daniel Iñigo <[email protected]>
@param {Function} fn - Returns a promise
@param {Number} retriesLeft - Number of retries. If -1 will keep retrying
@param {Number} interval - Millis between retries. If exponential set to true will be doubled each retry
@param {Boolean} exponential - Flag for exponential back-off mode
@return {Promise<*>} | retry ( fn , retriesLeft = 5 , interval = 1000 , exponential = false ) | javascript | DualSubs/Universal | src/Translate.response.dev.js | https://github.com/DualSubs/Universal/blob/master/src/Translate.response.dev.js | Apache-2.0 |
function getPlaylistCache(url, cache, language) {
Console.log("☑️ getPlaylistCache", `language: ${language}`);
let masterPlaylistURL = "";
let subtitlesPlaylist = {};
let subtitlesPlaylistIndex = 0;
cache?.forEach((Value, Key) => {
//Console.debug(`Key: ${Key}, Value: ${JSON.stringify(Value)}`);
if (Array.isArray(Value?.[language])) {
const array = Value?.[language];
//Console.debug(`array: ${JSON.stringify(array)}`);
if (
array?.some((object, index) => {
if (url.includes(object?.URI ?? object?.OPTION?.URI ?? null)) {
subtitlesPlaylistIndex = index;
Console.debug(`subtitlesPlaylistIndex: ${subtitlesPlaylistIndex}`);
return true;
} else return false;
})
) {
masterPlaylistURL = Key;
subtitlesPlaylist = Value;
//Console.debug(`masterPlaylistURL: ${masterPlaylistURL}`, `subtitlesPlaylist: ${JSON.stringify(subtitlesPlaylist)}`);
}
}
});
Console.log("✅ getPlaylistCache", `masterPlaylistURL: ${JSON.stringify(masterPlaylistURL)}`);
return { masterPlaylistURL, subtitlesPlaylist, subtitlesPlaylistIndex };
} | Get Playlist Cache
@author VirgilClyne
@param {String} url - Request URL / Master Playlist URL
@param {Map} cache - Playlist Cache
@param {String} language - Language
@return {Promise<Object>} { masterPlaylistURL, subtitlesPlaylist, subtitlesPlaylistIndex } | getPlaylistCache ( url , cache , language ) | javascript | DualSubs/Universal | src/Manifest.response.js | https://github.com/DualSubs/Universal/blob/master/src/Manifest.response.js | Apache-2.0 |
async function setSubtitlesCache(cache, playlist, language, index = 0, platform = "Universal") {
Console.log("☑️ setSubtitlesCache", `language: ${language}, index: ${index}`);
await Promise.all(
playlist?.[language]?.map(async (val, ind, arr) => {
//Console.debug(`setSubtitlesCache, ind: ${ind}, val: ${JSON.stringify(val)}`);
if ((arr[index] && ind === index) || !arr[index]) {
// 查找字幕文件地址vtt缓存(map)
let subtitlesURLarray = cache.get(val.URL) ?? [];
//Console.debug(`setSubtitlesCache`, `subtitlesURLarray: ${JSON.stringify(subtitlesURLarray)}`);
//Console.debug(`setSubtitlesCache`, `val?.URL: ${val?.URL}`);
// 获取字幕文件地址vtt/ttml缓存(按语言)
if (subtitlesURLarray.length === 0) subtitlesURLarray = await getSubtitles(val?.URL, $request.headers, platform);
//Console.debug(`setSubtitlesCache`, `subtitlesURLarray: ${JSON.stringify(subtitlesURLarray)}`);
// 写入字幕文件地址vtt/ttml缓存到map
if (subtitlesURLarray.length !== 0) cache = cache.set(val.URL, subtitlesURLarray);
//Console.debug(`subtitlesURLarray: ${JSON.stringify(cache.get(val?.URL))}`);
Console.log("✅ setSubtitlesCache", `val?.URL: ${val?.URL}`);
}
}),
);
return cache;
} | Set Subtitles Cache
@author VirgilClyne
@param {Map} cache - Subtitles Cache
@param {Object} playlist - Subtitles Playlist Cache
@param {Array} language - Language
@param {Number} index - Subtitles Playlist Index
@param {String} platform - Steaming Media Platform
@return {Promise<Object>} { masterPlaylistURL, subtitlesPlaylist, subtitlesPlaylistIndex } | setSubtitlesCache ( cache , playlist , language , index = 0 , platform = "Universal" ) | javascript | DualSubs/Universal | src/Manifest.response.js | https://github.com/DualSubs/Universal/blob/master/src/Manifest.response.js | Apache-2.0 |
async function getSubtitles(url, headers, platform) {
Console.log("☑️ Get Subtitle *.vtt *.ttml URLs");
let subtitles = await fetch(url, { headers: headers }).then((response, error) => {
//Console.debug(`Get Subtitle *.vtt *.ttml URLs`, `response: ${JSON.stringify(response)}`);
const subtitlePlayList = M3U8.parse(response.body);
return subtitlePlayList
.filter(({ URI }) => /^.+\.((web)?vtt|ttml2?|xml|smi)(\?.+)?$/.test(URI))
.filter(({ URI }) => !URI.includes("empty"))
.filter(({ URI }) => !URI.includes("blank"))
.filter(({ URI }) => !URI.includes("default"))
.map(({ URI }) => aPath(url, URI));
}); | Get Subtitle *.vtt URLs
@author VirgilClyne
@param {String} url - VTT URL
@param {String} headers - Request Headers
@param {String} platform - Steaming Media Platform
@return {Promise<*>} | getSubtitles ( url , headers , platform ) | javascript | DualSubs/Universal | src/Manifest.response.js | https://github.com/DualSubs/Universal/blob/master/src/Manifest.response.js | Apache-2.0 |
function idx<Ti, Tv>(input: Ti, accessor: (input: Ti) => Tv): ?Tv { | Traverses properties on objects and arrays. If an intermediate property is
either null or undefined, it is instead returned. The purpose of this method
is to simplify extracting properties from a chain of maybe-typed properties.
=== EXAMPLE ===
Consider the following type:
const props: {
user: ?{
name: string,
friends: ?Array<User>,
}
};
Getting to the friends of my first friend would resemble:
props.user &&
props.user.friends &&
props.user.friends[0] &&
props.user.friends[0].friends
Instead, `idx` allows us to safely write:
idx(props, _ => _.user.friends[0].friends)
The second argument must be a function that returns one or more nested member
expressions. Any other expression has undefined behavior.
=== NOTE ===
The code below exists for the purpose of illustrating expected behavior and
is not meant to be executed. The `idx` function is used in conjunction with a
Babel transform that replaces it with better performing code:
props.user == null ? props.user :
props.user.friends == null ? props.user.friends :
props.user.friends[0] == null ? props.user.friends[0] :
props.user.friends[0].friends
All this machinery exists due to the fact that an existential operator does
not currently exist in JavaScript. | > | javascript | facebook/idx | packages/idx/src/idx.js | https://github.com/facebook/idx/blob/master/packages/idx/src/idx.js | MIT |
const createImageResizer = (width, height) => (source) => {
const resized = new PNG({ width, height, fill: true });
PNG.bitblt(source, resized, 0, 0, source.width, source.height, 0, 0);
return resized;
}; | Helper function to create reusable image resizer | createImageResizer | javascript | americanexpress/jest-image-snapshot | src/diff-snapshot.js | https://github.com/americanexpress/jest-image-snapshot/blob/master/src/diff-snapshot.js | Apache-2.0 |
const alignImagesToSameSize = (firstImage, secondImage) => {
// Keep original sizes to fill extended area later
const firstImageWidth = firstImage.width;
const firstImageHeight = firstImage.height;
const secondImageWidth = secondImage.width;
const secondImageHeight = secondImage.height;
// Calculate biggest common values
const resizeToSameSize = createImageResizer(
Math.max(firstImageWidth, secondImageWidth),
Math.max(firstImageHeight, secondImageHeight)
);
// Resize both images
const resizedFirst = resizeToSameSize(firstImage);
const resizedSecond = resizeToSameSize(secondImage);
// Fill resized area with black transparent pixels
return [
fillSizeDifference(firstImageWidth, firstImageHeight)(resizedFirst),
fillSizeDifference(secondImageWidth, secondImageHeight)(resizedSecond),
];
}; | Aligns images sizes to biggest common value
and fills new pixels with transparent pixels | alignImagesToSameSize | javascript | americanexpress/jest-image-snapshot | src/diff-snapshot.js | https://github.com/americanexpress/jest-image-snapshot/blob/master/src/diff-snapshot.js | Apache-2.0 |
var Row = module.exports = function (params) {
// Top of row, relative to container
this.top = params.top;
// Left side of row relative to container (equal to container left padding)
this.left = params.left;
// Width of row, not including container padding
this.width = params.width;
// Horizontal spacing between items
this.spacing = params.spacing;
// Row height calculation values
this.targetRowHeight = params.targetRowHeight;
this.targetRowHeightTolerance = params.targetRowHeightTolerance;
this.minAspectRatio = this.width / params.targetRowHeight * (1 - params.targetRowHeightTolerance);
this.maxAspectRatio = this.width / params.targetRowHeight * (1 + params.targetRowHeightTolerance);
// Edge case row height minimum/maximum
this.edgeCaseMinRowHeight = params.edgeCaseMinRowHeight;
this.edgeCaseMaxRowHeight = params.edgeCaseMaxRowHeight;
// Widow layout direction
this.widowLayoutStyle = params.widowLayoutStyle;
// Full width breakout rows
this.isBreakoutRow = params.isBreakoutRow;
// Store layout data for each item in row
this.items = [];
// Height remains at 0 until it's been calculated
this.height = 0;
}; | Row
Wrapper for each row in a justified layout.
Stores relevant values and provides methods for calculating layout of individual rows.
@param {Object} layoutConfig - The same as that passed
@param {Object} Initialization parameters. The following are all required:
@param params.top {Number} Top of row, relative to container
@param params.left {Number} Left side of row relative to container (equal to container left padding)
@param params.width {Number} Width of row, not including container padding
@param params.spacing {Number} Horizontal spacing between items
@param params.targetRowHeight {Number} Layout algorithm will aim for this row height
@param params.targetRowHeightTolerance {Number} Row heights may vary +/- (`targetRowHeight` x `targetRowHeightTolerance`)
@param params.edgeCaseMinRowHeight {Number} Absolute minimum row height for edge cases that cannot be resolved within tolerance.
@param params.edgeCaseMaxRowHeight {Number} Absolute maximum row height for edge cases that cannot be resolved within tolerance.
@param params.isBreakoutRow {Boolean} Is this row in particular one of those breakout rows? Always false if it's not that kind of photo list
@param params.widowLayoutStyle {String} If widows are visible, how should they be laid out?
@constructor | module.exports ( params ) | javascript | flickr/justified-layout | lib/row.js | https://github.com/flickr/justified-layout/blob/master/lib/row.js | MIT |
addItem: function (itemData) {
var newItems = this.items.concat(itemData),
// Calculate aspect ratios for items only; exclude spacing
rowWidthWithoutSpacing = this.width - (newItems.length - 1) * this.spacing,
newAspectRatio = newItems.reduce(function (sum, item) {
return sum + item.aspectRatio;
}, 0),
targetAspectRatio = rowWidthWithoutSpacing / this.targetRowHeight,
previousRowWidthWithoutSpacing,
previousAspectRatio,
previousTargetAspectRatio;
// Handle big full-width breakout photos if we're doing them
if (this.isBreakoutRow) {
// Only do it if there's no other items in this row
if (this.items.length === 0) {
// Only go full width if this photo is a square or landscape
if (itemData.aspectRatio >= 1) {
// Close out the row with a full width photo
this.items.push(itemData);
this.completeLayout(rowWidthWithoutSpacing / itemData.aspectRatio, 'justify');
return true;
}
}
}
if (newAspectRatio < this.minAspectRatio) {
// New aspect ratio is too narrow / scaled row height is too tall.
// Accept this item and leave row open for more items.
this.items.push(Object.assign({}, itemData));
return true;
} else if (newAspectRatio > this.maxAspectRatio) {
// New aspect ratio is too wide / scaled row height will be too short.
// Accept item if the resulting aspect ratio is closer to target than it would be without the item.
// NOTE: Any row that falls into this block will require cropping/padding on individual items.
if (this.items.length === 0) {
// When there are no existing items, force acceptance of the new item and complete the layout.
// This is the pano special case.
this.items.push(Object.assign({}, itemData));
this.completeLayout(rowWidthWithoutSpacing / newAspectRatio, 'justify');
return true;
}
// Calculate width/aspect ratio for row before adding new item
previousRowWidthWithoutSpacing = this.width - (this.items.length - 1) * this.spacing;
previousAspectRatio = this.items.reduce(function (sum, item) {
return sum + item.aspectRatio;
}, 0);
previousTargetAspectRatio = previousRowWidthWithoutSpacing / this.targetRowHeight;
if (Math.abs(newAspectRatio - targetAspectRatio) > Math.abs(previousAspectRatio - previousTargetAspectRatio)) {
// Row with new item is us farther away from target than row without; complete layout and reject item.
this.completeLayout(previousRowWidthWithoutSpacing / previousAspectRatio, 'justify');
return false;
} else {
// Row with new item is us closer to target than row without;
// accept the new item and complete the row layout.
this.items.push(Object.assign({}, itemData));
this.completeLayout(rowWidthWithoutSpacing / newAspectRatio, 'justify');
return true;
}
} else {
// New aspect ratio / scaled row height is within tolerance;
// accept the new item and complete the row layout.
this.items.push(Object.assign({}, itemData));
this.completeLayout(rowWidthWithoutSpacing / newAspectRatio, 'justify');
return true;
}
}, | Attempt to add a single item to the row.
This is the heart of the justified algorithm.
This method is direction-agnostic; it deals only with sizes, not positions.
If the item fits in the row, without pushing row height beyond min/max tolerance,
the item is added and the method returns true.
If the item leaves row height too high, there may be room to scale it down and add another item.
In this case, the item is added and the method returns true, but the row is incomplete.
If the item leaves row height too short, there are too many items to fit within tolerance.
The method will either accept or reject the new item, favoring the resulting row height closest to within tolerance.
If the item is rejected, left/right padding will be required to fit the row height within tolerance;
if the item is accepted, top/bottom cropping will be required to fit the row height within tolerance.
@method addItem
@param itemData {Object} Item layout data, containing item aspect ratio.
@return {Boolean} True if successfully added; false if rejected. | addItem ( itemData ) | javascript | flickr/justified-layout | lib/row.js | https://github.com/flickr/justified-layout/blob/master/lib/row.js | MIT |
isLayoutComplete: function () {
return this.height > 0;
}, | Check if a row has completed its layout.
@method isLayoutComplete
@return {Boolean} True if complete; false if not. | isLayoutComplete ( ) | javascript | flickr/justified-layout | lib/row.js | https://github.com/flickr/justified-layout/blob/master/lib/row.js | MIT |
completeLayout: function (newHeight, widowLayoutStyle) {
var itemWidthSum = this.left,
rowWidthWithoutSpacing = this.width - (this.items.length - 1) * this.spacing,
clampedToNativeRatio,
clampedHeight,
errorWidthPerItem,
roundedCumulativeErrors,
singleItemGeometry,
centerOffset;
// Justify unless explicitly specified otherwise.
if (typeof widowLayoutStyle === 'undefined' || ['justify', 'center', 'left'].indexOf(widowLayoutStyle) < 0) {
widowLayoutStyle = 'left';
}
// Clamp row height to edge case minimum/maximum.
clampedHeight = Math.max(this.edgeCaseMinRowHeight, Math.min(newHeight, this.edgeCaseMaxRowHeight));
if (newHeight !== clampedHeight) {
// If row height was clamped, the resulting row/item aspect ratio will be off,
// so force it to fit the width (recalculate aspectRatio to match clamped height).
// NOTE: this will result in cropping/padding commensurate to the amount of clamping.
this.height = clampedHeight;
clampedToNativeRatio = (rowWidthWithoutSpacing / clampedHeight) / (rowWidthWithoutSpacing / newHeight);
} else {
// If not clamped, leave ratio at 1.0.
this.height = newHeight;
clampedToNativeRatio = 1.0;
}
// Compute item geometry based on newHeight.
this.items.forEach(function (item) {
item.top = this.top;
item.width = item.aspectRatio * this.height * clampedToNativeRatio;
item.height = this.height;
// Left-to-right.
// TODO right to left
// item.left = this.width - itemWidthSum - item.width;
item.left = itemWidthSum;
// Increment width.
itemWidthSum += item.width + this.spacing;
}, this);
// If specified, ensure items fill row and distribute error
// caused by rounding width and height across all items.
if (widowLayoutStyle === 'justify') {
itemWidthSum -= (this.spacing + this.left);
errorWidthPerItem = (itemWidthSum - this.width) / this.items.length;
roundedCumulativeErrors = this.items.map(function (item, i) {
return Math.round((i + 1) * errorWidthPerItem);
});
if (this.items.length === 1) {
// For rows with only one item, adjust item width to fill row.
singleItemGeometry = this.items[0];
singleItemGeometry.width -= Math.round(errorWidthPerItem);
} else {
// For rows with multiple items, adjust item width and shift items to fill the row,
// while maintaining equal spacing between items in the row.
this.items.forEach(function (item, i) {
if (i > 0) {
item.left -= roundedCumulativeErrors[i - 1];
item.width -= (roundedCumulativeErrors[i] - roundedCumulativeErrors[i - 1]);
} else {
item.width -= roundedCumulativeErrors[i];
}
});
}
} else if (widowLayoutStyle === 'center') {
// Center widows
centerOffset = (this.width - itemWidthSum) / 2;
this.items.forEach(function (item) {
item.left += centerOffset + this.spacing;
}, this);
}
}, | Set row height and compute item geometry from that height.
Will justify items within the row unless instructed not to.
@method completeLayout
@param newHeight {Number} Set row height to this value.
@param widowLayoutStyle {String} How should widows display? Supported: left | justify | center | completeLayout ( newHeight , widowLayoutStyle ) | javascript | flickr/justified-layout | lib/row.js | https://github.com/flickr/justified-layout/blob/master/lib/row.js | MIT |
forceComplete: function (fitToWidth, rowHeight) {
// TODO Handle fitting to width
// var rowWidthWithoutSpacing = this.width - (this.items.length - 1) * this.spacing,
// currentAspectRatio = this.items.reduce(function (sum, item) {
// return sum + item.aspectRatio;
// }, 0);
if (typeof rowHeight === 'number') {
this.completeLayout(rowHeight, this.widowLayoutStyle);
} else {
// Complete using target row height.
this.completeLayout(this.targetRowHeight, this.widowLayoutStyle);
}
}, | Force completion of row layout with current items.
@method forceComplete
@param fitToWidth {Boolean} Stretch current items to fill the row width.
This will likely result in padding.
@param fitToWidth {Number} | forceComplete ( fitToWidth , rowHeight ) | javascript | flickr/justified-layout | lib/row.js | https://github.com/flickr/justified-layout/blob/master/lib/row.js | MIT |
getItems: function () {
return this.items;
} | Return layout data for items within row.
Note: returns actual list, not a copy.
@method getItems
@return Layout data for items within row. | getItems ( ) | javascript | flickr/justified-layout | lib/row.js | https://github.com/flickr/justified-layout/blob/master/lib/row.js | MIT |
function createNewRow(layoutConfig, layoutData) {
var isBreakoutRow;
// Work out if this is a full width breakout row
if (layoutConfig.fullWidthBreakoutRowCadence !== false) {
if (((layoutData._rows.length + 1) % layoutConfig.fullWidthBreakoutRowCadence) === 0) {
isBreakoutRow = true;
}
}
return new Row({
top: layoutData._containerHeight,
left: layoutConfig.containerPadding.left,
width: layoutConfig.containerWidth - layoutConfig.containerPadding.left - layoutConfig.containerPadding.right,
spacing: layoutConfig.boxSpacing.horizontal,
targetRowHeight: layoutConfig.targetRowHeight,
targetRowHeightTolerance: layoutConfig.targetRowHeightTolerance,
edgeCaseMinRowHeight: 0.5 * layoutConfig.targetRowHeight,
edgeCaseMaxRowHeight: 2 * layoutConfig.targetRowHeight,
rightToLeft: false,
isBreakoutRow: isBreakoutRow,
widowLayoutStyle: layoutConfig.widowLayoutStyle
});
} | Create a new, empty row.
@method createNewRow
@param layoutConfig {Object} The layout configuration
@param layoutData {Object} The current state of the layout
@return A new, empty row of the type specified by this layout. | createNewRow ( layoutConfig , layoutData ) | javascript | flickr/justified-layout | lib/index.js | https://github.com/flickr/justified-layout/blob/master/lib/index.js | MIT |
function addRow(layoutConfig, layoutData, row) {
layoutData._rows.push(row);
layoutData._layoutItems = layoutData._layoutItems.concat(row.getItems());
// Increment the container height
layoutData._containerHeight += row.height + layoutConfig.boxSpacing.vertical;
return row.items;
} | Add a completed row to the layout.
Note: the row must have already been completed.
@method addRow
@param layoutConfig {Object} The layout configuration
@param layoutData {Object} The current state of the layout
@param row {Row} The row to add.
@return {Array} Each item added to the row. | addRow ( layoutConfig , layoutData , row ) | javascript | flickr/justified-layout | lib/index.js | https://github.com/flickr/justified-layout/blob/master/lib/index.js | MIT |
function computeLayout(layoutConfig, layoutData, itemLayoutData) {
var laidOutItems = [],
itemAdded,
currentRow,
nextToLastRowHeight;
// Apply forced aspect ratio if specified, and set a flag.
if (layoutConfig.forceAspectRatio) {
itemLayoutData.forEach(function (itemData) {
itemData.forcedAspectRatio = true;
itemData.aspectRatio = layoutConfig.forceAspectRatio;
});
}
// Loop through the items
itemLayoutData.some(function (itemData, i) {
if (isNaN(itemData.aspectRatio)) {
throw new Error("Item " + i + " has an invalid aspect ratio");
}
// If not currently building up a row, make a new one.
if (!currentRow) {
currentRow = createNewRow(layoutConfig, layoutData);
}
// Attempt to add item to the current row.
itemAdded = currentRow.addItem(itemData);
if (currentRow.isLayoutComplete()) {
// Row is filled; add it and start a new one
laidOutItems = laidOutItems.concat(addRow(layoutConfig, layoutData, currentRow));
if (layoutData._rows.length >= layoutConfig.maxNumRows) {
currentRow = null;
return true;
}
currentRow = createNewRow(layoutConfig, layoutData);
// Item was rejected; add it to its own row
if (!itemAdded) {
itemAdded = currentRow.addItem(itemData);
if (currentRow.isLayoutComplete()) {
// If the rejected item fills a row on its own, add the row and start another new one
laidOutItems = laidOutItems.concat(addRow(layoutConfig, layoutData, currentRow));
if (layoutData._rows.length >= layoutConfig.maxNumRows) {
currentRow = null;
return true;
}
currentRow = createNewRow(layoutConfig, layoutData);
}
}
}
});
// Handle any leftover content (orphans) depending on where they lie
// in this layout update, and in the total content set.
if (currentRow && currentRow.getItems().length && layoutConfig.showWidows) {
// Last page of all content or orphan suppression is suppressed; lay out orphans.
if (layoutData._rows.length) {
// Only Match previous row's height if it exists and it isn't a breakout row
if (layoutData._rows[layoutData._rows.length - 1].isBreakoutRow) {
nextToLastRowHeight = layoutData._rows[layoutData._rows.length - 1].targetRowHeight;
} else {
nextToLastRowHeight = layoutData._rows[layoutData._rows.length - 1].height;
}
currentRow.forceComplete(false, nextToLastRowHeight);
} else {
// ...else use target height if there is no other row height to reference.
currentRow.forceComplete(false);
}
laidOutItems = laidOutItems.concat(addRow(layoutConfig, layoutData, currentRow));
layoutConfig._widowCount = currentRow.getItems().length;
}
// We need to clean up the bottom container padding
// First remove the height added for box spacing
layoutData._containerHeight = layoutData._containerHeight - layoutConfig.boxSpacing.vertical;
// Then add our bottom container padding
layoutData._containerHeight = layoutData._containerHeight + layoutConfig.containerPadding.bottom;
return {
containerHeight: layoutData._containerHeight,
widowCount: layoutConfig._widowCount,
boxes: layoutData._layoutItems
};
} | Calculate the current layout for all items in the list that require layout.
"Layout" means geometry: position within container and size
@method computeLayout
@param layoutConfig {Object} The layout configuration
@param layoutData {Object} The current state of the layout
@param itemLayoutData {Array} Array of items to lay out, with data required to lay out each item
@return {Object} The newly-calculated layout, containing the new container height, and lists of layout items | computeLayout ( layoutConfig , layoutData , itemLayoutData ) | javascript | flickr/justified-layout | lib/index.js | https://github.com/flickr/justified-layout/blob/master/lib/index.js | MIT |
module.exports = function (input, config) {
var layoutConfig = {};
var layoutData = {};
// Defaults
var defaults = {
containerWidth: 1060,
containerPadding: 10,
boxSpacing: 10,
targetRowHeight: 320,
targetRowHeightTolerance: 0.25,
maxNumRows: Number.POSITIVE_INFINITY,
forceAspectRatio: false,
showWidows: true,
fullWidthBreakoutRowCadence: false,
widowLayoutStyle: 'left'
};
var containerPadding = {};
var boxSpacing = {};
config = config || {};
// Merge defaults and config passed in
layoutConfig = Object.assign(defaults, config);
// Sort out padding and spacing values
containerPadding.top = (!isNaN(parseFloat(layoutConfig.containerPadding.top))) ? layoutConfig.containerPadding.top : layoutConfig.containerPadding;
containerPadding.right = (!isNaN(parseFloat(layoutConfig.containerPadding.right))) ? layoutConfig.containerPadding.right : layoutConfig.containerPadding;
containerPadding.bottom = (!isNaN(parseFloat(layoutConfig.containerPadding.bottom))) ? layoutConfig.containerPadding.bottom : layoutConfig.containerPadding;
containerPadding.left = (!isNaN(parseFloat(layoutConfig.containerPadding.left))) ? layoutConfig.containerPadding.left : layoutConfig.containerPadding;
boxSpacing.horizontal = (!isNaN(parseFloat(layoutConfig.boxSpacing.horizontal))) ? layoutConfig.boxSpacing.horizontal : layoutConfig.boxSpacing;
boxSpacing.vertical = (!isNaN(parseFloat(layoutConfig.boxSpacing.vertical))) ? layoutConfig.boxSpacing.vertical : layoutConfig.boxSpacing;
layoutConfig.containerPadding = containerPadding;
layoutConfig.boxSpacing = boxSpacing;
// Local
layoutData._layoutItems = [];
layoutData._awakeItems = [];
layoutData._inViewportItems = [];
layoutData._leadingOrphans = [];
layoutData._trailingOrphans = [];
layoutData._containerHeight = layoutConfig.containerPadding.top;
layoutData._rows = [];
layoutData._orphans = [];
layoutConfig._widowCount = 0;
// Convert widths and heights to aspect ratios if we need to
return computeLayout(layoutConfig, layoutData, input.map(function (item) {
if (item.width && item.height) {
return { aspectRatio: item.width / item.height };
} else {
return { aspectRatio: item };
}
}));
}; | Takes in a bunch of box data and config. Returns
geometry to lay them out in a justified view.
@method covertSizesToAspectRatios
@param sizes {Array} Array of objects with widths and heights
@return {Array} A list of aspect ratios | module.exports ( input , config ) | javascript | flickr/justified-layout | lib/index.js | https://github.com/flickr/justified-layout/blob/master/lib/index.js | MIT |
_getHttpAdapter: function (adapterName, options) {
if (adapterName === 'fetch') {
return new FetchAdapter(options);
}
}, | Return an http adapter by name
@param <string> adapterName adapter name
@return <object> | _getHttpAdapter ( adapterName , options ) | javascript | nchaulet/node-geocoder | lib/geocoderfactory.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoderfactory.js | MIT |
_getGeocoder: function (geocoderName, adapter, extra) {
if (geocoderName === 'google') {
return new GoogleGeocoder(adapter, {
clientId: extra.clientId,
apiKey: extra.apiKey,
language: extra.language,
region: extra.region,
excludePartialMatches: extra.excludePartialMatches,
channel: extra.channel
});
}
if (geocoderName === 'here') {
return new HereGeocoder(adapter, {
apiKey: extra.apiKey,
appId: extra.appId,
appCode: extra.appCode,
language: extra.language,
politicalView: extra.politicalView,
country: extra.country,
state: extra.state,
production: extra.production,
limit: extra.limit
});
}
if (geocoderName === 'agol') {
return new AGOLGeocoder(adapter, {
client_id: extra.client_id,
client_secret: extra.client_secret
});
}
if (geocoderName === 'freegeoip') {
return new FreegeoipGeocoder(adapter);
}
if (geocoderName === 'datasciencetoolkit') {
return new DataScienceToolkitGeocoder(adapter, { host: extra.host });
}
if (geocoderName === 'openstreetmap') {
return new OpenStreetMapGeocoder(adapter, {
language: extra.language,
osmServer: extra.osmServer
});
}
if (geocoderName === 'pickpoint') {
return new PickPointGeocoder(adapter, {
language: extra.language,
apiKey: extra.apiKey
});
}
if (geocoderName === 'locationiq') {
return new LocationIQGeocoder(adapter, extra.apiKey);
}
if (geocoderName === 'mapquest') {
return new MapQuestGeocoder(adapter, extra.apiKey);
}
if (geocoderName === 'mapzen') {
return new MapzenGeocoder(adapter, extra.apiKey);
}
if (geocoderName === 'openmapquest') {
return new OpenMapQuestGeocoder(adapter, extra.apiKey);
}
if (geocoderName === 'yandex') {
return new YandexGeocoder(adapter, {
apiKey: extra.apiKey,
language: extra.language,
results: extra.results,
skip: extra.skip,
kind: extra.kind,
bbox: extra.bbox,
rspn: extra.rspn
});
}
if (geocoderName === 'geocodio') {
return new GeocodioGeocoder(adapter, extra.apiKey);
}
if (geocoderName === 'opencage') {
return new OpenCageGeocoder(adapter, extra.apiKey, extra);
}
if (geocoderName === 'nominatimmapquest') {
return new NominatimMapquestGeocoder(adapter, {
language: extra.language,
apiKey: extra.apiKey
});
}
if (geocoderName === 'tomtom') {
return new TomTomGeocoder(adapter, {
apiKey: extra.apiKey,
country: extra.country,
limit: extra.limit
});
}
if (geocoderName === 'virtualearth') {
return new VirtualEarthGeocoder(adapter, { apiKey: extra.apiKey });
}
if (geocoderName === 'smartystreets') {
return new SmartyStreets(adapter, extra.auth_id, extra.auth_token);
}
if (geocoderName === 'teleport') {
return new TeleportGeocoder(adapter, extra.apiKey, extra);
}
if (geocoderName === 'opendatafrance') {
return new OpendataFranceGeocoder(adapter);
}
if (geocoderName === 'mapbox') {
return new MapBoxGeocoder(adapter, extra);
}
if (geocoderName === 'aplace') {
return new APlaceGeocoder(adapter, extra);
}
throw new Error('No geocoder provider find for : ' + geocoderName);
}, | Return a geocoder adapter by name
@param <string> adapterName adapter name
@return <object> | _getGeocoder ( geocoderName , adapter , extra ) | javascript | nchaulet/node-geocoder | lib/geocoderfactory.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoderfactory.js | MIT |
_getFormatter: function (formatterName, extra) {
if (formatterName === 'gpx') {
var GpxFormatter = require('./formatter/gpxformatter.js');
return new GpxFormatter();
}
if (formatterName === 'string') {
var StringFormatter = require('./formatter/stringformatter.js');
return new StringFormatter(extra.formatterPattern);
}
}, | Return an formatter adapter by name
@param <string> adapterName adapter name
@return <object> | _getFormatter ( formatterName , extra ) | javascript | nchaulet/node-geocoder | lib/geocoderfactory.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoderfactory.js | MIT |
getGeocoder: function (geocoderAdapter, extra) {
if (typeof geocoderAdapter === 'object') {
extra = geocoderAdapter;
geocoderAdapter = null;
}
if (!extra) {
extra = {};
}
if (extra.provider) {
geocoderAdapter = extra.provider;
}
if (!geocoderAdapter) {
geocoderAdapter = 'google';
}
const httpAdapter = this._getHttpAdapter('fetch', extra);
if (Helper.isString(geocoderAdapter)) {
geocoderAdapter = this._getGeocoder(geocoderAdapter, httpAdapter, extra);
}
var formatter = extra.formatter;
if (Helper.isString(formatter)) {
formatter = this._getFormatter(formatter, extra);
}
return new Geocoder(geocoderAdapter, formatter);
} | Return a geocoder
@param <string|object> geocoderAdapter Geocoder adapter name or adapter object
@param <array> extra Extra parameters array
@return <object> | getGeocoder ( geocoderAdapter , extra ) | javascript | nchaulet/node-geocoder | lib/geocoderfactory.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoderfactory.js | MIT |
var Geocoder = function (geocoder, formatter) {
this._geocoder = geocoder;
this._formatter = formatter;
}; | Constructor
@param <object> geocoder Geocoder Adapter
@param <object> formatter Formatter adapter or null | Geocoder ( geocoder , formatter ) | javascript | nchaulet/node-geocoder | lib/geocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder.js | MIT |
Geocoder.prototype.geocode = function (value, callback) {
return BPromise.resolve()
.bind(this)
.then(function() {
return BPromise.fromCallback(function(callback) {
this._geocoder.geocode(value, callback);
}.bind(this));
})
.then(function(data) {
return this._filter(value, data);
})
.then(function(data) {
return this._format(data);
})
.asCallback(callback);
}; | Geocode a value (address or ip)
@param <string> value Value to geocoder (address or IP)
@param <function> callback Callback method | Geocoder.prototype.geocode ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder.js | MIT |
Geocoder.prototype.reverse = function(query, callback) {
return BPromise.resolve()
.bind(this)
.then(function() {
return BPromise.fromCallback(function(callback) {
this._geocoder.reverse(query, callback);
}.bind(this));
})
.then(function(data) {
return this._format(data);
})
.asCallback(callback);
}; | Reverse geocoding
@param {lat:<number>,lon:<number>} lat: Latitude, lon: Longitude
@param {function} callback Callback method | Geocoder.prototype.reverse ( query , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder.js | MIT |
Geocoder.prototype.batchGeocode = function(values, callback) {
return BPromise.resolve()
.bind(this)
.then(function() {
return BPromise.fromCallback(function(callback) {
this._geocoder.batchGeocode(values, callback);
}.bind(this));
})
.asCallback(callback);
}; | Batch geocode
@param <array> values array of Values to geocode (address or IP)
@param <function> callback
@return promise | Geocoder.prototype.batchGeocode ( values , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder.js | MIT |
_geocode(value, callback) {
let params = this._prepareQueryString({});
let searchtext = value;
if (value.address) {
params = this._prepareQueryString(value);
searchtext = value.address;
}
const endpoint = `${this._geocodeEndpoint}/${encodeURIComponent(
searchtext
)}.json`;
this.httpAdapter.get(endpoint, params, (err, result) => {
let results = [];
results.raw = result;
if (err) {
return callback(err, results);
} else {
const view = result.features;
if (!view) {
return callback(false, results);
}
results = view.map(this._formatResult);
results.raw = result;
callback(false, results);
}
});
} | Geocode
@param <string> value Value to geocode (Address)
@param <function> callback Callback method | _geocode ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/mapboxgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/mapboxgeocoder.js | MIT |
_reverse(query, callback) {
const { lat, lon, ...other } = query;
const params = this._prepareQueryString(other);
const endpoint = `${this._geocodeEndpoint}/${encodeURIComponent(
`${lon},${lat}`
)}.json`;
this.httpAdapter.get(endpoint, params, (err, result) => {
let results = [];
results.raw = result;
if (err) {
return callback(err, results);
} else {
const view = result.features;
if (!view) {
return callback(false, results);
}
results = view.map(this._formatResult);
results.raw = result;
callback(false, results);
}
});
} | Reverse geocoding
@param {lat:<number>,lon:<number>} lat: Latitude, lon: Longitude
@param <function> callback Callback method | _reverse ( query , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/mapboxgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/mapboxgeocoder.js | MIT |
var SmartyStreets = function SmartyStreets(httpAdapter, auth_id, auth_token) {
SmartyStreets.super_.call(this, httpAdapter);
if(!auth_id && !auth_token){
throw new Error('You must specify an auth-id and auth-token!');
}
this.auth_id = auth_id;
this.auth_token = auth_token;
}; | SmartyStreets Constructor
@param <object> httpAdapter Http Adapter
@param <object> options Options | SmartyStreets ( httpAdapter , auth_id , auth_token ) | javascript | nchaulet/node-geocoder | lib/geocoder/smartystreetsgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/smartystreetsgeocoder.js | MIT |
SmartyStreets.prototype.reverse = function(lat, lng, callback) {
if (typeof this._reverse != 'function') {
throw new Error(this.constructor.name + ' doesnt support reverse geocoding!');
}
return this._reverse(lat, lng, callback);
}; | Reverse geocoding
@param <integer> lat Latittude
@param <integer> lng Longitude
@param <function> callback Callback method | SmartyStreets.prototype.reverse ( lat , lng , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/smartystreetsgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/smartystreetsgeocoder.js | MIT |
SmartyStreets.prototype.geocode = function(value, callback) {
var _this = this;
var params = {
'street': value,
'auth-id': this.auth_id,
'auth-token': this.auth_token,
'format': 'json'
};
this.httpAdapter.get(this._endpoint,params,function(err, result){
if(err) {
return callback(err);
} else {
var results = [];
result.forEach(function(result) {
results.push(_this._formatResult(result));
});
results.raw = result;
callback(false, results);
}
});
}; | Geocode
@param <string> value Value to geocode
@param <function> callback Callback method | SmartyStreets.prototype.geocode ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/smartystreetsgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/smartystreetsgeocoder.js | MIT |
var AbstractGeocoder = function(httpAdapter, options) {
if (!this.constructor.name) {
throw new Error('The Constructor must be named');
}
this.name = formatGeocoderName(this.constructor.name);
if (!httpAdapter || httpAdapter == 'undefined') {
throw new Error(this.constructor.name + ' need an httpAdapter');
}
this.httpAdapter = httpAdapter;
if (!options || options == 'undefined') {
options = {};
}
if (this.options) {
this.options.forEach(function(option) {
if (!options[option] || options[option] == 'undefined') {
options[option] = null;
}
});
}
this.options = options;
}; | AbstractGeocoder Constructor
@param <object> httpAdapter Http Adapter
@param <object> options Options | AbstractGeocoder ( httpAdapter , options ) | javascript | nchaulet/node-geocoder | lib/geocoder/abstractgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/abstractgeocoder.js | MIT |
AbstractGeocoder.prototype.batchGeocode = function(values, callback) {
if (typeof this._batchGeocode === 'function') {
this._batchGeocode(values, callback);
} else {
Promise.all(
values.map(value =>
new Promise(resolve => {
this.geocode(value, (error, value) => {
resolve({
error,
value
});
});
})
)
)
.then(data => callback(null, data));
}
}; | Batch Geocode
@param <string[]> values Valueas to geocode
@param <function> callback Callback method | AbstractGeocoder.prototype.batchGeocode ( values , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/abstractgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/abstractgeocoder.js | MIT |
FreegeoipGeocoder.prototype._geocode = function(value, callback) {
this.httpAdapter.get(this._endpoint + value , { }, function(err, result) {
if (err) {
return callback(err);
} else {
var results = [];
results.push({
'ip' : result.ip,
'countryCode' : result.country_code,
'country' : result.country_name,
'regionCode' : result.region_code,
'regionName' : result.region_name,
'city' : result.city,
'zipcode' : result.zip_code,
'timeZone' : result.time_zone,
'latitude' : result.latitude,
'longitude' : result.longitude,
'metroCode' : result.metro_code
});
results.raw = result;
callback(false, results);
}
});
}; | Geocode
@param <string> value Value to geocode (IP only)
@param <function> callback Callback method | FreegeoipGeocoder.prototype._geocode ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/freegeoipgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/freegeoipgeocoder.js | MIT |
var AGOLGeocoder = function AGOLGeocoder(httpAdapter, options) {
if (!httpAdapter || httpAdapter == 'undefined') {
throw new Error('ArcGis Online Geocoder requires a httpAdapter to be defined');
}
if (!options || options == 'undefined') {
options = {};
}
if (!options.client_id || options.client_id == 'undefined') {
options.client_id = null;
}
if (!options.client_secret || options.client_secret == 'undefined') {
options.client_secret = null;
}
if (!options.client_secret || !options.client_id) {
throw new Error('You must specify the client_id and the client_secret');
}
this.options = options;
this.httpAdapter = httpAdapter;
this.cache = {};
}; | Constructor
@param {Object} httpAdapter Http Adapter
@param {Object} options Options (language, client_id, client_secret) | AGOLGeocoder ( httpAdapter , options ) | javascript | nchaulet/node-geocoder | lib/geocoder/agolgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/agolgeocoder.js | MIT |
AGOLGeocoder.prototype.geocode = function(value, callback) {
var _this = this;
if (net.isIP(value)) {
throw new Error('The AGOL geocoder does not support IP addresses');
}
if (value instanceof Array) {
//As defined in http://resources.arcgis.com/en/help/arcgis-rest-api/#/Batch_geocoding/02r300000003000000/
throw new Error('An ArcGIS Online organizational account is required to use the batch geocoding functionality');
}
var execute = function (value,token,callback) {
var params = {
'token':token,
'f':'json',
'text':value,
'outFields': 'AddNum,StPreDir,StName,StType,City,Postal,Region,Country'
};
_this.httpAdapter.get(_this._endpoint, params, function(err, result) {
if (typeof result === 'string') { result = JSON.parse(result); }
if (err) {
return callback(err);
} else {
//This is to work around ESRI's habit of returning 200 OK for failures such as lack of authentication
if(result.error){
callback(result.error);
return null;
}
var results = [];
for(var i = 0; i < result.locations.length; i++) {
results.push(_this._formatResult(result.locations[i]));
}
results.raw = result;
callback(false, results);
}
});
};
this._getToken(function(err,token) {
if (err) {
return callback(err);
} else {
execute(value,token,callback);
}
});
}; | Geocode
@param {String} value Value to geocode (Address)
@param {Function} callback Callback method | AGOLGeocoder.prototype.geocode ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/agolgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/agolgeocoder.js | MIT |
OpendataFranceGeocoder.prototype._geocode = function(value, callback) {
var _this = this;
var params = this._getCommonParams();
if (typeof value == 'string') {
params.q = value;
} else {
if (value.address) {
params.q = value.address;
}
if (value.lat && value.lon) {
params.lat = value.lat;
params.lon = value.lon;
}
if (value.zipcode) {
params.postcode = value.zipcode;
}
if (value.type) {
params.type = value.type;
}
if (value.citycode) {
params.citycode = value.citycode;
}
if (value.limit) {
params.limit = value.limit;
}
}
this.httpAdapter.get(this._endpoint, params, function(err, result) {
if (err) {
return callback(err);
} else {
if (result.error) {
return callback(new Error(result.error));
}
var results = [];
if (result.features) {
for (var i = 0; i < result.features.length; i++) {
results.push(_this._formatResult(result.features[i]));
}
}
results.raw = result;
callback(false, results);
}
});
}; | Geocode
@param <string|object> value Value to geocode (Address or parameters, as specified at https://opendatafrance/api/)
@param <function> callback Callback method | OpendataFranceGeocoder.prototype._geocode ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/opendatafrancegeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/opendatafrancegeocoder.js | MIT |
OpendataFranceGeocoder.prototype._reverse = function(query, callback) {
var _this = this;
var params = this._getCommonParams();
for (var k in query) {
var v = query[k];
params[k] = v;
}
this.httpAdapter.get(this._endpoint_reverse , params, function(err, result) {
if (err) {
return callback(err);
} else {
if(result.error) {
return callback(new Error(result.error));
}
var results = [];
if (result.features) {
for (var i = 0; i < result.features.length; i++) {
results.push(_this._formatResult(result.features[i]));
}
}
results.raw = result;
callback(false, results);
}
});
}; | Reverse geocoding
@param {lat:<number>,lon:<number>, ...} lat: Latitude, lon: Longitude, ... see https://wiki.openstreetmap.org/wiki/Nominatim#Parameters_2
@param <function> callback Callback method | OpendataFranceGeocoder.prototype._reverse ( query , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/opendatafrancegeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/opendatafrancegeocoder.js | MIT |
OpendataFranceGeocoder.prototype._getCommonParams = function(){
var params = {};
for (var k in this.options) {
var v = this.options[k];
if (!v) {
continue;
}
if (k === 'language') {
k = 'accept-language';
}
params[k] = v;
}
return params;
}; | Prepare common params
@return <Object> common params | OpendataFranceGeocoder.prototype._getCommonParams ( ) | javascript | nchaulet/node-geocoder | lib/geocoder/opendatafrancegeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/opendatafrancegeocoder.js | MIT |
TeleportGeocoder.prototype._geocode = function(value, callback) {
var _this = this;
var params = {};
params.search = value;
params.embed = 'city:search-results/city:item/{city:country,city:admin1_division,city:urban_area}';
this.httpAdapter.get(this._cities_endpoint, params, function(err, result) {
if (err) {
return callback(err);
} else {
var results = [];
if (result) {
var searchResults = getEmbeddedPath(result, 'city:search-results') || [];
for (var i in searchResults) {
var confidence = (25 - i) / 25.0 * 10;
results.push(_this._formatResult(searchResults[i], 'city:item', confidence));
}
}
results.raw = result;
callback(false, results);
}
});
}; | Geocode
@param <string> value Value to geocode (Address)
@param <function> callback Callback method | TeleportGeocoder.prototype._geocode ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/teleportgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/teleportgeocoder.js | MIT |
TeleportGeocoder.prototype._reverse = function(query, callback) {
var lat = query.lat;
var lng = query.lon;
var suffix = lat + ',' + lng;
var _this = this;
var params = {};
params.embed = 'location:nearest-cities/location:nearest-city/{city:country,city:admin1_division,city:urban_area}';
this.httpAdapter.get(this._locations_endpoint + suffix, params, function(err, result) {
if (err) {
throw err;
} else {
var results = [];
if (result) {
var searchResults = getEmbeddedPath(result, 'location:nearest-cities') || [];
for ( var i in searchResults) {
var searchResult = searchResults[i];
var confidence = Math.max(0, 25 - searchResult.distance_km) / 25 * 10;
results.push(_this._formatResult(searchResult, 'location:nearest-city', confidence));
}
}
results.raw = result;
callback(false, results);
}
});
}; | Reverse geocoding
@param {lat:<number>,lon:<number>} lat: Latitude, lon: Longitude
@param <function> callback Callback method | TeleportGeocoder.prototype._reverse ( query , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/teleportgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/teleportgeocoder.js | MIT |
DataScienceToolkitGeocoder.prototype._endpoint = function(value) {
var ep = { };
var host = 'www.datasciencetoolkit.org';
if(this.options.host) {
host = this.options.host;
}
ep.ipv4Endpoint = 'http://' + host + '/ip2coordinates/';
ep.street2coordinatesEndpoint = 'http://' + host + '/street2coordinates/';
return net.isIPv4(value) ? ep.ipv4Endpoint : ep.street2coordinatesEndpoint;
}; | Build DSTK endpoint, allows for local DSTK installs
@param <string> value Value to geocode (Address or IPv4) | DataScienceToolkitGeocoder.prototype._endpoint ( value ) | javascript | nchaulet/node-geocoder | lib/geocoder/datasciencetoolkitgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/datasciencetoolkitgeocoder.js | MIT |
DataScienceToolkitGeocoder.prototype._geocode = function(value, callback) {
var ep = this._endpoint(value);
this.httpAdapter.get(ep + value , { }, function(err, result) {
if (err) {
return callback(err);
} else {
result = result[value];
if (!result) {
return callback(new Error('Could not geocode "' + value + '".'));
}
var results = [];
results.push({
'latitude' : result.latitude,
'longitude' : result.longitude,
'country' : result.country_name,
'city' : result.city || result.locality,
'state' : result.state || result.region,
'zipcode' : result.postal_code,
'streetName': result.street_name,
'streetNumber' : result.street_number,
'countryCode' : result.country_code
});
results.raw = result;
callback(false, results);
}
});
}; | Geocode
@param <string> value Value to geocode (Address or IPv4)
@param <function> callback Callback method | DataScienceToolkitGeocoder.prototype._geocode ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/datasciencetoolkitgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/datasciencetoolkitgeocoder.js | MIT |
var VirtualEarthGeocoder = function VirtualEarthGeocoder(httpAdapter, options) {
VirtualEarthGeocoder.super_.call(this, httpAdapter, options);
if (!this.options.apiKey || this.options.apiKey == 'undefined') {
throw new Error('You must specify an apiKey');
}
}; | Constructor
@param <object> httpAdapter Http Adapter
@param <object> options Options (language, clientId, apiKey) | VirtualEarthGeocoder ( httpAdapter , options ) | javascript | nchaulet/node-geocoder | lib/geocoder/virtualearth.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/virtualearth.js | MIT |
VirtualEarthGeocoder.prototype._reverse = function(value, callback) {
var _this = this;
var params = {
key: this.options.apiKey
};
var endpoint = this._endpoint + '/' + value.lat + ',' + value.lon;
this.httpAdapter.get(endpoint, params, function(err, result) {
if (err) {
return callback(err);
} else {
var results = [];
for(var i = 0; i < result.resourceSets[0].resources.length; i++) {
results.push(_this._formatResult(result.resourceSets[0].resources[i]));
}
results.raw = result;
callback(false, results);
}
});
} | Reverse geocoding
@param {lat:<number>, lon:<number>} lat: Latitude, lon: Longitude
@param <function> callback Callback method | VirtualEarthGeocoder.prototype._reverse ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/virtualearth.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/virtualearth.js | MIT |
var GoogleGeocoder = function GoogleGeocoder(httpAdapter, options) {
this.options = [
'language',
'apiKey',
'clientId',
'region',
'excludePartialMatches',
'channel'
];
GoogleGeocoder.super_.call(this, httpAdapter, options);
if (this.options.clientId && !this.options.apiKey) {
throw new Error('You must specify a apiKey (privateKey)');
}
if (this.options.apiKey && !httpAdapter.supportsHttps()) {
throw new Error('You must use https http adapter');
}
}; | Constructor
@param <object> httpAdapter Http Adapter
@param <object> options Options (language, clientId, apiKey, region, excludePartialMatches) | GoogleGeocoder ( httpAdapter , options ) | javascript | nchaulet/node-geocoder | lib/geocoder/googlegeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/googlegeocoder.js | MIT |
var LocationIQGeocoder = function LocationIQGeocoder(httpAdapter, apiKey) {
LocationIQGeocoder.super_.call(this, httpAdapter);
if (!apiKey || apiKey == 'undefined') {
throw new Error('LocationIQGeocoder needs an apiKey');
}
this.apiKey = querystring.unescape(apiKey);
}; | Constructor
Geocoder for LocationIQ
http://locationiq.org/#docs
@param {[type]} httpAdapter [description]
@param {String} apiKey [description] | LocationIQGeocoder ( httpAdapter , apiKey ) | javascript | nchaulet/node-geocoder | lib/geocoder/locationiqgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/locationiqgeocoder.js | MIT |
LocationIQGeocoder.prototype._geocode = function(value, callback) {
var params = this._getCommonParams();
if (typeof value === 'string') {
params.q = value;
} else {
for (var k in value) {
var v = value[k];
switch(k) {
default:
params[k] = v;
break;
// alias for postalcode
case 'zipcode':
params.postalcode = v;
break;
// alias for street
case 'address':
params.street = v;
break;
}
}
}
this._forceParams(params);
this.httpAdapter.get(this._endpoint + '/search', params,
function(err, responseData) {
if (err) {
return callback(err);
}
// when there’s no err thrown here the resulting array object always
// seemes to be defined but empty so no need to check for
// responseData.error for now
// add check if the array is not empty, as it returns an empty array from time to time
var results = [];
if (responseData.length && responseData.length > 0) {
results = responseData.map(this._formatResult).filter(function(result) {
return result.longitude && result.latitude;
});
results.raw = responseData;
}
callback(false, results);
}.bind(this));
}; | Geocode
@param {string|object} value
Value to geocode (Adress String or parameters as specified over at
http://locationiq.org/#docs)
@param {Function} callback callback method | LocationIQGeocoder.prototype._geocode ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/locationiqgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/locationiqgeocoder.js | MIT |
LocationIQGeocoder.prototype._reverse = function(query, callback) {
var params = this._getCommonParams();
for (var k in query) {
var v = query[k];
params[k] = v;
}
this._forceParams(params);
this.httpAdapter.get(this._endpoint + '/reverse', params,
function(err, responseData) {
if (err) {
return callback(err);
}
// when there’s no err thrown here the resulting array object always
// seemes to be defined but empty so no need to check for
// responseData.error for now
// locationiq always seemes to answer with a single object instead
// of an array
var results = [responseData].map(this._formatResult).filter(function(result) {
return result.longitude && result.latitude;
});
results.raw = responseData;
callback(false, results);
}.bind(this));
}; | Reverse geocoding
@param {lat:<number>,lon<number>} query lat: Latitude, lon: Longitutde and additional parameters as specified here: http://locationiq.org/#docs
@param {Function} callback Callback method | LocationIQGeocoder.prototype._reverse ( query , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/locationiqgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/locationiqgeocoder.js | MIT |
LocationIQGeocoder.prototype._forceParams = function(params) {
params.format = 'json';
params.addressdetails = '1';
}; | Adds parameters that are enforced
@param {object} params object containing the parameters | LocationIQGeocoder.prototype._forceParams ( params ) | javascript | nchaulet/node-geocoder | lib/geocoder/locationiqgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/locationiqgeocoder.js | MIT |
var APlaceGeocoder = function (httpAdapter, options) {
this.supportIPv4 = false;
this.supportIPv6 = false;
this.supportAddress = true;
APlaceGeocoder.super_.call(this, httpAdapter);
if (!this.constructor.name) {
throw new Error('The Constructor must be named');
}
this.name = formatGeocoderName(this.constructor.name);
if (!httpAdapter || httpAdapter == 'undefined') {
throw new Error(this.constructor.name + ' need an httpAdapter');
}
this.httpAdapter = httpAdapter;
if (options) {
for (var k in options) {
this.options[k] = options[k];
}
}
if (!this.options.language) {
this.options.language = 'en';
}
if (!this.options.apiKey) {
throw new Error('You must specify a apiKey (see https://aplace.io/en/documentation/general/authentication)');
}
if (this.options.apiKey && !httpAdapter.supportsHttps()) {
throw new Error('You must use https http adapter');
}
this.options = options;
}; | APlaceGeocoder Constructor
@param <object> httpAdapter Http Adapter
@param <object> options Options (language, apiKey) | APlaceGeocoder ( httpAdapter , options ) | javascript | nchaulet/node-geocoder | lib/geocoder/aplacegeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/aplacegeocoder.js | MIT |
OpenStreetMapGeocoder.prototype._geocode = function(value, callback) {
var _this = this;
var params = this._getCommonParams();
params.addressdetails = 1;
if (typeof value == 'string') {
params.q = value;
} else {
for (var k in value) {
var v = value[k];
params[k] = v;
}
}
this._forceParams(params);
this.httpAdapter.get(this._endpoint , params, function(err, result) {
if (err) {
return callback(err);
} else {
var results = [];
if(result.error) {
return callback(new Error(result.error));
}
if (result instanceof Array) {
for (var i = 0; i < result.length; i++) {
results.push(_this._formatResult(result[i]));
}
} else {
results.push(_this._formatResult(result));
}
results.raw = result;
callback(false, results);
}
});
}; | Geocode
@param <string|object> value Value to geocode (Address or parameters, as specified at https://wiki.openstreetmap.org/wiki/Nominatim#Parameters)
@param <function> callback Callback method | OpenStreetMapGeocoder.prototype._geocode ( value , callback ) | javascript | nchaulet/node-geocoder | lib/geocoder/openstreetmapgeocoder.js | https://github.com/nchaulet/node-geocoder/blob/master/lib/geocoder/openstreetmapgeocoder.js | MIT |
;(function() {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used as the semantic version number. */
var VERSION = '4.17.10';
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Error message constants. */
var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',
FUNC_ERROR_TEXT = 'Expected a function';
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used as default options for `_.truncate`. */
var DEFAULT_TRUNC_LENGTH = 30,
DEFAULT_TRUNC_OMISSION = '...';
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/** Used to indicate the type of lazy iteratees. */
var LAZY_FILTER_FLAG = 1,
LAZY_MAP_FLAG = 2,
LAZY_WHILE_FLAG = 3;
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_SAFE_INTEGER = 9007199254740991,
MAX_INTEGER = 1.7976931348623157e+308,
NAN = 0 / 0;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295,
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
asyncTag = '[object AsyncFunction]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
domExcTag = '[object DOMException]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
nullTag = '[object Null]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
proxyTag = '[object Proxy]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
undefinedTag = '[object Undefined]',
weakMapTag = '[object WeakMap]',
weakSetTag = '[object WeakSet]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to match empty string literals in compiled template source. */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; | @license
Lodash <https://lodash.com/>
Copyright JS Foundation and other contributors <https://js.foundation/>
Released under MIT license <https://lodash.com/license>
Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors | (anonymous) ( ) | javascript | NUKnightLab/sql-mysteries | scripts/lodash.js | https://github.com/NUKnightLab/sql-mysteries/blob/master/scripts/lodash.js | MIT |
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined; | The base implementation of `_.create` without support for assigning
properties to the created object.
@private
@param {Object} proto The object to inherit from.
@returns {Object} Returns the new object. | (anonymous) ( proto ) | javascript | NUKnightLab/sql-mysteries | scripts/lodash.js | https://github.com/NUKnightLab/sql-mysteries/blob/master/scripts/lodash.js | MIT |
function baseConforms(source) {
var props = keys(source);
return function(object) { | The base implementation of `_.conforms` which doesn't clone `source`.
@private
@param {Object} source The object of property predicates to conform to.
@returns {Function} Returns the new spec function. | (anonymous) ( object ) | javascript | NUKnightLab/sql-mysteries | scripts/lodash.js | https://github.com/NUKnightLab/sql-mysteries/blob/master/scripts/lodash.js | MIT |
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection); | The base implementation of `_.every` without support for iteratee shorthands.
@private
@param {Array|Object} collection The collection to iterate over.
@param {Function} predicate The function invoked per iteration.
@returns {boolean} Returns `true` if all elements pass the predicate check,
else `false` | (anonymous) ( value , index , collection ) | javascript | NUKnightLab/sql-mysteries | scripts/lodash.js | https://github.com/NUKnightLab/sql-mysteries/blob/master/scripts/lodash.js | MIT |
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value); | The base implementation of `_.filter` without support for iteratee shorthands.
@private
@param {Array|Object} collection The collection to iterate over.
@param {Function} predicate The function invoked per iteration.
@returns {Array} Returns the new filtered array. | (anonymous) ( value , index , collection ) | javascript | NUKnightLab/sql-mysteries | scripts/lodash.js | https://github.com/NUKnightLab/sql-mysteries/blob/master/scripts/lodash.js | MIT |
function parseHeadersInput(inputKey, inputOptions) {
/** @type {string}*/
const rawHeadersString = core.getInput(inputKey, inputOptions) || '';
const headerStrings = rawHeadersString
.split('\n')
.map(line => line.trim())
.filter(line => line !== '');
return headerStrings
.reduce((map, line) => {
const seperator = line.indexOf(':');
const key = line.substring(0, seperator).trim().toLowerCase();
const value = line.substring(seperator + 1).trim();
if (map.has(key)) {
map.set(key, [map.get(key), value].join(', '));
} else {
map.set(key, value);
}
return map;
}, new Map());
} | @param {string} inputKey
@param {any} inputOptions | parseHeadersInput ( inputKey , inputOptions ) | javascript | hashicorp/vault-action | src/action.js | https://github.com/hashicorp/vault-action/blob/master/src/action.js | MIT |
function parseSecretsInput(secretsInput) {
if (!secretsInput) {
return []
}
const secrets = secretsInput
.split(';')
.filter(key => !!key)
.map(key => key.trim())
.filter(key => key.length !== 0);
/** @type {SecretRequest[]} */
const output = [];
for (const secret of secrets) {
let pathSpec = secret;
let outputVarName = null;
const renameSigilIndex = secret.lastIndexOf('|');
if (renameSigilIndex > -1) {
pathSpec = secret.substring(0, renameSigilIndex).trim();
outputVarName = secret.substring(renameSigilIndex + 1).trim();
if (outputVarName.length < 1) {
throw Error(`You must provide a value when mapping a secret to a name. Input: "${secret}"`);
}
}
const pathParts = pathSpec
.split(/\s+/)
.map(part => part.trim())
.filter(part => part.length !== 0);
if (pathParts.length !== 2) {
throw Error(`You must provide a valid path and key. Input: "${secret}"`);
}
const [path, selectorQuoted] = pathParts;
/** @type {any} */
const selectorAst = jsonata(selectorQuoted).ast();
const selector = selectorQuoted.replace(new RegExp('"', 'g'), '');
if (selector !== WILDCARD && selector !== WILDCARD_UPPERCASE && (selectorAst.type !== "path" || selectorAst.steps[0].stages) && selectorAst.type !== "string" && !outputVarName) {
throw Error(`You must provide a name for the output key when using json selectors. Input: "${secret}"`);
}
let envVarName = outputVarName;
if (!outputVarName) {
outputVarName = normalizeOutputKey(selector);
envVarName = normalizeOutputKey(selector, true);
}
output.push({
path,
envVarName,
outputVarName,
selector
});
}
return output;
}
/**
* @param {string} inputKey
* @param {any} inputOptions
*/
function parseHeadersInput(inputKey, inputOptions) {
/** @type {string}*/
const rawHeadersString = core.getInput(inputKey, inputOptions) || '';
const headerStrings = rawHeadersString
.split('\n')
.map(line => line.trim())
.filter(line => line !== '');
return headerStrings
.reduce((map, line) => {
const seperator = line.indexOf(':');
const key = line.substring(0, seperator).trim().toLowerCase();
const value = line.substring(seperator + 1).trim();
if (map.has(key)) {
map.set(key, [map.get(key), value].join(', '));
} else {
map.set(key, value);
}
return map;
}, new Map());
}
module.exports = {
exportSecrets,
parseSecretsInput,
parseHeadersInput,
}; | Parses a secrets input string into key paths and their resulting environment variable name.
@param {string} secretsInput | parseSecretsInput ( secretsInput ) | javascript | hashicorp/vault-action | src/action.js | https://github.com/hashicorp/vault-action/blob/master/src/action.js | MIT |
function normalizeOutputKey(dataKey, upperCase = false) {
let outputKey = dataKey
.replace(".", "__")
.replace(new RegExp("-", "g"), "")
.replace(/[^\p{L}\p{N}_-]/gu, "");
if (upperCase) {
outputKey = outputKey.toUpperCase();
}
return outputKey;
} | Replaces any dot chars to __ and removes non-ascii charts
@param {string} dataKey
@param {boolean=} isEnvVar | normalizeOutputKey ( dataKey , upperCase = false ) | javascript | hashicorp/vault-action | src/utils.js | https://github.com/hashicorp/vault-action/blob/master/src/utils.js | MIT |
function generateJwt(privateKey, keyPassword, ttl) {
const alg = 'RS256';
const header = { alg: alg, typ: 'JWT' };
const now = rsasign.KJUR.jws.IntDate.getNow();
const payload = {
iss: 'vault-action',
iat: now,
nbf: now,
exp: now + ttl,
event: process.env.GITHUB_EVENT_NAME,
workflow: process.env.GITHUB_WORKFLOW,
sha: process.env.GITHUB_SHA,
actor: process.env.GITHUB_ACTOR,
repository: process.env.GITHUB_REPOSITORY,
ref: process.env.GITHUB_REF
};
const decryptedKey = rsasign.KEYUTIL.getKey(privateKey, keyPassword);
return rsasign.KJUR.jws.JWS.sign(alg, JSON.stringify(header), JSON.stringify(payload), decryptedKey);
} | *
Generates signed Json Web Token with specified private key and ttl
@param {string} privateKey
@param {string} keyPassword
@param {number} ttl | generateJwt ( privateKey , keyPassword , ttl ) | javascript | hashicorp/vault-action | src/auth.js | https://github.com/hashicorp/vault-action/blob/master/src/auth.js | MIT |
async function getClientToken(client, method, path, payload) {
/** @type {'json'} */
const responseType = 'json';
var options = {
json: payload,
responseType,
};
core.debug(`Retrieving Vault Token from ${path} endpoint`);
/** @type {import('got').Response<VaultLoginResponse>} */
let response;
try {
response = await client.post(`${path}`, options);
} catch (err) {
if (err instanceof got.HTTPError) {
throw Error(`failed to retrieve vault token. code: ${err.code}, message: ${err.message}, vaultResponse: ${JSON.stringify(err.response.body)}`)
} else {
throw err
}
}
if (response && response.body && response.body.auth && response.body.auth.client_token) {
core.debug('✔ Vault Token successfully retrieved');
core.startGroup('Token Info');
core.debug(`Operating under policies: ${JSON.stringify(response.body.auth.policies)}`);
core.debug(`Token Metadata: ${JSON.stringify(response.body.auth.metadata)}`);
core.endGroup();
return response.body.auth.client_token;
} else {
throw Error(`Unable to retrieve token from ${method}'s login endpoint.`);
}
} | *
Call the appropriate login endpoint and parse out the token in the response.
@param {import('got').Got} client
@param {string} method
@param {string} path
@param {any} payload | getClientToken ( client , method , path , payload ) | javascript | hashicorp/vault-action | src/auth.js | https://github.com/hashicorp/vault-action/blob/master/src/auth.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.