Rollupjs tree-shaking with typescript decorator modules - bundle

When I am using typescript decorators with modules in my script, rollupjs bundles entire modules instead of imported module.
main.js
import { outter } from './index.js';
let a = new outter();
index.js
export * from './display';
export * from './form';
display.js
export var outter = (function (_super) {
console.log();
})();
form.js
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
export var err;
(function (err) {
err[err["name"] = 0] = "name";
err[err["error"] = 1] = "error";
})(err || (err = {}));
export var formV = (function (_super) {
__extends(formV, _super);
function formV(element, options) {
_super.call(this, options, element);
}
__decorate([
Property(err.name)
], formV.prototype, "err", void 0);
return formV;
}());
The formV module is not imported in the main.js file, but it also bundled with the output file.
rollup.config.js
import nodeResolve from 'rollup-plugin-node-resolve';
export default {
entry: 'main.js',
plugins: [
nodeResolve({ jsnext: true })
],
targets: [
{ dest: 'dist/rollup.js', format: 'cjs' },
{ dest: 'dist/rollup.es.js', format: 'es' },
{ dest: 'dist/rollup.amd.js', format: 'amd' }
],
treeshake: true
};

Related

Discord Bot on Heroku not online

Hello everyone I have looked up this issue but can't find an answer to my specific problem.
So basically the bot is not turning on, it is offline. I don't know where to put the token or how to put the token. Please let me know of the problem or if you need more code/details. Thank you.
Code URL: https://github.com/Verggz/Electrolite
main.bot.js
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const discord_js_1 = __importDefault(require("discord.js"));
const builders_1 = require("#discordjs/builders");
const SlashCommand_model_1 = require("./model/SlashCommand.model");
const HelpCommand_command_1 = require("./commands/HelpCommand.command");
const fs_extra_1 = __importDefault(require("fs-extra"));
const BINFlipCommand_command_1 = require("./commands/flip/BINFlipCommand.command");
var client = new discord_js_1.default.Client({ "intents": [discord_js_1.default.Intents.FLAGS.GUILDS, discord_js_1.default.Intents.FLAGS.GUILD_MEMBERS, discord_js_1.default.Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => __awaiter(void 0, void 0, void 0, function* () {
var helpcommandbuilder = new builders_1.SlashCommandBuilder()
.setName("help")
.setDescription("Get the list of commands that Project: Scyll has.");
var binflipcommandbuilder = new builders_1.SlashCommandBuilder()
.setName("binflip")
.setDescription("Finds a BIN snipe on the auction house based on the amount of profit you can make.")
.addIntegerOption(option => option.setName("profit")
.setDescription("the amount of profit you would like to make.").setRequired(true));
SlashCommand_model_1.SlashCommand.CreateSlashCommands([helpcommandbuilder, binflipcommandbuilder]);
}));
client.on('interactionCreate', function (interaction) {
return __awaiter(this, void 0, void 0, function* () {
if (!interaction.isCommand())
return;
new HelpCommand_command_1.HelpCommand(interaction);
new BINFlipCommand_command_1.BINFlipCommand(interaction);
});
});
client.login(fs_extra_1.default.readJSONSync("./config.json").SERVER_BOT_KEY);
Another file:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SlashCommand = void 0;
const discord_js_1 = require("discord.js");
const axios = __importStar(require("axios"));
const rest_1 = require("#discordjs/rest");
const v9_1 = require("discord-api-types/v9");
const fs_extra_1 = __importDefault(require("fs-extra"));
var token = fs_extra_1.default.readJSONSync("./config.json").SERVER_BOT_KEY;
class SlashCommand {
constructor(interaction) {
this.http = axios.default;
this.interaction = interaction;
this.command = interaction.commandName;
this.purple = "#BA55D3";
this.backtick = "`";
this.gold = "#d4af37";
this.red = "#C70039";
}
CreateEmbed() {
return new discord_js_1.MessageEmbed()
.setAuthor("Project: Scyll", this.interaction.client.user.avatarURL()).setFooter("Project:Scyll 0.1.0").setTimestamp();
}
static CreateSlashCommands(commands) {
return __awaiter(this, void 0, void 0, function* () {
var clientid = (yield fs_extra_1.default.readJSON("./config.json")).SERVER_CLIENT_ID;
yield SlashCommand.REST.put(v9_1.Routes.applicationCommands(clientid), { "body": commands });
});
}
}
exports.SlashCommand = SlashCommand;
SlashCommand.REST = new rest_1.REST({ "version": "9" }).setToken(token);
Look for a config.json file and put you token there

Kendo Grid Sorting issues for numeric

I am using kendo grid to display data, but while sorting(ascending or descending) it's sorting perfectly for string values. But for numeric it's not sorting properly it's taking only first character to do sorting, not taking as string values even it's in numeric. How to solve this issue ?
You can use the gird column sortable.compare property to assign your own compare function.
Then what you are looking for is a Natural sort, like the one described here: http://web.archive.org/web/20130826203933/http://my.opera.com/GreyWyvern/blog/show.dml/1671288 and implemented here: http://www.davekoelle.com/files/alphanum.js
Here is a demo using a case insensitive version of the natural sort:
https://dojo.telerik.com/eReHUReH
function AlphaNumericCaseInsensitive(a, b) {
if (!a || a.length < 1) return -1;
var anum = Number(a);
var bnum = Number(b);
if (!isNaN(anum) && !isNaN(bnum)) {
return anum - bnum;
}
function chunkify(t) {
var tz = new Array();
var x = 0, y = -1, n = 0, i, j;
while (i = (j = t.charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >= 48 && i <= 57));
if (m !== n) {
tz[++y] = "";
n = m;
}
tz[y] += j;
}
return tz;
}
var aa = chunkify(a ? a.toLowerCase() : "");
var bb = chunkify(b ? b.toLowerCase() : "");
for (x = 0; aa[x] && bb[x]; x++) {
if (aa[x] !== bb[x]) {
var c = Number(aa[x]), d = Number(bb[x]);
if (!isNaN(c) && !isNaN(d)) {
return c - d;
} else return (aa[x] > bb[x]) ? 1 : -1;
}
}
return aa.length - bb.length;
}
var dataSource = new kendo.data.DataSource({
data: [
{ id: 1, item: "item101" },
{ id: 2, item: "item2" },
{ id: 3, item: "item11" },
{ id: 4, item: "item1" }
]
});
$("#grid").kendoGrid({
dataSource: dataSource,
sortable: true,
columns: [{
field: "item",
sortable: {
compare: function(a, b) {
return AlphaNumericCaseInsensitive(a.item, b.item);
}
}
}]
});

Found this code on a public institution's website and have some concerns. Seeking opinions

I found this code on a clients website, loaded the URL which returned the attached script. This appears to me (and I could be wrong) to be some sport of dataLayer info capture to spreadsheet auto-fill script. Naturally, what concerned my was the "userInfo", "user", "password" sections of this. I'm not overly versed in this level of code so I am reaching out here! Thanks!
! function(r, e, t) {
var n = function(e) {
return "string" == typeof e
},
o = function() {
return function(e) {
for (var n = {
strictMode: !1,
key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:#]*)(?::([^:#]*))?)?#)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:#]+:[^:#\/]*#)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:#?]*)(?::([^:#]*))?)?#)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
}, r = n.parser[n.strictMode ? "strict" : "loose"].exec(e), o = {}, t = 14; t--;) o[n.key[t]] = r[t] || "";
o[n.q.name] = {}, o[n.key[12]].replace(n.q.parser, function(e, r, t) {
r && (r = decodeURIComponent(r), o[n.q.name][r] && o[n.q.name][r].constructor === Array ? o[n.q.name][r].push(decodeURIComponent(t)) : o[n.q.name][r] ? o[n.q.name][r] = [o[n.q.name][r], decodeURIComponent(t)] : o[n.q.name][r] = decodeURIComponent(t))
});
var s = o.host.split(".");
return o.rootDomain = 2 <= s.length ? s[s.length - 2] + "." + s[s.length - 1] : "", o.href = e, o
}(r.location.href)
},
s = function() {
if (r.rl_widget_cfg) return r.rl_widget_cfg.id;
if (r.rl_siteid) return r.rl_siteid;
var e = o().queryKey.rl_siteid;
return e || ((e = localStorage.getItem("capture_previous_site_id")) || null)
},
c = e.createElement("script");
if (r.rl_widget_cfg || r.test_mode) c.src = "https://cdn.rlets.com/capture_static/mms/capture.js";
else {
var i = function() {
var e, r, t = s();
if (t && n(t) && 32 === (t = (e = t, n(e) ? !1 !== r && e.trim ? e.trim() : e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "") : e).replace(/-/g, "")).length) return "/" + t.substr(0, 3) + "/" + t.substr(3, 3) + "/" + t.substr(6, 3) + "/" + t.substr(9) + ".js"
}();
i && (c.src = "https://cdn.rlets.com/capture_configs" + i)
}
e.head.appendChild(c)
}(window, document);
cdn.rlets.com is for a tracking pixel for reachlocal.com. It's used for marketing purposes. (I've seen it used specifically as an integration with Facebook ads.)
It's minified, so hard to say exactly what it's doing, but I don't think it's malicious (any more than marketing pixels in general are).

limit input type number to 2 place of decimal in angular 2

I have a number of input boxes on a html page. I want to restrict the user from entering any numbers after 2 decimals.
Currently try to apply html 5 input Step="0.00" but doesn't work.
Any typescript solution is also ok
See demo of below directive in Plnkr.
You can achieve this using the following directive :
import { Directive, ElementRef, HostListener, Input } from '#angular/core';
#Directive({
selector: '[OnlyNumber]'
})
export class OnlyNumber {
elemRef: ElementRef
constructor(private el: ElementRef) {
this.elemRef = el
}
#Input() OnlyNumber: boolean;
#Input() DecimalPlaces: string;
#Input() minValue: string;
#Input() maxValue: string;
#HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent> event;
if (this.OnlyNumber) {
if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
}
#HostListener('keypress', ['$event']) onKeyPress(event) {
let e = <any> event
let valInFloat: number = parseFloat(e.target.value)
if(this.minValue.length) {
// (isNaN(valInFloat) && e.key === "0") - When user enters value for first time valInFloat will be NaN, e.key condition is
// because I didn't want user to enter anything below 1.
// NOTE: You might want to remove it if you want to accept 0
if( valInFloat < parseFloat(this.minValue) || (isNaN(valInFloat) && e.key === "0") ) {
e.preventDefault();
}
}
if(this.maxValue.length) {
if(valInFloat > parseFloat(this.maxValue)) {
e.preventDefault();
}
}
if (this.DecimalPlaces) {
let currentCursorPos: number = -1;
if (typeof this.elemRef.nativeElement.selectionStart == "number") {
currentCursorPos = this.elemRef.nativeElement.selectionStart;
} else {
// Probably an old IE browser
console.log("This browser doesn't support selectionStart");
}
let dotLength: number = e.target.value.replace(/[^\.]/g, '').length
// If user has not entered a dot(.) e.target.value.split(".")[1] will be undefined
let decimalLength = e.target.value.split(".")[1] ? e.target.value.split(".")[1].length : 0;
// (this.DecimalPlaces - 1) because we don't get decimalLength including currently pressed character
// currentCursorPos > e.target.value.indexOf(".") because we must allow user's to enter value before dot(.)
// Checking Backspace etc.. keys because firefox doesn't pressing them while chrome does by default
if( dotLength > 1 || (dotLength === 1 && e.key === ".") || (decimalLength > (parseInt(this.DecimalPlaces) - 1) &&
currentCursorPos > e.target.value.indexOf(".")) && ["Backspace", "ArrowLeft", "ArrowRight"].indexOf(e.key) === -1 ) {
e.preventDefault();
}
}
}
}
The HTML usage is as follows:
<input type="text" OnlyNumber="true" DecimalPlaces="2" minValue="1.00" maxValue="999999999.00">
If you find any bugs with it please let me know in the comments below.
P.S: This directive is improved work upon this answer to validate decimal points.
I got the solution using #pipe
import { Directive,Input,Inject, HostListener, ElementRef, OnInit } from "#angular/core";
const PADDING = "000000";
#Pipe({ name: "CurrencyPipe" })
export class CurrencyPipe implements PipeTransform {
transform(value: any, args: string[]): any {
var clean = value.replace(/[^-0-9\.]/g, '');
var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
if (negativeCheck[1] != undefined) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean = negativeCheck[0] + '-' + negativeCheck[1];
if (negativeCheck[0].length > 0) {
clean = negativeCheck[0];
}
}
if (decimalCheck[1] != undefined) {
decimalCheck[1] = decimalCheck[1].slice(0, 2);
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
return clean;
}
parse(value: string, fractionSize: number = 2): string {
var clean = value.replace(/[^-0-9\.]/g, '');
var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
if (negativeCheck[1] != undefined) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean = negativeCheck[0] + '-' + negativeCheck[1];
if (negativeCheck[0].length > 0) {
clean = negativeCheck[0];
}
}
if (decimalCheck[1] != undefined) {
decimalCheck[1] = decimalCheck[1].slice(0, 2);
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
return clean;
}
}
And Pipe Extends in my directive.
import { Directive, Input, Inject, HostListener, OnChanges, ElementRef, Renderer, AfterViewInit, OnInit } from "#angular/core";
import { CurrencyPipe } from '../../shared/pipe/orderby';
#Directive({ selector: "[CurrencyFormatter]" })
export class CurrencyFormatterDirective {
private el: HTMLInputElement;
constructor(
private elementRef: ElementRef,
private currencyPipe: CurrencyPipe
) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
this.el.value = this.currencyPipe.parse(this.el.value);
}
#HostListener("focus", ["$event.target.value"])
onFocus(value) {
this.el.value = this.currencyPipe.parse(value); // opossite of transform
}
#HostListener("blur", ["$event.target.value"])
onBlur(value) {
this.el.value = this.currencyPipe.parse(value);
}
#HostListener("keyup", ["$event.target.value"])
onKeyUp(value) {
this.el.value = this.currencyPipe.parse(value);
}
}
Import Directive on your component
import { CurrencyFormatterDirective } from '../../shared/directive/showOnRowHover';
import { CurrencyPipe } from '../../shared/pipe/orderby';
providers: [CurrencyPipe,
CurrencyFormatterDirective]
And Directive on your html Input
<input type="text" [(ngModel)]="invoiceDetail.InvoiceAmount" class="form-control" placeholder="Enter invoice amount"
CurrencyFormatter>
<input type='number' step='0.01' value='0.00' placeholder='0.00' />
don't use Step use step and if still you want old browser's support you can opt for javascript code for same

solve in passing parameter to jquery plugin file

I have live filter mike merritt plugin and I passing parameter to it in my inline javascript like this:
$("ul#course-group-list").LiveFilter('basic');
but it have JavaScript runtime error: Object doesn't support property or method 'LiveFilter'
jquery.livefilter plugin is:
(function (a) {
a.fn.liveFilter = function (d) {
var c = a(this);
var g;
if (a(this).is("ul")) {
g = "li"
} else {
if (a(this).is("ol")) {
g = "li"
} else {
if (a(this).is("table")) {
g = "tbody tr"
}
}
}
var e;
var b;
var f;
a("input.filter").keyup(function () {
f = a(this).val();
e = a(c).find(g + ':not(:Contains("' + f + '"))');
b = a(c).find(g + ':Contains("' + f + '")');
if (d == "basic") {
e.hide();
b.show()
} else {
if (d == "slide") {
e.slideUp(500);
b.slideDown(500)
} else {
if (d == "fade") {
e.fadeOut(400);
b.fadeIn(400)
}
}
}
});
jQuery.expr[":"].Contains = function (j, k, h) {
return jQuery(j).text().toLowerCase().indexOf(h[3].toLowerCase()) >= 0
}
}
})(jQuery);

Resources