repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
jaden-young/NWR
|
src/vscripts/addon_init.ts
|
<reponame>jaden-young/NWR
if (IsClient()) {
require("lib/client_util");
}
|
jaden-young/NWR
|
src/panorama/shared_scoreboard_updater.ts
|
<filename>src/panorama/shared_scoreboard_updater.ts
//@ts-nocheck
"use strict";
//=============================================================================
//=============================================================================
function _ScoreboardUpdater_SetTextSafe( panel, childName, textValue )
{
if ( panel === null )
return;
var childPanel = panel.FindChildInLayoutFile( childName )
if ( childPanel === null )
return;
childPanel.text = textValue;
}
//=============================================================================
//=============================================================================
function _ScoreboardUpdater_UpdatePlayerPanel( scoreboardConfig, playersContainer, playerId, localPlayerTeamId )
{
var playerPanelName = "_dynamic_player_" + playerId;
var playerPanel = playersContainer.FindChild( playerPanelName );
if ( playerPanel === null )
{
playerPanel = $.CreatePanel( "Panel", playersContainer, playerPanelName );
playerPanel.SetAttributeInt( "player_id", playerId );
playerPanel.BLoadLayout( scoreboardConfig.playerXmlName, false, false );
}
playerPanel.SetHasClass( "is_local_player", ( playerId == Game.GetLocalPlayerID() ) );
var ultStateOrTime = PlayerUltimateStateOrTime_t.PLAYER_ULTIMATE_STATE_HIDDEN; // values > 0 mean on cooldown for that many seconds
var goldValue = -1;
var isTeammate = false;
var playerInfo = Game.GetPlayerInfo( playerId );
if ( playerInfo )
{
isTeammate = ( playerInfo.player_team_id == localPlayerTeamId );
if ( isTeammate )
{
ultStateOrTime = Game.GetPlayerUltimateStateOrTime( playerId );
}
goldValue = playerInfo.player_gold;
playerPanel.SetHasClass( "player_dead", ( playerInfo.player_respawn_seconds >= 0 ) );
playerPanel.SetHasClass( "local_player_teammate", isTeammate && ( playerId != Game.GetLocalPlayerID() ) );
_ScoreboardUpdater_SetTextSafe( playerPanel, "RespawnTimer", ( playerInfo.player_respawn_seconds + 1 ) ); // value is rounded down so just add one for rounded-up
var playerPortrait = playerPanel.FindChildInLayoutFile( "HeroIcon" );
if ( playerPortrait )
{
if ( playerInfo.player_selected_hero !== "" )
{
playerPortrait.SetImage( "file://{images}/custom_game/heroes/topbar/" + playerInfo.player_selected_hero + ".png" );
}
else
{
playerPortrait.SetImage( "file://{images}/custom_game/unassigned.png" );
}
}
if ( playerInfo.player_selected_hero_id == -1 )
{
_ScoreboardUpdater_SetTextSafe( playerPanel, "HeroName", $.Localize( "#DOTA_Scoreboard_Picking_Hero" ) )
}
else
{
_ScoreboardUpdater_SetTextSafe( playerPanel, "HeroName", $.Localize( "#"+playerInfo.player_selected_hero ) )
}
var heroNameAndDescription = playerPanel.FindChildInLayoutFile( "HeroNameAndDescription" );
if ( heroNameAndDescription )
{
if ( playerInfo.player_selected_hero_id == -1 )
{
heroNameAndDescription.SetDialogVariable( "hero_name", $.Localize( "#DOTA_Scoreboard_Picking_Hero" ) );
}
else
{
heroNameAndDescription.SetDialogVariable( "hero_name", $.Localize( "#"+playerInfo.player_selected_hero ) );
}
heroNameAndDescription.SetDialogVariableInt( "hero_level", playerInfo.player_level );
}
var playerName = playerPanel.FindChildInLayoutFile( "PlayerName" );
if ( playerName )
{
playerName.text = playerInfo.player_name;
}
playerPanel.SetHasClass( "player_connection_abandoned", playerInfo.player_connection_state == DOTAConnectionState_t.DOTA_CONNECTION_STATE_ABANDONED );
playerPanel.SetHasClass( "player_connection_failed", playerInfo.player_connection_state == DOTAConnectionState_t.DOTA_CONNECTION_STATE_FAILED );
playerPanel.SetHasClass( "player_connection_disconnected", playerInfo.player_connection_state == DOTAConnectionState_t.DOTA_CONNECTION_STATE_DISCONNECTED );
var playerAvatar = playerPanel.FindChildInLayoutFile( "AvatarImage" );
if ( playerAvatar )
{
playerAvatar.steamid = playerInfo.player_steamid;
}
var playerColorBar = playerPanel.FindChildInLayoutFile( "PlayerColorBar" );
if ( playerColorBar !== null )
{
if ( GameUI.CustomUIConfig().team_colors )
{
var teamColor = GameUI.CustomUIConfig().team_colors[ playerInfo.player_team_id ];
if ( teamColor )
{
playerColorBar.style.backgroundColor = teamColor;
}
}
else
{
var playerColor = "#000000";
playerColorBar.style.backgroundColor = playerColor;
}
}
}
var playerItemsContainer = playerPanel.FindChildInLayoutFile( "PlayerItemsContainer" );
if ( playerItemsContainer )
{
var playerItems = Game.GetPlayerItems( playerId );
if ( playerItems )
{
// $.Msg( "playerItems = ", playerItems );
for ( var i = playerItems.inventory_slot_min; i < playerItems.inventory_slot_max; ++i )
{
var itemPanelName = "_dynamic_item_" + i;
var itemPanel = playerItemsContainer.FindChild( itemPanelName );
if ( itemPanel === null )
{
itemPanel = $.CreatePanel( "Image", playerItemsContainer, itemPanelName );
itemPanel.AddClass( "PlayerItem" );
}
var itemInfo = playerItems.inventory[i];
if ( itemInfo )
{
var item_image_name = "file://{images}/items/" + itemInfo.item_name.replace( "item_", "" ) + ".png"
if ( itemInfo.item_name.indexOf( "recipe" ) >= 0 )
{
item_image_name = "file://{images}/items/recipe.png"
}
itemPanel.SetImage( item_image_name );
}
else
{
itemPanel.SetImage( "" );
}
}
}
}
if ( isTeammate )
{
_ScoreboardUpdater_SetTextSafe( playerPanel, "TeammateGoldAmount", goldValue );
}
_ScoreboardUpdater_SetTextSafe( playerPanel, "PlayerGoldAmount", goldValue );
playerPanel.SetHasClass( "player_ultimate_ready", ( ultStateOrTime == PlayerUltimateStateOrTime_t.PLAYER_ULTIMATE_STATE_READY ) );
playerPanel.SetHasClass( "player_ultimate_no_mana", ( ultStateOrTime == PlayerUltimateStateOrTime_t.PLAYER_ULTIMATE_STATE_NO_MANA) );
playerPanel.SetHasClass( "player_ultimate_not_leveled", ( ultStateOrTime == PlayerUltimateStateOrTime_t.PLAYER_ULTIMATE_STATE_NOT_LEVELED) );
playerPanel.SetHasClass( "player_ultimate_hidden", ( ultStateOrTime == PlayerUltimateStateOrTime_t.PLAYER_ULTIMATE_STATE_HIDDEN) );
playerPanel.SetHasClass( "player_ultimate_cooldown", ( ultStateOrTime > 0 ) );
_ScoreboardUpdater_SetTextSafe( playerPanel, "PlayerUltimateCooldown", ultStateOrTime );
}
//=============================================================================
//=============================================================================
function _ScoreboardUpdater_UpdateTeamPanel( scoreboardConfig, containerPanel, teamDetails, teamsInfo )
{
if ( !containerPanel )
return;
var teamId = teamDetails.team_id;
// $.Msg( "_ScoreboardUpdater_UpdateTeamPanel: ", teamId );
var teamPanelName = "_dynamic_team_" + teamId;
var teamPanel = containerPanel.FindChild( teamPanelName );
if ( teamPanel === null )
{
// $.Msg( "UpdateTeamPanel.Create: ", teamPanelName, " = ", scoreboardConfig.teamXmlName );
teamPanel = $.CreatePanel( "Panel", containerPanel, teamPanelName );
teamPanel.SetAttributeInt( "team_id", teamId );
teamPanel.BLoadLayout( scoreboardConfig.teamXmlName, false, false );
var scoreboard_container = teamPanel.FindChildInLayoutFile( "FlyoutTeamData" );
if (teamId == 2){
scoreboard_container.AddClass( "ShinobiBoard" );
}
if (teamId == 3){
scoreboard_container.AddClass( "AkatBoard" );
}
}
var localPlayerTeamId = -1;
var localPlayer = Game.GetLocalPlayerInfo();
if ( localPlayer )
{
localPlayerTeamId = localPlayer.player_team_id;
}
teamPanel.SetHasClass( "local_player_team", localPlayerTeamId == teamId );
teamPanel.SetHasClass( "not_local_player_team", localPlayerTeamId != teamId );
var teamPlayers = Game.GetPlayerIDsOnTeam( teamId )
var playersContainer = teamPanel.FindChildInLayoutFile( "PlayersContainer" );
if ( playersContainer )
{
for ( var playerId of teamPlayers )
{
_ScoreboardUpdater_UpdatePlayerPanel( scoreboardConfig, playersContainer, playerId, localPlayerTeamId )
}
}
teamPanel.SetHasClass( "no_players", (teamPlayers.length == 0) )
teamPanel.SetHasClass( "one_player", (teamPlayers.length == 1) )
if ( teamsInfo.max_team_players < teamPlayers.length )
{
teamsInfo.max_team_players = teamPlayers.length;
}
_ScoreboardUpdater_SetTextSafe( teamPanel, "TeamName", $.Localize( teamDetails.team_name ) )
var teamIconPanel = teamPanel.FindChildInLayoutFile( "TeamIcon" );
if ( teamIconPanel )
{
}
if ( GameUI.CustomUIConfig().team_colors )
{
var teamColor = GameUI.CustomUIConfig().team_colors[ teamId ];
var teamColorPanel = teamPanel.FindChildInLayoutFile( "TeamColor" );
teamColor = teamColor.replace( ";", "" );
if ( teamColorPanel )
{
teamNamePanel.style.backgroundColor = teamColor + ";";
}
var teamColor_GradentFromTransparentLeft = teamPanel.FindChildInLayoutFile( "TeamColor_GradentFromTransparentLeft" );
if ( teamColor_GradentFromTransparentLeft )
{
var gradientText = 'gradient( linear, 0% 0%, 800% 0%, from( #00000000 ), to( ' + teamColor + ' ) );';
// $.Msg( gradientText );
teamColor_GradentFromTransparentLeft.style.backgroundColor = gradientText;
}
}
return teamPanel;
}
//=============================================================================
//=============================================================================
function _ScoreboardUpdater_ReorderTeam( scoreboardConfig, teamsParent, teamPanel, teamId, newPlace, prevPanel )
{
// $.Msg( "UPDATE: ", GameUI.CustomUIConfig().teamsPrevPlace );
var oldPlace = null;
if ( GameUI.CustomUIConfig().teamsPrevPlace.length > teamId )
{
oldPlace = GameUI.CustomUIConfig().teamsPrevPlace[ teamId ];
}
GameUI.CustomUIConfig().teamsPrevPlace[ teamId ] = newPlace;
if ( newPlace != oldPlace )
{
// $.Msg( "Team ", teamId, " : ", oldPlace, " --> ", newPlace );
teamPanel.RemoveClass( "team_getting_worse" );
teamPanel.RemoveClass( "team_getting_better" );
if ( newPlace > oldPlace )
{
teamPanel.AddClass( "team_getting_worse" );
}
else if ( newPlace < oldPlace )
{
teamPanel.AddClass( "team_getting_better" );
}
}
teamsParent.MoveChildAfter( teamPanel, prevPanel );
}
// sort / reorder as necessary
function compareFunc( a, b ) // GameUI.CustomUIConfig().sort_teams_compare_func;
{
if ( a.team_score < b.team_score )
{
return 1; // [ B, A ]
}
else if ( a.team_score > b.team_score )
{
return -1; // [ A, B ]
}
else
{
return 0;
}
};
function stableCompareFunc( a, b )
{
var unstableCompare = compareFunc( a, b );
if ( unstableCompare != 0 )
{
return unstableCompare;
}
if ( GameUI.CustomUIConfig().teamsPrevPlace.length <= a.team_id )
{
return 0;
}
if ( GameUI.CustomUIConfig().teamsPrevPlace.length <= b.team_id )
{
return 0;
}
// $.Msg( GameUI.CustomUIConfig().teamsPrevPlace );
var a_prev = GameUI.CustomUIConfig().teamsPrevPlace[ a.team_id ];
var b_prev = GameUI.CustomUIConfig().teamsPrevPlace[ b.team_id ];
if ( a_prev < b_prev ) // [ A, B ]
{
return -1; // [ A, B ]
}
else if ( a_prev > b_prev ) // [ B, A ]
{
return 1; // [ B, A ]
}
else
{
return 0;
}
};
//=============================================================================
//=============================================================================
function _ScoreboardUpdater_UpdateAllTeamsAndPlayers( scoreboardConfig, teamsContainer )
{
// $.Msg( "_ScoreboardUpdater_UpdateAllTeamsAndPlayers: ", scoreboardConfig );
var teamsList = [];
for ( var teamId of Game.GetAllTeamIDs() )
{
teamsList.push( Game.GetTeamDetails( teamId ) );
}
// update/create team panels
var teamsInfo = { max_team_players: 0 };
var panelsByTeam = [];
for ( var i = 0; i < teamsList.length; ++i )
{
if (teamsList[i].team_id != 6){
var teamPanel = _ScoreboardUpdater_UpdateTeamPanel( scoreboardConfig, teamsContainer, teamsList[i], teamsInfo );
if ( teamPanel )
{
panelsByTeam[ teamsList[i].team_id ] = teamPanel;
}
}
}
if ( teamsList.length > 1 )
{
// $.Msg( "panelsByTeam: ", panelsByTeam );
// sort
if ( scoreboardConfig.shouldSort )
{
teamsList.sort( stableCompareFunc );
}
// $.Msg( "POST: ", teamsAndPanels );
// reorder the panels based on the sort
var prevPanel = panelsByTeam[ teamsList[0].team_id ];
for ( var i = 0; i < teamsList.length; ++i )
{
var teamId = teamsList[i].team_id;
if (teamId != 6){
var teamPanel = panelsByTeam[ teamId ];
_ScoreboardUpdater_ReorderTeam( scoreboardConfig, teamsContainer, teamPanel, teamId, i, prevPanel );
prevPanel = teamPanel;
}
}
// $.Msg( GameUI.CustomUIConfig().teamsPrevPlace );
}
// $.Msg( "END _ScoreboardUpdater_UpdateAllTeamsAndPlayers: ", scoreboardConfig );
}
//=============================================================================
//=============================================================================
function ScoreboardUpdater_InitializeScoreboard( scoreboardConfig, scoreboardPanel )
{
GameUI.CustomUIConfig().teamsPrevPlace = [];
if ( typeof(scoreboardConfig.shouldSort) === 'undefined')
{
// default to true
scoreboardConfig.shouldSort = false;
}
_ScoreboardUpdater_UpdateAllTeamsAndPlayers( scoreboardConfig, scoreboardPanel );
return { "scoreboardConfig": scoreboardConfig, "scoreboardPanel":scoreboardPanel }
}
//=============================================================================
//=============================================================================
function ScoreboardUpdater_SetScoreboardActive( scoreboardHandle, isActive )
{
if ( scoreboardHandle.scoreboardConfig === null || scoreboardHandle.scoreboardPanel === null )
{
return;
}
if ( isActive )
{
_ScoreboardUpdater_UpdateAllTeamsAndPlayers( scoreboardHandle.scoreboardConfig, scoreboardHandle.scoreboardPanel );
}
}
//=============================================================================
//=============================================================================
function ScoreboardUpdater_GetTeamPanel( scoreboardHandle, teamId )
{
if ( scoreboardHandle.scoreboardPanel === null )
{
return;
}
if (teamId != 6){
var teamPanelName = "_dynamic_team_" + teamId;
return scoreboardHandle.scoreboardPanel.FindChild( teamPanelName );
}else{
return;
}
}
//=============================================================================
//=============================================================================
function ScoreboardUpdater_GetSortedTeamInfoList( scoreboardHandle )
{
var teamsList = [];
for ( var teamId of Game.GetAllTeamIDs() )
{
teamsList.push( Game.GetTeamDetails( teamId ) );
}
if ( teamsList.length > 1 )
{
teamsList.sort( stableCompareFunc );
}
return teamsList;
}
|
jaden-young/NWR
|
src/vscripts/modifiers/modifier_generic_custom_indicator.d.ts
|
interface modifier_generic_custom_indicator extends CDOTA_Modifier_Lua {
Register(loc: Vector): void;
}
|
jaden-young/NWR
|
src/panorama/better_cooldown.ts
|
//@ts-nocheck
const basePanel = $.GetContextPanel().GetParent().GetParent().GetParent();
let x = basePanel.FindChildTraverse('HUDElements');
x = x.FindChildTraverse('lower_hud');
x = x.FindChildTraverse('center_with_stats');
x = x.FindChildTraverse('center_block');
x = x.FindChildTraverse('AbilitiesAndStatBranch');
const abilities = x.FindChildTraverse('abilities');
//Set this higher if the "wiggle is too much"
var MAX_CONSECUTIV = 10;
var abilityState = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var abilityData = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined];
var lastSelected = undefined;
//Check if selected units ability goes on cooldown
$.RegisterForUnhandledEvent("StyleClassesChanged", (panel) => {
if (panel === null) return;
const abilityIndex = GetAbilityIndexFromPanel(panel);
if (abilityIndex >= 0) {
if (abilityState[abilityIndex] > 0) {
return;
}
const abilityPanel = FindAbilityPanelByIndex(abilityIndex);
if (abilityPanel) {
$.Msg("Ability activated!");
const abilityImage = abilityPanel.FindChildTraverse("AbilityImage")
const abilityID = abilityImage.contextEntityIndex;
const cooldownPanel = abilityPanel.FindChild("Cooldown");
const cooldown = Abilities.GetCooldownTimeRemaining(abilityID);
if (cooldown > 0) {
abilityState[abilityIndex] = 1;
abilityData[abilityIndex] = [abilityID, cooldownPanel, cooldown, Abilities.GetCooldownLength(abilityID), 0];
OverwriteOverlay(abilityIndex);
}
}
}
});
//Get the ability index (not ability id), if the panel is an ability panel and on cooldown
function GetAbilityIndexFromPanel(panel) {
if (panel.paneltype === "DOTAAbilityPanel" && panel.BHasClass("in_cooldown")) {
const parent = panel.GetParent();
if (parent !== undefined && parent.id === "abilities") {
return parseInt(panel.id.slice(-1), 10);
}
}
return -1;
}
//Checks if selected unit has changed and checks for abilities on cooldown
function CheckAbilities() {
const mainSelected = Players.GetLocalPlayerPortraitUnit();
let reCheck = false;
if (mainSelected !== lastSelected) {
abilityState = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
abilityData = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined];
reCheck = true;
}
lastSelected = mainSelected;
if (reCheck) {
for (let i = 0; i < 10; i++) {
const abilityPanel = FindAbilityPanelByIndex(i);
if (abilityPanel) {
const abilityImage = abilityPanel.FindChildTraverse("AbilityImage")
const abilityID = abilityImage.contextEntityIndex;
const cooldownPanel = abilityPanel.FindChildTraverse("Cooldown");
const cooldown = Abilities.GetCooldownTimeRemaining(abilityID);
if (cooldown && cooldown > 0) {
abilityState[i] = 1;
abilityData[i] = [abilityID, cooldownPanel, cooldown, Abilities.GetCooldownLength(abilityID), 0];
OverwriteOverlay(i);
}
}
}
} else if (abilityState.includes(1)) {
for (let i = 0; i < 10; i++) {
if (abilityState[i] == 1) {
OverwriteOverlay(i);
}
}
}
$.Schedule(1/60, CheckAbilities)
}
//Find the ability panel for this index
function FindAbilityPanelByIndex(index) {
const abilityPanel = abilities.FindChild("Ability" + index);
if (abilityPanel === null) {return false;}
const abilityButtonAndLevel = abilityPanel.FindChild("ButtonAndLevel");
const abilityLevelUpTab = abilityButtonAndLevel.FindChild("ButtonWithLevelUpTab");
const abilityButtonWell = abilityLevelUpTab.FindChild("ButtonWell");
const abilityButtonSize = abilityButtonWell.FindChild("ButtonSize");
return abilityButtonSize.FindChild("AbilityButton");
}
//Called multiple times a second; updates the cooldown visualizer
function OverwriteOverlay(index) {
const data = abilityData[index];
let cooldowns = GetCooldowns(index);
if (cooldowns) {
const percentage = cooldowns[0];
const currentCD = cooldowns[1];
const overlay = ReplaceOverlay(data[1]);
const timer = ReplaceTimer(data[1]);
if (percentage > 1) {
percentage = 1;
}
const degrees = -360 * percentage;
overlay.style.clip = "radial( 50.0% 50.0%, 0.0deg, " + degrees + "deg)";
timer.text = Math.ceil(currentCD);
} else {
if (abilityState[index] == 1) {
abilityState[index] = 0;
abilityData[index] = undefined;
}
}
}
//Calculated the current fill percentage
function GetCooldowns(index) {
const mainSelected = Players.GetLocalPlayerPortraitUnit();
let data = abilityData[index];
if (data[0] !== undefined) {
let maxCD = Abilities.GetCooldown(data[0]) * GetCooldownReduction(mainSelected);
if (maxCD === 0) {
return false;
}
let curCD = Abilities.GetCooldownTimeRemaining(data[0]);
if (curCD > maxCD) {
maxCD = data[3];
}
let consecutiv = data[4];
if (curCD > data[2]) {
abilityData[index][4] = consecutiv + 1;
if (consecutiv <= MAX_CONSECUTIV - 1) {
let ratio = data[2] / maxCD;
return [ratio, data[2]];
}
} else if (consecutiv < MAX_CONSECUTIV) {
abilityData[index][4] = 0;
}
abilityData[index][2] = curCD
if (curCD === 0) {
return [0, 0];
}
let ratio = curCD / maxCD;
return [ratio, curCD];
}
return false;
}
//Adds the custom cooldown overlay and hides the default one
function ReplaceOverlay(cdPanel) {
let overlay = cdPanel.FindChildTraverse("CooldownOverlay");
if (overlay) {
overlay.style.opacity = "0";
}
let newOverlay = cdPanel.FindChildTraverse("NewCooldownOverlay");
if (newOverlay === undefined || !newOverlay) {
newOverlay = $.CreatePanel("Panel", $.GetContextPanel(), "NewCooldownOverlay");
newOverlay.SetParent(cdPanel);
newOverlay.style.width = "100%";
newOverlay.style.height = "100%";
newOverlay.style.backgroundColor = "#000000dc";
newOverlay.hittest = false;
let child1 = cdPanel.GetChild(1);
let child2 = cdPanel.GetChild(2);
cdPanel.MoveChildAfter(child1, child2);
} else {
newOverlay.style.opacity = "1";
}
return newOverlay;
}
//Adds the custom cooldown timer and hides the default one
function ReplaceTimer(cdPanel) {
let timer = cdPanel.FindChildTraverse("CooldownTimer");
if (timer) {
timer.style.opacity = "0";
}
let newTimer = cdPanel.FindChildTraverse("NewCooldownTimer");
if (newTimer === undefined || !newTimer) {
newTimer = $.CreatePanel("Label", $.GetContextPanel(), "NewCooldownTimer");
newTimer.SetParent(cdPanel);
newTimer.AddClass("MonoNumbersFont")
newTimer.style.width = "100%";
newTimer.style.color = "white";
newTimer.style.fontSize = "28px";
newTimer.style.textShadow = "0px 0px 6px 6 #000000";
newTimer.style.textAlign = "center";
newTimer.style.verticalAlign = "center";
newTimer.style.textOverflow = "shrink";
newTimer.hittest = false;
newTimer.text = timer.text;
} else {
newTimer.style.opacity = "1";
}
return newTimer;
}
//Receives the cdr from custom nettable entries
function GetCooldownReduction(unitID) {
let table = CustomNetTables.GetTableValue("better_cooldowns_cdr", unitID.toString())
if (table) {
return parseFloat(table["cdr"]);
}
return 1;
}
//Start the checker
CheckAbilities();
|
jaden-young/NWR
|
src/vscripts/components/barebones/eventtest.d.ts
|
declare interface EventTest {
StartEventTest(): void;
}
declare var EventTest: EventTest;
|
jaden-young/NWR
|
src/vscripts/components/barebones/physics.d.ts
|
<reponame>jaden-young/NWR
/** @noSelfInFile */
declare interface PhysicsUnit extends CDOTA_BaseNPC {
//TODO: this interface is huge
}
declare function IsPhysicsUnit(unit: CDOTA_BaseNPC): unit is PhysicsUnit;
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/madara/madara_innate_passive.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class madara_innate_passive extends BaseAbility
{
OnUpgrade(): void {
//Should refresh modifier on eanch upgrade
let caster = this.GetCaster()
caster.FindModifierByName(this.GetIntrinsicModifierName())?.ForceRefresh()
let counter_modifier = caster.FindModifierByName("modifier_madara_innate_passive_buff_counter")
if(counter_modifier){
(counter_modifier as modifier_madara_innate_passive_buff_counter).UpdateNumbers()
}
}
GetIntrinsicModifierName(): string {
return "modifier_madara_innate_passive_intrinsic"
}
}
@registerModifier()
export class modifier_madara_innate_passive_intrinsic extends BaseModifier
{
IsHidden(): boolean {
return true;
}
IsDebuff(): boolean {
return false;
}
IsPurgable(): boolean {
return false;
}
IsPermanent(): boolean {
return false
}
DeclareFunctions(){
return [ModifierFunction.ON_ATTACK_LANDED]
}
OnAttackLanded(event: ModifierAttackEvent){
if(event.target !== this.GetParent()){return}
if(event.attacker.GetTeam() === this.GetParent().GetTeam()){return}
// this.ApplyStack()
let parent = this.GetParent()
let ability = this.GetAbility()
if(ability){
let stack_duration = ability.GetSpecialValueFor("stack_duration_base") + (ability.GetSpecialValueFor("stack_duration_per_level_bonus") + (ability.GetLevel() - 1))
print(stack_duration)
parent.AddNewModifier(parent, ability, "modifier_madara_innate_passive_buff", {duration: stack_duration})
}
}
}
@registerModifier()
export class modifier_madara_innate_passive_buff extends BaseModifier
{
IsHidden(): boolean {
return true;
}
IsDebuff(): boolean {
return false;
}
IsPurgable(): boolean {
return false;
}
GetAttributes(): ModifierAttribute {
return ModifierAttribute.MULTIPLE
}
OnCreated(params: object): void {
let parent = this.GetParent()
let ability = this.GetAbility()
if(!IsServer()){return}
if(!ability){return}
let max_stacks = ability.GetSpecialValueFor("max_stacks_base") + (ability.GetSpecialValueFor("max_stacks_per_level_bonus") + (ability.GetLevel() - 1))
let stack_duration = ability.GetSpecialValueFor("stack_duration_base") + (ability.GetSpecialValueFor("stack_duration_per_level_bonus") + (ability.GetLevel() - 1))
if(parent.HasModifier("modifier_madara_innate_passive_buff_counter")){
let counter_modifier = parent.FindModifierByName("modifier_madara_innate_passive_buff_counter")
if(!counter_modifier){return}
let current_stacks = counter_modifier.GetStackCount()
if(current_stacks === max_stacks){
let buff_modifiers = parent.FindAllModifiersByName("modifier_madara_innate_passive_buff")
buff_modifiers[0].Destroy()
counter_modifier.SetDuration(stack_duration, true)
counter_modifier.IncrementStackCount()
}else{
counter_modifier.IncrementStackCount()
counter_modifier.SetDuration(stack_duration, true)
}
}else{
let new_counter_modifier = parent.AddNewModifier(parent, ability,"modifier_madara_innate_passive_buff_counter", {duration: stack_duration})
new_counter_modifier.SetStackCount(1)
}
}
OnDestroy(): void {
if(!IsServer()){return}
let parent = this.GetParent()
let ability = this.GetAbility()
if(!ability){return}
let max_stacks = ability.GetSpecialValueFor("max_stacks_base") + (ability.GetSpecialValueFor("max_stacks_per_level_bonus") + (ability.GetLevel() - 1))
let stack_duration = ability.GetSpecialValueFor("stack_duration_base") + (ability.GetSpecialValueFor("stack_duration_per_level_bonus") + (ability.GetLevel() - 1))
let counter_modifier = parent.FindModifierByName("modifier_madara_innate_passive_buff_counter")
if(!counter_modifier){return}
if(counter_modifier.GetStackCount() === 1){
parent.RemoveModifierByName("modifier_madara_innate_passive_buff_counter")
}else{
counter_modifier.DecrementStackCount()
}
}
}
@registerModifier()
export class modifier_madara_innate_passive_buff_counter extends BaseModifier
{
spell_damage_bonus_per_stack: number = 0
health_regen_per_stack: number = 0
IsHidden(): boolean {
return false;
}
IsDebuff(): boolean {
return false;
}
IsPurgable(): boolean {
return false;
}
UpdateNumbers(){
let ability = this.GetAbility()
if(!ability){return}
this.spell_damage_bonus_per_stack = ability.GetSpecialValueFor("spell_damage_bonus_per_stack")
this.health_regen_per_stack = ability.GetSpecialValueFor("health_regen_per_stack_base") + (ability.GetSpecialValueFor("health_regen_per_stack_per_level_bonus") * (ability.GetLevel() - 1))
}
OnCreated(): void {
this.UpdateNumbers()
}
DeclareFunctions(){
return [ModifierFunction.HEALTH_REGEN_CONSTANT,
ModifierFunction.SPELL_AMPLIFY_PERCENTAGE]
}
GetModifierConstantHealthRegen(){
return this.GetStackCount() * this.health_regen_per_stack
}
GetModifierSpellAmplify_Percentage(){
return this.GetStackCount() * this.spell_damage_bonus_per_stack
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/sai/sai_super_god_drawing.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
interface SuperGodDrawingAbility extends CDOTABaseAbility
{
agyo?: CDOTA_BaseNPC;
ungyo?: CDOTA_BaseNPC;
}
@registerAbility()
export class sai_super_god_drawing extends BaseAbility {
agyo?: CDOTA_BaseNPC;
ungyo?: CDOTA_BaseNPC;
/****************************************/
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/sai/sai_super_god_drawing_spawn.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/sai/game_sounds_sai.vsndevts", context);
PrecacheResource("soundfile", "soundevents/heroes/sai/game_sounds_vo_sai.vsndevts", context);
}
/****************************************/
GetIntrinsicModifierName(): string {
return "modifier_sai_super_god_drawing";
}
/****************************************/
OnAbilityPhaseStart(): boolean {
EmitSoundOn("Hero_Sai.SuperGodDrawing.PreCast", this.GetCaster());
EmitSoundOn("VO_Hero_Sai.SuperGodDrawing.Cast", this.GetCaster());
return true
}
/****************************************/
OnSpellStart(): void {
let caster = this.GetCaster();
let level = this.GetLevel();
let remote_ability = caster.FindAbilityByName("sai_kamis_strength_remote");
let right_pos = caster.GetAbsOrigin() + caster.GetRightVector() * 150 as Vector;
let left_pos = caster.GetAbsOrigin() - caster.GetRightVector() * 150 as Vector;
if (this.agyo && !this.agyo.IsNull() && this.agyo.IsAlive()) this.agyo.ForceKill(false);
if (this.ungyo && !this.ungyo.IsNull() && this.ungyo.IsAlive()) this.ungyo.ForceKill(false);
CreateUnitByNameAsync("npc_dota_sai_agyo" + level, right_pos, true, caster, caster, caster.GetTeamNumber(), (unit) => this.SetupUnit(unit, true));
CreateUnitByNameAsync("npc_dota_sai_ungyo" + level, left_pos, true, caster, caster, caster.GetTeamNumber(), (unit) => this.SetupUnit(unit, false));
if (remote_ability) Timers.CreateTimer(0.2, () => remote_ability!.SetActivated(true));
EmitSoundOn("Hero_Sai.SuperGodDrawing.Cast", caster);
}
/****************************************/
SetupUnit(unit: CDOTA_BaseNPC, is_agyo: boolean) {
let caster = this.GetCaster();
let armor = this.GetSpecialValueFor("armor") + caster.FindTalentValue("special_bonus_sai_4");
unit.SetPhysicalArmorBaseValue(armor);
unit.SetControllableByPlayer(caster.GetPlayerOwnerID(), true);
unit.SetForwardVector(caster.GetForwardVector() * 1000 as Vector);
if (caster.HasTalent("special_bonus_sai_5")) {
unit.AddAbility("special_bonus_sai_5").SetLevel(1);
}
if (is_agyo) this.agyo = unit;
else this.ungyo = unit;
ParticleManager.ReleaseParticleIndex(
ParticleManager.CreateParticle("particles/units/heroes/sai/sai_super_god_drawing_spawn.vpcf", ParticleAttachment.ABSORIGIN, unit)
);
}
}
@registerModifier()
export class modifier_sai_super_god_drawing extends BaseModifier
{
IsHidden(): boolean {return true}
IsPurgable(): boolean {return false}
RemoveOnDeath(): boolean {return false}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.ON_DEATH,
]}
/****************************************/
OnDeath(event: ModifierInstanceEvent): void {
if (!IsServer()) return;
let ability = this.GetAbility() as SuperGodDrawingAbility;
let remote_ability = this.GetParent().FindAbilityByName("sai_kamis_strength_remote");
if (!remote_ability || !ability?.IsTrained()) return;
let agyo = ability.agyo!;
let ungyo = ability.ungyo!;
if ((!agyo || agyo.IsNull() || !agyo.IsAlive()) && (!ungyo || ungyo.IsNull() || !ungyo.IsAlive())) {
if (remote_ability.IsActivated()) remote_ability.SetActivated(false);
}
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/shisui/shisui_kotoamatsukami.ts
|
<reponame>jaden-young/NWR
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class shisui_kotoamatsukami extends BaseAbility {
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/shisui/shisui_kotoamatsukami.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/shisui/game_sounds_shisui.vsndevts", context);
PrecacheResource("soundfile", "soundevents/heroes/shisui/game_sounds_vo_shisui.vsndevts", context);
}
/****************************************/
GetCastRange(location: Vector, target: CDOTA_BaseNPC | undefined): number {
return this.GetSpecialValueFor("radius");
}
/****************************************/
OnSpellStart(): void {
let caster = this.GetCaster();
caster.AddNewModifier(caster, this, "modifier_shisui_kotoamatsukami", {duration: this.GetSpecialValueFor("buff_duration")});
if (caster.HasTalent("special_bonus_shisui_4")) {
caster.AddNewModifier(caster, this, "modifier_shisui_kotoamatsukami_invisibility", {duration: this.GetSpecialValueFor("buff_duration")});
EmitSoundOn("DOTA_Item.InvisibilitySword.Activate", caster);
}
EmitSoundOn("VO_Hero_Shisui.Koto.Cast", caster);
EmitSoundOn("Hero_Shisui.Kotoamatsukami.Cast", caster);
}
}
@registerModifier()
export class modifier_shisui_kotoamatsukami extends BaseModifier
{
radius?: number;
hypno_duration?: number;
/****************************************/
IsPurgable(): boolean {return false}
RemoveOnDeath(): boolean {return true}
/****************************************/
OnCreated(params: Object): void {
let ability = this.GetAbility()!;
let parent = this.GetParent();
this.radius = ability.GetSpecialValueFor("radius");
this.hypno_duration = ability.GetSpecialValueFor("hypno_duration");
if (!IsServer()) return;
let haste_fx = ParticleManager.CreateParticle("particles/units/heroes/shisui/shisui_kotoamatsukami_haste.vpcf", ParticleAttachment.ABSORIGIN_FOLLOW, parent)
ParticleManager.SetParticleControlEnt(haste_fx, 1, parent, ParticleAttachment.ABSORIGIN_FOLLOW, "attach_hitloc", parent.GetAbsOrigin(), true)
ParticleManager.SetParticleControlEnt(haste_fx, 2, parent, ParticleAttachment.POINT_FOLLOW, "attach_eye_right", parent.GetAbsOrigin(), true)
ParticleManager.SetParticleControlEnt(haste_fx, 3, parent, ParticleAttachment.ABSORIGIN_FOLLOW, "attach_hitloc", parent.GetAbsOrigin(), true)
ParticleManager.SetParticleControlEnt(haste_fx, 10, parent, ParticleAttachment.ABSORIGIN_FOLLOW, "attach_hitloc", parent.GetAbsOrigin(), true)
this.AddParticle(haste_fx, false, false, -1, false, false)
}
OnDestroy(): void {
if (!IsServer()) return;
let caster = this.GetCaster() as CDOTA_BaseNPC;
let ability = this.GetAbility();
let enemies = FindUnitsInRadius(
caster.GetTeamNumber(),
caster.GetAbsOrigin(),
undefined,
this.radius!,
ability!.GetAbilityTargetTeam(),
ability!.GetAbilityTargetType(),
UnitTargetFlags.NONE,
FindOrder.ANY,
false
);
enemies.forEach(enemy => {
enemy.AddNewModifier(caster, ability, "modifier_shisui_kotoamatsukami_debuff", {duration: this.hypno_duration});
});
EmitSoundOn("Hero_Shisui.Kotoamatsukami.Trigger", caster);
EmitSoundOn("VO_Hero_Shisui.Koto.Fire", caster);
}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.MOVESPEED_ABSOLUTE_MIN
]}
/****************************************/
GetModifierMoveSpeed_AbsoluteMin(): number {
return 550;
}
}
@registerModifier()
export class modifier_shisui_kotoamatsukami_invisibility extends BaseModifier
{
IsPurgable(): boolean {return false}
RemoveOnDeath(): boolean {return true}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.INVISIBILITY_LEVEL,
ModifierFunction.ON_ATTACK_LANDED,
ModifierFunction.ON_ABILITY_EXECUTED
]}
/****************************************/
CheckState(): Partial<Record<ModifierState, boolean>> {
return {
[ModifierState.INVISIBLE]: true,
[ModifierState.NO_UNIT_COLLISION]: true
};
}
/****************************************/
GetModifierInvisibilityLevel(): number {
return 1
}
/****************************************/
OnAttackLanded(event: ModifierAttackEvent): void {
if (!IsServer()) return;
if (event.attacker != this.GetParent()) return;
this.Destroy();
}
/****************************************/
OnAbilityExecuted(event: ModifierAbilityEvent): void {
if (!IsServer()) return;
if (event.unit != this.GetParent()) return;
this.Destroy();
}
}
@registerModifier()
export class modifier_shisui_kotoamatsukami_debuff extends BaseModifier
{
IsPurgable(): boolean {return false}
IsPurgeException(): boolean {return true}
/****************************************/
OnCreated(params: object): void {
if (!IsServer()) return;
let parent = this.GetParent();
let caster = this.GetCaster() as CDOTA_BaseNPC;
EmitSoundOn("Hero_Shisui.Kotoamatsukami.Target", parent);
parent.MoveToNPC(caster);
let gaze_fx = ParticleManager.CreateParticle("particles/units/heroes/shisui/shisui_kotoamatsukami.vpcf", ParticleAttachment.ABSORIGIN_FOLLOW, parent)
ParticleManager.SetParticleControlEnt(gaze_fx, 1, parent, ParticleAttachment.ABSORIGIN_FOLLOW, "attach_hitloc", parent.GetAbsOrigin(), true)
ParticleManager.SetParticleControlEnt(gaze_fx, 2, caster, ParticleAttachment.POINT_FOLLOW, "attach_eye_right", caster.GetAbsOrigin(), true)
ParticleManager.SetParticleControlEnt(gaze_fx, 3, caster, ParticleAttachment.ABSORIGIN_FOLLOW, "attach_hitloc", caster.GetAbsOrigin(), true)
ParticleManager.SetParticleControlEnt(gaze_fx, 10, caster, ParticleAttachment.ABSORIGIN_FOLLOW, "attach_hitloc", caster.GetAbsOrigin(), true)
this.AddParticle(gaze_fx, false, false, -1, false, false)
this.StartIntervalThink(0.1);
}
/****************************************/
OnDestroy(): void {
if (!IsServer()) return;
this.GetParent().Stop();
}
/****************************************/
OnIntervalThink(): void {
this.GetParent().MoveToNPC(this.GetCaster()!);
}
/****************************************/
CheckState(): Partial<Record<ModifierState, boolean>> {
return {
[ModifierState.COMMAND_RESTRICTED]: true,
[ModifierState.FEARED]: true
};
}
}
|
jaden-young/NWR
|
src/vscripts/items/forehead_protector.d.ts
|
/** @noSelfInFile */
declare function foreheadProtectorChangeIcon(hero: CDOTA_BaseNPC_Hero, itemName: string): void;
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/sai/sai_kamis_strength.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class sai_kamis_strength extends BaseAbility {
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/sai/kami_strength.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/sai/game_sounds_sai.vsndevts", context);
//PrecacheResource("soundfile", "soundevents/heroes/sai/game_sounds_vo_sai.vsndevts", context);
}
/****************************************/
OnSpellStart(): void {
let caster = this.GetCaster();
caster.AddNewModifier(caster, this, "modifier_sai_kamis_strength", {duration: this.GetSpecialValueFor("duration")});
EmitSoundOn("Hero_Sai.KamisStrength.Cast", caster);
}
}
@registerModifier()
export class modifier_sai_kamis_strength extends BaseModifier
{
attack_speed?: number;
move_speed?: number;
/****************************************/
OnCreated(params: Object): void {
let ability = this.GetAbility()!;
this.attack_speed = ability.GetSpecialValueFor("attack_speed");
this.move_speed = ability.GetSpecialValueFor("move_speed");
}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.ATTACKSPEED_BONUS_CONSTANT,
ModifierFunction.MOVESPEED_BONUS_PERCENTAGE
]}
/****************************************/
GetModifierAttackSpeedBonus_Constant(): number {
return this.attack_speed!;
}
/****************************************/
GetModifierMoveSpeedBonus_Percentage(): number {
return this.move_speed!;
}
/****************************************/
GetEffectName(): string {
return "particles/units/heroes/sai/kami_strength.vpcf";
}
/****************************************/
GetEffectAttachType(): ParticleAttachment {
return ParticleAttachment.ABSORIGIN_FOLLOW;
}
}
|
jaden-young/NWR
|
src/vscripts/items.d.ts
|
/** @noSelfInFile */
declare function SupportItemCooldownReset(killedUnit: CBaseEntity, killerEntity: CBaseEntity): void;
declare function ForeheadProtectorOnItemPickedUp(hero: CDOTA_BaseNPC_Hero, itemName: string): void;
declare function ChakraArmorOnItemPickedUp(hero: CDOTA_BaseNPC_Hero, itemName: string): void;
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/itachi/itachi_innate_passive.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class itachi_innate_passive extends BaseAbility
{
GetIntrinsicModifierName(): string {
return "modifier_itachi_innate_passive"
}
/****************************************/
Spawn(): void {
if (IsServer()) {
this.SetLevel(1);
}
}
}
@registerModifier()
export class modifier_itachi_innate_passive extends BaseModifier
{
parent: CDOTA_BaseNPC = this.GetParent();
angle?: number;
damage_table?: ApplyDamageOptions;
record: number = -1;
sound: string = "ChakraPunch.Attack";
/****************************************/
IsHidden(): boolean {return true}
IsPurgable(): boolean {return false}
RemoveOnDeath(): boolean {return false}
/****************************************/
OnCreated(params: object): void {
if (!IsServer()) return;
let ability = this.GetAbility()!;
this.angle = ability.GetSpecialValueFor("angle") / 180;
this.damage_table = {
attacker: this.GetParent(),
victim: this.GetParent(),
damage: 0,
damage_type: ability.GetAbilityDamageType(),
ability: ability
}
this.StartIntervalThink(0.1);
}
/****************************************/
OnIntervalThink(): void {
let parent = this.GetParent()
if (parent.IsMoving() || parent.GetSequence() == "striker_itachi_idle") {
this.GetParent().FadeGesture(GameActivity.DOTA_ATTACK);
this.GetParent().FadeGesture(GameActivity.DOTA_ATTACK_EVENT);
}
}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.PRE_ATTACK,
ModifierFunction.ON_ATTACK_CANCELLED,
ModifierFunction.ON_ATTACK_RECORD_DESTROY,
ModifierFunction.ON_ATTACK_LANDED,
ModifierFunction.TRANSLATE_ATTACK_SOUND
]}
/****************************************/
GetModifierPreAttack(event: ModifierAttackEvent): number {
if (!IsServer()) return 0;
let attacker = event.attacker as CDOTA_BaseNPC_Hero;
let target = event.target;
let ability = this.GetAbility();
if (!attacker || !target || !ability || attacker != this.parent) return 0;
if (!this.IsAttackingFromBehind(target)) return 0;
this.record = event.record;
let play_rate = 1 / attacker.GetSecondsPerAttack();
attacker.StartGestureWithPlaybackRate(GameActivity.DOTA_ATTACK_EVENT, play_rate * 1.4);
EmitSoundOn("Hero_Itachi.Kunai.PreAttack", attacker);
this.sound = "Hero_Itachi.Kunai.Attack";
return 0;
}
OnAttackCancelled(event: ModifierAttackEvent): void {
if (!IsServer()) return;
if (event.record == this.record) {
event.attacker.FadeGesture(GameActivity.DOTA_ATTACK_EVENT);
StopSoundOn("Hero_Itachi.Kunai.PreAttack", event.attacker);
}
}
/****************************************/
OnAttackRecordDestroy(event: ModifierAttackEvent): void {
if (!IsServer()) return;
if (event.record == this.record) {
this.record = -1;
this.sound = "ChakraPunch.Attack";
}
}
/****************************************/
OnAttackLanded(event: ModifierAttackEvent): void {
if (!IsServer()) return;
let attacker = event.attacker as CDOTA_BaseNPC_Hero;
let target = event.target;
let ability = this.GetAbility();
if (this.record != event.record) return;
let multiplier = ability!.GetSpecialValueFor("damage_per_int") + attacker.FindTalentValue("special_bonus_itachi_5");
this.damage_table!.victim = target;
this.damage_table!.damage = attacker.GetIntellect() * multiplier;
ApplyDamage(this.damage_table!);
let true_damage = math.floor((this.damage_table!.damage * (1 + attacker.GetSpellAmplification(false))) - this.damage_table!.damage * target.GetMagicalArmorValue());
SendOverheadEventMessage(undefined, OverheadAlert.BONUS_SPELL_DAMAGE, target, true_damage, undefined);
EmitSoundOn("Hero_Itachi.Anbu.Proc", target);
let crit_fx = ParticleManager.CreateParticle("particles/units/heroes/hero_phantom_assassin/phantom_assassin_crit_impact.vpcf", ParticleAttachment.CUSTOMORIGIN, undefined);
ParticleManager.SetParticleControlEnt(crit_fx, 0, target, ParticleAttachment.POINT_FOLLOW, "attach_hitloc", target.GetAbsOrigin(), true);
ParticleManager.SetParticleControl(crit_fx, 1, target.GetAbsOrigin());
ParticleManager.SetParticleControlForward(crit_fx, 1, -attacker.GetForwardVector() as Vector);
ParticleManager.ReleaseParticleIndex(crit_fx);
}
/****************************************/
IsAttackingFromBehind(target: CDOTA_BaseNPC): boolean {
let direction = (target.GetAbsOrigin() - this.parent.GetAbsOrigin() as Vector).Normalized();
let target_facing_direction = target.GetForwardVector();
return target_facing_direction.Dot(direction) > this.angle!;
}
GetAttackSound(): string {
return this.sound;
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/raikage/raikage_innate_passive.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class raikage_innate_passive extends BaseAbility
{
GetIntrinsicModifierName(): string {
return "modifier_raikage_innate_passive"
}
/****************************************/
Spawn(): void {
if (IsServer()) {
this.SetLevel(1);
}
}
}
@registerModifier()
export class modifier_raikage_innate_passive extends BaseModifier
{
parent: CDOTA_BaseNPC = this.GetParent();
distance_per_charge?: number;
charge_per_distance?: number;
max_charges?: number;
attack_min_charges?: number;
added_charges_threshold?: number;
added_charges?: number;
crit_per_stack?: number;
crit_per_stack_lvl?: number;
current_crit?: number;
current_distance: number = 0;
last_pos?: Vector
/****************************************/
IsHidden(): boolean {return this.GetStackCount() == 0}
IsPurgable(): boolean {return false}
RemoveOnDeath(): boolean {return false}
/****************************************/
OnCreated(params: object): void {
let ability = this.GetAbility()!;
this.distance_per_charge = ability.GetSpecialValueFor("distance_per_charge");
this.charge_per_distance = ability.GetSpecialValueFor("charge_per_distance");
this.max_charges = ability.GetSpecialValueFor("max_charges");
this.attack_min_charges = ability.GetSpecialValueFor("attack_min_charges");
this.added_charges_threshold = ability.GetSpecialValueFor("added_charges_threshold");
this.added_charges = ability.GetSpecialValueFor("added_charges");
this.crit_per_stack = ability.GetSpecialValueFor("crit_per_stack");
this.crit_per_stack_lvl = ability.GetSpecialValueFor("crit_per_stack_lvl");
this.current_crit = this.crit_per_stack;
this.StartIntervalThink(0.1);
}
/****************************************/
OnIntervalThink(): void {
this.current_crit = this.crit_per_stack! + (this.crit_per_stack_lvl! * (this.GetParent().GetLevel() - 1))
if (!IsServer()) return;
if (!this.last_pos) this.last_pos = this.GetParent().GetAbsOrigin();
let parent = this.GetParent();
let origin = parent.GetAbsOrigin();
this.current_distance += (origin - this.last_pos! as Vector).Length2D();
this.last_pos = origin;
if (this.current_distance >= this.distance_per_charge!) {
let stacks = math.floor(this.current_distance / this.distance_per_charge! + 0.5)
this.current_distance = this.current_distance % this.distance_per_charge!;
this.SetStackCount(math.min(this.GetStackCount() + stacks, this.max_charges!));
}
}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.PREATTACK_CRITICALSTRIKE,
ModifierFunction.ON_ATTACK_LANDED,
ModifierFunction.TOOLTIP
]}
/****************************************/
GetModifierPreAttack_CriticalStrike(event: ModifierAttackEvent): number {
if (!IsServer()) return 0;
let attacker = event.attacker as CDOTA_BaseNPC_Hero;
let target = event.target;
let ability = this.GetAbility();
if (attacker != this.GetParent() || !target || !ability || target.IsBuilding() || target.IsOther()) return 0;
if (this.GetStackCount() < this.attack_min_charges!) return 0;
return 100 + this.GetStackCount() * (this.crit_per_stack! + (this.crit_per_stack_lvl! * (attacker.GetLevel() - 1)));
}
/****************************************/
OnAttackLanded(event: ModifierAttackEvent): void {
if (!IsServer()) return;
let attacker = event.attacker as CDOTA_BaseNPC_Hero;
let target = event.target;
let ability = this.GetAbility();
if (attacker != this.GetParent() || !target || !ability || target.IsBuilding() || target.IsOther()) return;
if (this.GetStackCount() < this.added_charges_threshold!) {
this.SetStackCount(this.GetStackCount() + this.added_charges!);
} else {
this.SetStackCount(0);
}
}
/****************************************/
OnTooltip(): number {
return 100 + this.current_crit! * this.GetStackCount();
}
}
|
jaden-young/NWR
|
src/vscripts/items/ninja_info_cards.d.ts
|
/** @noSelfInFile */
declare function ninjaInfoCardsSetCD(killedUnit: CBaseEntity, killerEntity: CBaseEntity): void;
declare function ninjaInfoCardsDeny(killedUnit: CBaseEntity, killerEntity: CBaseEntity): void;
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/hidan/hidan_innate_passive.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class hidan_innate_passive extends BaseAbility
{
ready_vfx?: ParticleID;
OnUpgrade(): void {
//Should refresh modifier on eanch upgrade
this.GetCaster().FindModifierByName(this.GetIntrinsicModifierName())?.ForceRefresh()
}
GetIntrinsicModifierName(): string {
return "modifier_hidan_innate_passive_intrinsic"
}
GetCooldown(level: number): number {
let cooldown_base = this.GetSpecialValueFor("cooldown_base")
let cooldown_bonus_per_level = this.GetSpecialValueFor("cooldown_bonus_per_level")
return cooldown_base + (this.GetLevel() - 1) * cooldown_bonus_per_level
}
TriggerAbility(){
let caster = this.GetCaster()
let hp_to_heal = (this.GetSpecialValueFor("hp_healed_percentage_base") + this.GetSpecialValueFor("hp_healed_percentage_bonus_per_level") * (this.GetLevel() - 1)) * caster.GetMaxHealth() * 0.01
caster.Heal(hp_to_heal, this)
this.StartCooldown(this.GetEffectiveCooldown(this.GetLevel()))
//Effects
this.RemoveReadyEffect()
let particle = ParticleManager.CreateParticle("particles/units/heroes/hidan/hidan_passive_a.vpcf", ParticleAttachment.ABSORIGIN_FOLLOW, caster)
ParticleManager.SetParticleControl(particle, 0, caster.GetAbsOrigin())
ParticleManager.SetParticleControl(particle, 1, caster.GetAbsOrigin())
ParticleManager.SetParticleControl(particle, 3, caster.GetAbsOrigin())
ParticleManager.DestroyParticle(particle, false)
ParticleManager.ReleaseParticleIndex(particle)
EmitSoundOn("hidan_jashinblessing_proc", caster)
}
CreateReadyEffect(){
let caster = this.GetCaster()
this.ready_vfx = ParticleManager.CreateParticle("particles/units/heroes/hidan/hidan_passive_ready_a.vpcf", ParticleAttachment.ABSORIGIN_FOLLOW, caster)
ParticleManager.SetParticleControlEnt(this.ready_vfx, 3, caster, ParticleAttachment.ABSORIGIN_FOLLOW, "attach_origin", caster.GetAbsOrigin(), true)
}
RemoveReadyEffect(){
if(this.ready_vfx){
ParticleManager.DestroyParticle(this.ready_vfx, false)
ParticleManager.ReleaseParticleIndex(this.ready_vfx)
}
}
}
@registerModifier()
export class modifier_hidan_innate_passive_intrinsic extends BaseModifier{
IsDebuff(): boolean {
return false
}
IsHidden(): boolean {
return true
}
OnCreated(params: object): void {
if (!IsServer()) return;
let ability = this.GetAbility()
let caster = ability?.GetCaster()
if(ability?.IsCooldownReady()){
(ability as hidan_innate_passive)?.CreateReadyEffect()
}else{
this.StartIntervalThink(ability?.GetCooldownTimeRemaining() ?? -1)
}
}
DeclareFunctions() {
return [
ModifierFunction.ABSOLUTE_NO_DAMAGE_PHYSICAL,
ModifierFunction.ABSOLUTE_NO_DAMAGE_PURE,
ModifierFunction.ABSOLUTE_NO_DAMAGE_MAGICAL
]
}
OnIntervalThink(): void {
(this.GetAbility() as hidan_innate_passive).CreateReadyEffect()
this.StartIntervalThink(-1)
}
IsDamageDeadly(damage: number){
return this.GetParent().GetHealth() <= damage
}
GetAbsolutelyNoDamage(event: ModifierAttackEvent) : 0 | 1{
if(event.target === this.GetParent()){
if(this.IsDamageDeadly(event.damage) && !this.GetParent().PassivesDisabled() && this.GetAbility()?.IsCooldownReady()){
(this.GetAbility() as hidan_innate_passive)?.TriggerAbility()
if(IsServer()){
this.StartIntervalThink(this.GetAbility()?.GetCooldownTimeRemaining() ?? -1)
}
return 1
} else{
return 0
}
}
return 0
}
GetAbsoluteNoDamagePhysical(event: ModifierAttackEvent){
return this.GetAbsolutelyNoDamage(event)
}
GetAbsoluteNoDamageMagical(event: ModifierAttackEvent){
return this.GetAbsolutelyNoDamage(event)
}
GetAbsoluteNoDamagePure(event: ModifierAttackEvent){
return this.GetAbsolutelyNoDamage(event)
}
}
|
jaden-young/NWR
|
src/common/nettables.d.ts
|
<filename>src/common/nettables.d.ts<gh_stars>0
interface CustomNetTableDeclarations {
better_cooldowns_cdr: {
[unitID: string]: {
cdr: number;
};
};
kakashi_sharingan_tracker: {
[PlayerID: string]: {
last_ability: string;
};
};
}
|
jaden-young/NWR
|
src/vscripts/lib/keyvalues.d.ts
|
<reponame>jaden-young/NWR
declare function LoadKeyValues(): void;
declare type KeyValueResult = undefined | LuaTable | string | number;
declare function GetKeyValueByHeroName(hero_name: string, key: string): KeyValueResult;
declare function GetKeyValue(name: string, key?: string, level?: number, tbl?: LuaTable): KeyValueResult;
declare function GetUnitKV(unitName: string, key?: string, level?: number): KeyValueResult;
declare function GetAbilityKV(unitName: string, key?: string, level?: number): KeyValueResult;
declare function GetItemKV(unitName: string, key?: string, level?: number): KeyValueResult;
declare function GetAbilitySpecials(name: string): LuaTable | undefined;
declare function GetAbilityCooldown(name: string): number;
declare function GetAbilityManaCost(name: string): number;
declare function GetSpellImmunityType(name: string): string | undefined;
declare function GetSpellDispellableType(name: string): string | undefined;
declare interface CDOTA_BaseNPC {
GetKeyValue(key: string, level?: number): KeyValueResult;
}
declare interface CDOTABaseAbility {
GetKeyValue(key: string, level?: number): KeyValueResult;
GetAbilitySpecial(key: string): KeyValueResult;
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/kakashi/kakashi_earth_release.ts
|
<reponame>jaden-young/NWR<filename>src/vscripts/abilities/heroes/kakashi/kakashi_earth_release.ts
import {BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
import {BaseVectorAbility} from "../../../lib/vector_targeting_interface";
@registerAbility()
export class kakashi_earth_release extends BaseVectorAbility
{
Precache(context: CScriptPrecacheContext): void{
//PrecacheResource("particle", "", context);
PrecacheResource("soundfile", "soundevents/heroes/kakashi/game_sounds_kakashi.vsndevts", context);
PrecacheResource("soundfile", "soundevents/heroes/kakashi/game_sounds_vo_kakashi.vsndevts", context);
}
/****************************************/
GetVectorTargetRange(): number {
return this.GetSpecialValueFor("wall_length")
}
/****************************************/
GetVectorTargetStartRadius(): number {
return this.GetSpecialValueFor("wall_width")
}
/****************************************/
IsDualVectorDirection(): boolean {
return true;
}
/****************************************/
OnVectorCastStart(start_loc: Vector, direction: Vector): void {
let caster = this.GetCaster();
let damage = this.GetSpecialValueFor("damage");
let duration = this.GetSpecialValueFor("duration");
let stun_duration = this.GetSpecialValueFor("stun_duration");
let radius = this.GetSpecialValueFor("radius");
let length = this.GetSpecialValueFor("wall_length") / 2;
let width = this.GetSpecialValueFor("wall_width");
let start_pos = start_loc + length * direction as Vector;
let end_pos = start_loc - length * direction as Vector;
for (let i = -(length / width); i <= length / width; i++) {
let position = start_loc + i * width * direction as Vector;
let block = CreateModifierThinker(caster, this, "modifier_kakashi_earth_release_thinker", {duration: duration}, position, caster.GetTeamNumber(), true);
block.SetHullRadius(width);
}
EmitSoundOnLocationWithCaster(start_loc, "Hero_Kakashi.MudWall.Cast", caster)
EmitSoundOnLocationWithCaster(start_loc, "Hero_Kakashi.MudWall.Layer", caster)
let wall_fx = ParticleManager.CreateParticle("particles/units/heroes/kakashi/mud_wall.vpcf", ParticleAttachment.WORLDORIGIN, undefined);
ParticleManager.SetParticleControl(wall_fx, 0, start_pos)
ParticleManager.SetParticleControl(wall_fx, 1, end_pos)
ParticleManager.SetParticleControl(wall_fx, 2, Vector(duration, 0, 0))
ParticleManager.ReleaseParticleIndex(wall_fx)
let units = FindUnitsInLine(
caster.GetTeamNumber(),
start_pos,
end_pos,
undefined,
radius,
UnitTargetTeam.BOTH,
UnitTargetType.BASIC + UnitTargetType.HERO,
0
)
let damage_table: ApplyDamageOptions = {
attacker: caster,
victim: caster,
damage: damage,
damage_type: this.GetAbilityDamageType(),
ability: this
}
Timers.CreateTimer(FrameTime(), () =>{
units.forEach(unit => {
FindClearSpaceForUnit(unit, unit.GetAbsOrigin(), true);
if (unit.GetTeamNumber() != caster.GetTeamNumber()) {
damage_table.victim = unit;
ApplyDamage(damage_table);
unit.AddNewModifier(caster, this, "modifier_stunned", {duration: stun_duration * (1 - unit.GetStatusResistance())});
}
});
});
}
}
@registerModifier()
export class modifier_kakashi_earth_release_thinker extends BaseModifier
{
IsPurgable(): boolean {return false}
/****************************************/
OnDestroy(): void {
if (!IsServer()) return;
EmitSoundOnLocationWithCaster(this.GetParent().GetAbsOrigin(), "Hero_EarthShaker.FissureDestroy", this.GetCaster()!)
UTIL_Remove(this.GetParent());
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/temari/temari_innate_passive.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class temari_innate_passive extends BaseAbility
{
OnUpgrade(): void {
//Should refresh modifier on eanch upgrade
let caster = this.GetCaster()
caster.FindModifierByName(this.GetIntrinsicModifierName())?.ForceRefresh()
}
GetIntrinsicModifierName(): string {
return "modifier_temari_innate_passive_intrinsic"
}
}
@registerModifier()
export class modifier_temari_innate_passive_intrinsic extends BaseModifier
{
IsPurgable(): boolean {
return false
}
IsHidden(): boolean {
return true
}
IsDebuff(): boolean {
return false
}
IsPermanent(): boolean {
return true
}
DeclareFunctions(){
return [ModifierFunction.ON_ABILITY_EXECUTED]
}
OnAbilityExecuted(event: ModifierAbilityEvent){
let parent = this.GetParent()
let ability = this.GetAbility()
if(!ability){return}
if(event.unit !== parent){return}
if(parent.PassivesDisabled()){return}
let stack_duration = ability.GetSpecialValueFor("stack_duration")
parent.AddNewModifier(parent, this.GetAbility(), "modifier_temari_innate_passive_buff", {duration: stack_duration})
}
}
@registerModifier()
export class modifier_temari_innate_passive_buff_counter extends BaseModifier
{
bonus_attack_speed_constant: number = 0
bonus_movement_speed_percentage: number = 0
IsPurgable(): boolean {
return true
}
IsHidden(): boolean {
return false
}
IsDebuff(): boolean {
return false
}
IsPermanent(): boolean {
return false
}
UpdateNumbers(){
let ability = this.GetAbility()
if(!ability){return}
this.bonus_attack_speed_constant = ability.GetSpecialValueFor("bonus_attack_speed_constant_per_stack_base") + (ability.GetSpecialValueFor("bonus_attack_speed_constant_per_stack_per_level_bonus") * (ability.GetLevel() - 1))
this.bonus_movement_speed_percentage = ability.GetSpecialValueFor("bonus_movement_speed_percentage_per_stack_base") + (ability.GetSpecialValueFor("bonus_movement_speed_percentage_per_stack_per_level_bonus") * (ability.GetLevel() - 1))
}
OnCreated(): void {
this.UpdateNumbers()
}
DeclareFunctions(){
return [ModifierFunction.MOVESPEED_BONUS_PERCENTAGE,
ModifierFunction.ATTACKSPEED_BONUS_CONSTANT]
}
GetModifierMoveSpeedBonus_Percentage(){
return this.GetStackCount() * this.bonus_movement_speed_percentage
}
GetModifierAttackSpeedBonus_Constant(){
return this.GetStackCount() * this.bonus_attack_speed_constant
}
}
@registerModifier()
export class modifier_temari_innate_passive_buff extends BaseModifier
{
IsPurgable(): boolean {
return true
}
IsPermanent(): boolean {
return false
}
IsDebuff(): boolean {
return false
}
IsHidden(): boolean {
return true
}
GetAttributes(): ModifierAttribute {
return ModifierAttribute.MULTIPLE
}
OnCreated(params: object): void {
let parent = this.GetParent()
let ability = this.GetAbility()
if(!IsServer()){return}
if(!ability){return}
let max_stacks = ability.GetSpecialValueFor("max_stacks")
let stack_duration = ability.GetSpecialValueFor("stack_duration")
if(parent.HasModifier("modifier_temari_innate_passive_buff_counter")){
let counter_modifier = parent.FindModifierByName("modifier_temari_innate_passive_buff_counter")
if(!counter_modifier){return}
let current_stacks = counter_modifier.GetStackCount()
if(current_stacks === max_stacks){
let buff_modifiers = parent.FindAllModifiersByName("modifier_temari_innate_passive_buff")
buff_modifiers[0].Destroy()
counter_modifier.SetDuration(stack_duration, true)
counter_modifier.IncrementStackCount()
}else{
counter_modifier.IncrementStackCount()
counter_modifier.SetDuration(stack_duration, true)
}
}else{
let new_counter_modifier = parent.AddNewModifier(parent, ability,"modifier_temari_innate_passive_buff_counter", {duration: stack_duration})
new_counter_modifier.SetStackCount(1)
}
}
OnDestroy(): void {
if(!IsServer()){return}
let parent = this.GetParent()
let ability = this.GetAbility()
if(!ability){return}
let counter_modifier = parent.FindModifierByName("modifier_temari_innate_passive_buff_counter")
if(!counter_modifier){return}
if(counter_modifier.GetStackCount() === 1){
parent.RemoveModifierByName("modifier_temari_innate_passive_buff_counter")
}else{
counter_modifier.DecrementStackCount()
}
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/haku/haku_demonic_speed.ts
|
<reponame>jaden-young/NWR
import { BaseAbility, BaseModifier, BaseModifierMotionHorizontal, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
interface kv {
x: number;
y: number;
z: number;
}
@registerAbility()
export class haku_demonic_speed extends BaseAbility
{
lightning_blade_fx?: ParticleID;
active_target?: CDOTA_BaseNPC;
/****************************************/
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/haku/haku_demonic_speed.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/haku/game_sounds_haku.vsndevts", context);
//PrecacheResource("soundfile", "soundevents/heroes/haku/game_sounds_vo_haku.vsndevts", context);
}
/****************************************/
GetCastRange(location: Vector, target: CDOTA_BaseNPC | undefined): number {
return IsClient() ? super.GetCastRange(location, target) : 50000;
}
/****************************************/
OnSpellStart(): void {
let caster = this.GetCaster();
let position = this.GetCursorPosition();
let origin = caster.GetAbsOrigin();
let range = this.GetSpecialValueFor("cast_range");
let distance = (position - origin as Vector).Length2D();
position = distance < range ? position : (position - origin as Vector).Normalized() * range + origin as Vector;
caster.AddNewModifier(caster, this, "modifier_haku_demonic_speed", {duration: -1, x: position.x, y: position.y, z: position.z})
EmitSoundOn("Hero_Haku.DemonicSpeed.Cast", caster);
}
}
@registerModifier()
export class modifier_haku_demonic_speed extends BaseModifierMotionHorizontal
{
position?: Vector;
origin?: Vector;
speed?: number;
search_radius?: number;
distance_to_cross?: number;
/****************************************/
IsPurgable(): boolean {return false}
RemoveOnDeath(): boolean {return true}
/****************************************/
OnCreated(params: kv): void {
let ability = this.GetAbility()!;
let parent = this.GetParent();
this.speed = 1900//ability.GetSpecialValueFor("speed");
this.search_radius = ability.GetSpecialValueFor("attack_search_range");
if (!IsServer()) return;
this.origin = parent.GetAbsOrigin();
this.position = Vector(params.x, params.y, params.z);
this.distance_to_cross = (this.position - parent!.GetAbsOrigin() as Vector).Length2D();
if (!this.ApplyHorizontalMotionController()) {
this.Destroy()
return;
}
this.StartIntervalThink(FrameTime());
this.OnIntervalThink();
}
/****************************************/
OnDestroy(): void {
if (!IsServer()) return;
let parent = this.GetParent();
parent.RemoveHorizontalMotionController(this);
GridNav.DestroyTreesAroundPoint(parent.GetAbsOrigin(), 150, true);
if(GridNav.IsBlocked(parent.GetAbsOrigin()))
FindClearSpaceForUnit(parent, parent.GetAbsOrigin(), false);
}
/****************************************/
CheckState(): Partial<Record<ModifierState, boolean>> {
return {
[ModifierState.NO_UNIT_COLLISION]: true,
[ModifierState.FLYING_FOR_PATHING_PURPOSES_ONLY]: true,
};
}
/****************************************/
UpdateHorizontalMotion(parent: CDOTA_BaseNPC, dt: number): void {
let direction = (this.position! - parent.GetAbsOrigin() as Vector).Normalized();
if (this.CheckDistance()) {
this.Destroy();
return;
}
parent.FaceTowards(this.position!);
parent.SetAbsOrigin(parent.GetAbsOrigin() + this.speed! * direction * dt as Vector);
}
/****************************************/
OnHorizontalMotionInterrupted(): void {
this.Destroy();
}
/****************************************/
OnIntervalThink(): void {
let parent = this.GetParent();
let enemy = undefined;
let enemies = FindUnitsInRadius(
parent.GetTeamNumber(),
parent.GetAbsOrigin(),
undefined,
this.search_radius!,
UnitTargetTeam.ENEMY,
UnitTargetType.HERO,
UnitTargetFlags.NO_INVIS + UnitTargetFlags.FOW_VISIBLE,
FindOrder.CLOSEST,
false
);
if (enemies.length == 0)
enemies = FindUnitsInRadius(
parent.GetTeamNumber(),
parent.GetAbsOrigin(),
undefined,
this.search_radius!,
UnitTargetTeam.ENEMY,
UnitTargetType.HERO + UnitTargetType.BASIC,
UnitTargetFlags.NO_INVIS + UnitTargetFlags.FOW_VISIBLE,
FindOrder.CLOSEST,
false
);
if (enemies.length > 0) {
enemy = enemies[0]
parent.PerformAttack(enemy, false, true, true, false, true, false, false);
this.StartIntervalThink(-1);
}
}
/****************************************/
CheckDistance(): boolean {
let parent = this.GetParent();
let distance = (parent.GetAbsOrigin() - this.origin! as Vector).Length2D()
if (distance >= this.distance_to_cross!) {
return true;
}
return false;
}
/****************************************/
GetEffectName(): string {
return "particles/units/heroes/haku/haku_demonic_speed.vpcf";
}
/****************************************/
GetEffectAttachType(): ParticleAttachment {
return ParticleAttachment.ABSORIGIN_FOLLOW;
}
}
|
jaden-young/NWR
|
src/vscripts/lib/vanilla_extension.d.ts
|
<reponame>jaden-young/NWR
export {}
declare global {
interface CDOTA_BaseNPC {
IsCustomHero(): boolean;
HasTalent(talentName: string): boolean;
FindTalentValue(talentName: string, key?: string): number;
HighestTalentTypeValue(talentType: string): number;
IsRoshan(): boolean;
HasShard(): boolean;
// also overrides CreateIllusions
}
interface CDOTABaseAbility {
GetTalentSpecialValueFor(value: string): number;
}
/**
* Has something to do with talent initialization and
* `modifier_custom_mechanics` that is needed for the e.g. FindTalentValue()
* extension methods to work.
* @param hero short hero name, e.g. "naruto"
*/
function CreateEmptyTalents(this: void, hero: string): void;
}
|
jaden-young/NWR
|
src/panorama/vanilla_hud_overrides.ts
|
//@ts-nocheck
var Parent: Panel = $.GetContextPanel()!.GetParent()!.GetParent()!.GetParent()!;
function SetCustomHUD() {
SetTopBarBackground();
SetInventoryBackground();
SetAbilityBackground();
SetMinimapBackground();
SetPortraitBackground();
}
// One would think that you'd be able to call SetImage on a HeroImage panel,
// but there's some weird timing/races. It works after things are totally
// loaded in, but I haven't been able to find a good signal for that, and
// waiting some number of seconds feels fragile. Instead, just add a new panel
// on top with an image that will definitely be there.
function OverrideImage(hParent, sHeroName) {
var newheroimage = $.CreatePanel("Panel", hParent, "");
newheroimage.style.width = "100%";
newheroimage.style.height = "100%";
newheroimage.style.backgroundImage =
'url("file://{images}/custom_game/heroes/topbar/' +
sHeroName +
'.png")';
newheroimage.style.backgroundSize = "cover";
}
function OverrideTopBarHeroImages() {
for (let i = 0; i < 10; i++) {
const playerInfo = Game.GetPlayerInfo(i);
if (playerInfo) {
let container = Parent.FindChildTraverse("RadiantPlayer" + i);
if (container) {
let heroImage = container.FindChildTraverse("HeroImage") as
| HeroImage
| undefined;
OverrideImage(heroImage, playerInfo.player_selected_hero);
} else {
container = Parent.FindChildTraverse("DirePlayer" + i);
if (container) {
let heroImage = container.FindChildTraverse("HeroImage") as
| HeroImage
| undefined;
OverrideImage(heroImage, playerInfo.player_selected_hero);
}
}
}
}
}
function SetTopBarBackground() {
var container = Parent.FindChildTraverse("HUDSkinTopBarBG");
container.style.visibility = "visible";
container.style.backgroundImage =
"url('file://{resources}/images/custom_game/hud/tophud.png')";
container.style.backgroundSize = "100% 100%";
container.style.width = "57.8%";
container.style.height = "90px";
var backgrounds = Parent.FindChildrenWithClassTraverse("TopBarBackground");
for (var i = 0; i < backgrounds.length; i++) {
var child = backgrounds[i];
child.style.backgroundImage = "none";
}
}
function SetInventoryBackground() {
var container = Parent.FindChildTraverse("HUDSkinInventoryBG");
var container2 = Parent.FindChildTraverse("right_flare");
container.style.visibility = "visible";
container.style.backgroundImage =
"url('file://{resources}/images/custom_game/hud/dhb_abilities.png')";
container.style.backgroundSize = "103% 105%"; //103 104
container.style.backgroundPosition = "0px -8px"; // -6 -7
container.style.backgroundRepeat = "no-repeat";
if (!container2) return;
container2.style.height = "145px"; // 138px
container2.style.backgroundImage =
"url('file://{resources}/images/custom_game/hud/dhb_inventory2.png')";
container2.style.backgroundSize = "100% 100%";
container2.style.backgroundRepeat = "no-repeat";
const rightParticles = container2.FindChild(
"HUDSkinPreCenterParticlesRight"
);
if (rightParticles) rightParticles.visible = false;
const leftHudSkin = Parent.FindChildTraverse(
"HUDSkinPreCenterParticlesLeft"
);
if (leftHudSkin) leftHudSkin.visible = false;
}
function SetAbilityBackground() {
var container = Parent.FindChildTraverse("center_bg");
var container2 = Parent.FindChildTraverse("right_flare");
container.style.visibility = "visible";
container.style.backgroundImage =
"url('file://{resources}/images/custom_game/hud/dhb_abilities.png')";
container.style.backgroundSize = "100% 105%";
container.style.backgroundPosition = "0% -8px";
container.style.backgroundRepeat = "no-repeat";
}
function SetPortraitBackground() {
var container = Parent.FindChildTraverse("left_flare");
var container2 = Parent.FindChildTraverse("HUDSkinPortrait");
var container3 = Parent.FindChildTraverse("HUDSkinStatBranchGlow");
var container4 = Parent.FindChildTraverse("unitname");
container.style.visibility = "collapse";
container2.style.backgroundImage =
"url('file://{images}/custom_game/hud/dhb_portrait1_simple.png')";
container2.style.backgroundSize = "90% 90%";
container2.style.backgroundPosition = "63% -9%";
container2.style.backgroundRepeat = "no-repeat";
container2.style.zIndex = "6";
container2.style.visibility = "visible";
container3.style.boxShadow = "none";
container4.style.marginLeft = "23px";
container4.style.marginBottom = "145px";
container4.style.zIndex = "7";
}
function SetMinimapBackground() {
var container = Parent.FindChildTraverse("HUDSkinMinimap");
var container2 = Parent.FindChildTraverse("GlyphScanContainer");
container.style.visibility = "visible";
container.style.backgroundImage =
"url('file://{resources}/images/custom_game/hud/dhb_minimap.png')";
container.style.backgroundSize = "91.7% 81%";
container.style.backgroundPosition = "0px 69px";
container.style.backgroundRepeat = "no-repeat";
container2.style.backgroundImage =
"url('file://{resources}/images/custom_game/hud/dhb_minimap2.png')";
container2.style.backgroundSize = "100% 100%";
}
function HideAghs() {
const lowHud = Parent?.FindChildTraverse("lower_hud");
const aghs = lowHud?.FindChildTraverse("AghsStatusContainer");
if (aghs) {
aghs.style.width = "0px";
}
}
(function () {
GameEvents.Subscribe("override_hero_images", OverrideTopBarHeroImages);
OverrideTopBarHeroImages();
SetCustomHUD();
})();
|
jaden-young/NWR
|
src/panorama/innate_passive_panel.ts
|
var Parent: Panel = $.GetContextPanel()!.GetParent()!.GetParent()!.GetParent()!;
const PRINT_WARNINGS = false;
let cdCheckSchedule: ScheduleID | undefined;
function AddAbilityPanel(abilityID: AbilityEntityIndex, isHero: boolean) {
const centerHud = Parent!.FindChildTraverse("center_block");
if (!centerHud) return;
const xpPanel = centerHud.FindChild("xp");
if (!xpPanel) return;
if (centerHud.FindChild("innate_passive_ability")) {
centerHud.FindChild("innate_passive_ability")!.DeleteAsync(0);
}
if (cdCheckSchedule) {
$.CancelScheduled(cdCheckSchedule);
cdCheckSchedule = undefined;
}
if (!isHero) {
xpPanel.style.margin = "0";
return;
}
xpPanel.style.margin = "0 0 4px -30px";
const newPanel = $.CreatePanelWithProperties(
"Image",
centerHud,
"innate_passive_ability",
{
src: `file://{images}/custom_game/hud/frame_innate_ability_small.png`,
scaling: "stretch-to-fit-preserve-aspect",
style: `width: 95px; height: 180px; vertical-align: bottom; margin-left: -22px; z-index: 7;`,
hittest: "false",
}
);
const abilityPanel = $.CreatePanelWithProperties("Panel", newPanel, "", {
style: "width: 51px; height: 51px; margin: 32px 0 0 16px; border-radius: 50%; box-shadow: inset 0 0 8px #000000f0; border: 1px solid black;",
hittest: "false",
class: "Reborn",
});
const abilityName = Abilities.GetAbilityName(abilityID);
const abilityImage = $.CreatePanelWithProperties(
"DOTAAbilityImage",
abilityPanel,
"innate_passive_ability_image",
{
abilityname: abilityName,
style: "tooltip-position: top;",
hittest: "true",
onmouseover: `DOTAShowAbilityTooltip('${abilityName}')`,
onmouseout: "DOTAHideAbilityTooltip()",
}
);
const cooldownPanel = $.CreatePanelWithProperties(
"Panel",
abilityPanel,
"Cooldown",
{
hittest: "false",
style: "visibility: visible; margin: 0;",
}
);
const cooldownOverlay = $.CreatePanelWithProperties(
"Panel",
cooldownPanel,
"CooldownOverlay",
{
hittest: "false",
}
);
const cooldownTimer = $.CreatePanelWithProperties(
"Label",
cooldownPanel,
"CooldownTimer",
{
class: "MonoNumbersFont",
hittest: "false",
text: "3",
}
);
function checkCooldown() {
cdCheckSchedule = undefined;
const [percentage, curCD] = GetCooldowns(abilityID);
const degrees = -360 * percentage;
cooldownOverlay.style.clip =
"radial( 50.0% 50.0%, 0.0deg, " + degrees + "deg)";
cooldownTimer.text = curCD === 0 ? "" : Math.ceil(curCD).toString();
cdCheckSchedule = $.Schedule(0.1, checkCooldown);
}
checkCooldown();
}
let lastEntity: EntityIndex | undefined;
let lastEntityCount = 0;
function CheckUnit() {
const iPlayerID = Players.GetLocalPlayer();
const selectedEntities = Players.GetSelectedEntities(iPlayerID);
const mainSelected = Players.GetLocalPlayerPortraitUnit();
if (
lastEntity === undefined ||
mainSelected !== lastEntity ||
selectedEntities.length !== lastEntityCount
) {
lastEntity = mainSelected;
lastEntityCount = selectedEntities.length;
if (selectedEntities.length > 1) {
AddAbilityPanel(-1 as AbilityEntityIndex, false);
$.Schedule(0, CheckUnit);
return;
}
const unitName = Entities.GetUnitName(mainSelected);
let abilityName = `${unitName.replace(
"npc_dota_hero_",
""
)}_innate_passive`;
let abilityID = Entities.GetAbilityByName(mainSelected, abilityName);
if (abilityID < 0) {
if (PRINT_WARNINGS)
$.Msg(
`> Innate ability [${abilityName}] not found for ${unitName}]`
);
abilityID = Entities.GetAbility(mainSelected, 0);
abilityName = Abilities.IsHidden(abilityID)
? ""
: Abilities.GetAbilityName(abilityID);
}
AddAbilityPanel(
abilityID,
Entities.IsHero(mainSelected) && abilityName !== ""
);
}
$.Schedule(0, CheckUnit);
}
CheckUnit();
/**
* Calculate the current fill percentage for the cooldown of an ability
* @param abilityID ability entindex
* @returns [fill percentage, current cooldown]
*/
function GetCooldowns(abilityID: AbilityEntityIndex) {
const mainSelected = Players.GetLocalPlayerPortraitUnit();
const cdLength = Abilities.GetCooldownLength(abilityID);
const curCD = Abilities.GetCooldownTimeRemaining(abilityID);
let maxCD =
Abilities.GetCooldown(abilityID) * GetCooldownReduction(mainSelected);
if (maxCD === 0) {
return [0, 0];
}
if (curCD > maxCD) {
maxCD = cdLength;
}
if (curCD === 0) {
return [0, 0];
}
const ratio = curCD / maxCD;
return [ratio, curCD];
}
/**
* Get the cooldown reduction for this unit.
* @param unitID Unit entindex
* @returns unit cdr
*/
function GetCooldownReduction(unitID: EntityIndex): number {
const table = CustomNetTables.GetTableValue(
"better_cooldowns_cdr",
unitID.toString()
);
if (table) {
return table["cdr"];
}
return 1;
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/kakashi/kakashi_sharingan.ts
|
<filename>src/vscripts/abilities/heroes/kakashi/kakashi_sharingan.ts
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
interface kv {
ability_id: EntityIndex;
}
@registerAbility()
export class kakashi_sharingan extends BaseAbility
{
Precache(context: CScriptPrecacheContext): void{
//PrecacheResource("particle", "particles/units/heroes/kakashi/chidori.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/kakashi/game_sounds_kakashi.vsndevts", context);
PrecacheResource("soundfile", "soundevents/heroes/kakashi/game_sounds_vo_kakashi.vsndevts", context);
}
/****************************************/
Spawn(): void {
if (this.GetCaster().IsRealHero()) {
ListenToGameEvent("dota_player_used_ability", (event) => this.OnAbilityUsed(event), undefined);
}
}
/****************************************/
CastFilterResultTarget(target: CDOTA_BaseNPC): UnitFilterResult {
let caster = this.GetCaster();
let result = UnitFilter(
target,
UnitTargetTeam.ENEMY,
UnitTargetType.HERO,
UnitTargetFlags.NOT_CREEP_HERO + UnitTargetFlags.NOT_ILLUSIONS,
caster.GetTeamNumber()
)
if (result != UnitFilterResult.SUCCESS) return result;
const tracker = CustomNetTables.GetTableValue("kakashi_sharingan_tracker", target.GetPlayerOwnerID().toString());
return tracker && UnitFilterResult.SUCCESS || UnitFilterResult.FAIL_CUSTOM;
}
/****************************************/
GetCustomCastErrorTarget(target: CDOTA_BaseNPC): string {
return "#dota_hud_error_cant_steal_spell"
}
/****************************************/
OnSpellStart(): void {
let caster = this.GetCaster();
let target = this.GetCursorTarget() as CDOTA_BaseNPC;
let duration = this.GetSpecialValueFor("spell_duration") + caster.FindTalentValue("special_bonus_kakashi_5");
if (target?.TriggerSpellAbsorb(this)) return;
const tracker = CustomNetTables.GetTableValue("kakashi_sharingan_tracker", target.GetPlayerOwnerID().toString());
let ability_name = tracker && tracker.last_ability || "invalid"
let original_ability = target.FindAbilityByName(ability_name);
if (!original_ability) return;
let ability_id = this.StealAbility(original_ability, ability_name as string);
caster.AddNewModifier(caster, this, "modifier_kakashi_sharingan", {duration: duration, ability_id: ability_id})
EmitSoundOn("Hero_Kakashi.Sharingan.Cast", caster);
}
/****************************************/
StealAbility(ability: CDOTABaseAbility, ability_name: string): EntityIndex {
let caster = this.GetCaster();
if (caster.HasModifier("modifier_kakashi_sharingan")) {
caster.RemoveModifierByName("modifier_kakashi_sharingan");
}
let stolen_ability = caster.AddAbility(ability_name);
stolen_ability.SetHidden(true);
stolen_ability.SetLevel(this.GetLevel());
stolen_ability.SetStolen(true);
caster.SwapAbilities("kakashi_empty", ability_name, false, true)
return stolen_ability.entindex();
}
/****************************************/
OnAbilityUsed(event: DotaPlayerUsedAbilityEvent): void {
if (!event.caster_entindex || !event.abilityname || !event.PlayerID) return;
let caster = EntIndexToHScript(event.caster_entindex) as CDOTA_BaseNPC;
let ability = caster.FindAbilityByName(event.abilityname);
if (!ability || !ability.IsStealable() || ability.GetAbilityType() == AbilityTypes.ULTIMATE) return;
CustomNetTables.SetTableValue("kakashi_sharingan_tracker", tostring(event.PlayerID), {last_ability: event.abilityname});
}
}
@registerModifier()
export class modifier_kakashi_sharingan extends BaseModifier
{
ability_id?: EntityIndex;
/****************************************/
OnCreated(params: kv): void {
if (!IsServer()) return;
this.ability_id = params.ability_id;
}
/****************************************/
OnDestroy(): void {
if (!IsServer()) return;
let parent = this.GetParent();
let ability = EntIndexToHScript(this.ability_id!) as CDOTABaseAbility
parent.SwapAbilities(ability.GetAbilityName(), "kakashi_empty", false, true)
parent.RemoveAbilityByHandle(ability);
}
}
|
jaden-young/NWR
|
src/vscripts/components/lul/label.d.ts
|
/** @noSelfInFile */
declare function SetPlayerHealthLabel(player: CDOTAPlayerController): void;
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/kisame/kisame_innate_passive.ts
|
<filename>src/vscripts/abilities/heroes/kisame/kisame_innate_passive.ts
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class kisame_innate_passive extends BaseAbility
{
OnUpgrade(): void {
//Should refresh modifier on eanch upgrade
this.GetCaster().FindModifierByName(this.GetIntrinsicModifierName())?.ForceRefresh()
}
GetIntrinsicModifierName(): string {
return "modifier_kisame_innate_passive_intrinsic"
}
GetCooldown(level: number): number {
let cooldown_base = this.GetSpecialValueFor("cooldown")
// let cooldown_bonus_per_level = this.GetSpecialValueFor("cooldown_bonus_per_level")
return cooldown_base
}
Precache(context: CScriptPrecacheContext){
PrecacheResource("soundfile", "soundevents\heroes\kisame\kisame_samehada_trigger.vsndevts", context)
}
}
@registerModifier()
export class modifier_kisame_innate_passive_intrinsic extends BaseModifier
{
IsHidden(): boolean {
return true
}
IsDebuff(): boolean {
return false
}
IsPermanent(): boolean {
return true
}
IsPurgable(): boolean {
return false
}
DeclareFunctions(){
return [ModifierFunction.ON_ATTACK_LANDED]
}
OnAttackLanded(event: ModifierAttackEvent){
let ability = this.GetAbility()
if(!ability){return}
if(!ability.IsCooldownReady()){return}
if(event.attacker !== this.GetParent()){return}
if(event.target.IsBuilding()){return}
if(event.target.GetMana() <= 0){return}
let max_mana_steal = (ability.GetSpecialValueFor("max_mana_stolen_percentage_base") + (ability.GetSpecialValueFor("max_mana_stolen_percentage_per_level") * this.GetParent().GetLevel() - 1)) * 0.01
let mana_to_steal = event.target.GetMaxMana() * max_mana_steal
let current_target_mana = event.target.GetMana()
let mana_delta = current_target_mana - mana_to_steal
let actual_stolen_mana = 0
if(mana_delta <= 0){
actual_stolen_mana = mana_to_steal + mana_delta
event.target.SetMana(0)
}else{
actual_stolen_mana = mana_to_steal
event.target.SetMana(mana_delta)
}
this.GetParent().SetMana(math.min(this.GetParent().GetMana() + actual_stolen_mana, this.GetParent().GetMaxMana()))
// VFX/SFX
let particle_cast = "particles/generic_gameplay/generic_manaburn.vpcf"
let sound_cast = "kisame_samehada_trigger"
// Create Particle
let effect_cast = ParticleManager.CreateParticle( particle_cast, ParticleAttachment.ABSORIGIN, event.target )
ParticleManager.ReleaseParticleIndex( effect_cast )
// Create Sound
EmitSoundOn( sound_cast, event.target )
let bonus_attack_duration = ability.GetSpecialValueFor("bonus_attack_damage_duration")
let mana_percentage_as_bonus_damage = ability.GetSpecialValueFor("mana_percentage_as_bonus_damage")
let bonus_attack_modifier = this.GetParent().AddNewModifier(this.GetParent(), this.GetAbility(), "modifier_kisame_innate_passive_attack_bonus", {duration: bonus_attack_duration})
let bonus_damage = actual_stolen_mana * mana_percentage_as_bonus_damage * 0.01
bonus_attack_modifier.SetStackCount(math.floor(bonus_damage))
ability.StartCooldown(ability.GetEffectiveCooldown(ability.GetLevel()))
}
}
@registerModifier()
export class modifier_kisame_innate_passive_attack_bonus extends BaseModifier
{
IsDebuff(): boolean {
return false
}
IsHidden(): boolean {
return false
}
DeclareFunctions(){
return [ModifierFunction.PREATTACK_BONUS_DAMAGE]
}
GetModifierPreAttack_BonusDamage(){
return this.GetStackCount() ?? 0
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/itachi/itachi_crow_clone.ts
|
<filename>src/vscripts/abilities/heroes/itachi/itachi_crow_clone.ts
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
interface CDOTA_BaseNPC_Hero_Clone
{
is_clone?: boolean;
}
@registerAbility()
export class itachi_crow_clone extends BaseAbility
{
clone?: CDOTA_BaseNPC_Hero;
default_pos: Vector = Vector(25000, -25000 , 0);
/****************************************/
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/itachi/ephemeral.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/itachi/game_sounds_itachi.vsndevts", context);
//PrecacheResource("soundfile", "soundevents/heroes/itachi/game_sounds_vo_itachi.vsndevts", context);
}
/****************************************/
Spawn(): void {
if (!IsServer()) return;
let ability = this;
if (ability == undefined || ability.IsNull()) return;
let caster = this.GetCaster();
Timers.CreateTimer(FrameTime(), () => {
if (ability != undefined && !ability.IsNull() && caster != undefined && !caster.IsNull() && !(caster as CDOTA_BaseNPC_Hero_Clone).is_clone) {
this.SpawnDefferedClone()
}
});
}
/****************************************/
OnSpellStart(): void {
if (this.clone && !this.clone.IsNull() && this.clone.IsAlive()) {
this.UpdateClone(this.clone);
this.FinishCreation(this.clone);
} else {
this.SpawnCloneInstantly();
}
}
/****************************************/
SpawnDefferedClone() {
let caster = this.GetCaster();
this.clone = CreateUnitByName(
caster.GetUnitName(),
this.default_pos,
false,
caster,
caster,
caster.GetTeamNumber()
) as CDOTA_BaseNPC_Hero;
this.clone.StartGesture(GameActivity.DOTA_RUN);
this.clone.AddNewModifier(caster, this, "modifier_itachi_crow_clone_deffered", {duration: -1});
this.SetupClone(this.clone);
}
/****************************************/
SpawnCloneInstantly() {
let caster = this.GetCaster();
this.SetupClone(
CreateUnitByName(
caster.GetUnitName(),
caster.GetAbsOrigin(),
false,
caster,
caster,
caster.GetTeamNumber()
) as CDOTA_BaseNPC_Hero);
}
/****************************************/
SetupClone(clone: CDOTA_BaseNPC_Hero) {
let caster = this.GetCaster();
(clone as CDOTA_BaseNPC_Hero_Clone).is_clone = true;
clone.MakeIllusion();
while (clone.GetLevel() < caster.GetLevel())
clone.HeroLevelUp(false);
clone.SetAbilityPoints(0);
for (let i = 0; i < caster.GetAbilityCount(); i++) {
let ability = caster.GetAbilityByIndex(i);
let clone_ability = clone.GetAbilityByIndex(i);
if (ability && clone_ability)
clone_ability.SetLevel(ability.GetLevel());
}
for (let j = 0; j <= InventorySlot.SLOT_6; j++) {
let item = clone.GetItemInSlot(j);
if (item) clone.RemoveItem(item);
item = caster.GetItemInSlot(j);
if (item) {
clone.AddItemByName(item.GetName());
}
}
let neutral_item = caster.GetItemInSlot(InventorySlot.NEUTRAL_SLOT);
if (neutral_item) clone.AddItemByName(neutral_item.GetName());
clone.SetHealth(caster.GetHealth());
clone.SetMana(caster.GetMana());
}
/****************************************/
UpdateClone(clone: CDOTA_BaseNPC_Hero) {
let caster = this.GetCaster();
while (clone.GetLevel() < caster.GetLevel())
clone.HeroLevelUp(false);
clone.SetAbilityPoints(0);
for (let j = 0; j <= InventorySlot.SLOT_6; j++) {
let item = clone.GetItemInSlot(j);
if (item) clone.RemoveItem(item);
item = caster.GetItemInSlot(j);
if (item) {
clone.AddItemByName(item.GetName());
}
}
let neutral_item = caster.GetItemInSlot(InventorySlot.NEUTRAL_SLOT);
if (neutral_item) clone.AddItemByName(neutral_item.GetName());
clone.SetHealth(caster.GetHealth());
clone.SetMana(caster.GetMana());
}
/****************************************/
FinishCreation(clone: CDOTA_BaseNPC) {
let caster = this.GetCaster() as CDOTA_BaseNPC_Hero;
let invis_duration = this.GetSpecialValueFor("invis_duration");
let clone_duration = this.GetSpecialValueFor("clone_duration");
let frame_delay_count = 2
clone.SetForwardVector(caster.GetForwardVector());
clone.SetControllableByPlayer(caster.GetPlayerID(), true);
clone.SetAbsOrigin(caster.GetAbsOrigin());
if (!caster.IsMoving()) frame_delay_count = 1;
clone.RemoveModifierByName("modifier_itachi_crow_clone_deffered");
ExecuteOrderFromTable({
OrderType: UnitOrder.MOVE_TO_POSITION,
UnitIndex: clone.entindex(),
Position: clone.GetAbsOrigin() + clone.GetForwardVector() * 800 as Vector,
Queue: false
})
clone.AddNewModifier(caster, this, "modifier_itachi_crow_clone_illusion", {duration: clone_duration});
Timers.CreateTimer(FrameTime() * frame_delay_count, () => {
caster.AddNewModifier(caster, this, "modifier_itachi_crow_clone", {duration: invis_duration});
EmitSoundOnLocationForAllies(caster.GetAbsOrigin(), "DOTA_Item.InvisibilitySword.Activate", caster);
});
this.SpawnDefferedClone();
}
}
@registerModifier()
export class modifier_itachi_crow_clone extends BaseModifier
{
move_speed?: number;
/****************************************/
OnCreated(params: object): void {
this.move_speed = this.GetAbility()!.GetSpecialValueFor("bonus_move_speed") + this.GetCaster()!.FindTalentValue("special_bonus_itachi_4");
}
/****************************************/
CheckState(): Partial<Record<ModifierState, boolean>> {
return {
[ModifierState.INVISIBLE]: true,
[ModifierState.NO_UNIT_COLLISION]: true
};
}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.ON_ATTACK_LANDED,
ModifierFunction.ON_ABILITY_EXECUTED,
ModifierFunction.MOVESPEED_BONUS_PERCENTAGE,
ModifierFunction.INVISIBILITY_LEVEL,
]}
/****************************************/
GetModifierMoveSpeedBonus_Percentage(): number {
return this.move_speed!;
}
/****************************************/
GetModifierInvisibilityLevel(): number {
return 1
}
/****************************************/
OnAttackLanded(event: ModifierAttackEvent): void {
if (!IsServer()) return;
if (event.attacker != this.GetParent()) return;
this.Destroy();
}
/****************************************/
OnAbilityExecuted(event: ModifierAbilityEvent): void {
if (!IsServer()) return;
if (event.unit != this.GetParent()) return;
this.Destroy();
}
}
@registerModifier()
export class modifier_itachi_crow_clone_illusion extends BaseModifier
{
outgoing_damage?: number;
fear_radius?: number;
fear_duration?: number;
/****************************************/
IsHidden(): boolean {
if (IsServer()) return true;
return GetLocalPlayerTeam(GetLocalPlayerID()) != this.GetParent().GetTeamNumber();
}
/****************************************/
OnCreated(params: object): void {
if (!IsServer()) return;
let parent = this.GetParent();
let ability = this.GetAbility() as CDOTABaseAbility;
this.outgoing_damage = ability.GetSpecialValueFor("outgoing_damage");
this.fear_radius = ability.GetSpecialValueFor("shard_fear_radius");
this.fear_duration = ability.GetSpecialValueFor("shard_fear_duration");
Timers.CreateTimer(1, () =>{
parent.FadeGesture(GameActivity.DOTA_RUN);
});
}
/****************************************/
OnDestroy(): void {
if (!IsServer()) return;
this.KillClone();
}
/****************************************/
CheckState(): Partial<Record<ModifierState, boolean>> {return {[ModifierState.NO_UNIT_COLLISION]: true}}
/****************************************/
DeclareFunctions(){ return [ModifierFunction.TOTALDAMAGEOUTGOING_PERCENTAGE]}
/****************************************/
GetModifierTotalDamageOutgoing_Percentage() {
return this.outgoing_damage! - 100;
}
/****************************************/
KillClone(): void {
let caster = this.GetCaster();
let parent = this.GetParent();
let origin = parent.GetAbsOrigin();
parent.AddNoDraw();
let ephemeral_fx = ParticleManager.CreateParticle("particles/units/heroes/itachi/ephemeral.vpcf", ParticleAttachment.CUSTOMORIGIN, undefined);
ParticleManager.SetParticleControl(ephemeral_fx, 0, parent.GetAbsOrigin());
ParticleManager.ReleaseParticleIndex(ephemeral_fx);
EmitSoundOnLocationWithCaster(origin, "Hero_Itachi.CrowClone.Death", this.GetCaster()!);
EmitSoundOnLocationWithCaster(origin, "Hero_Itachi.BlinkLayer", this.GetCaster()!);
if (parent.IsAlive()) parent.ForceKill(false);
if (caster?.HasShard()) {
this.FearEnemies(caster, origin);
}
}
/****************************************/
FearEnemies(caster: CDOTA_BaseNPC, position: Vector) {
let enemies = FindUnitsInRadius(
caster.GetTeamNumber(),
position,
undefined,
this.fear_radius!,
UnitTargetTeam.ENEMY,
UnitTargetType.BASIC + UnitTargetType.HERO,
UnitTargetFlags.NONE,
FindOrder.ANY,
false
)
enemies.forEach(enemy => {
enemy.AddNewModifier(caster, this.GetAbility(), "modifier_nevermore_necromastery_fear", {duration: this.fear_duration! * (1 - enemy.GetStatusResistance())});
});
}
}
@registerModifier()
export class modifier_itachi_crow_clone_deffered extends BaseModifier
{
/****************************************/
IsHidden(): boolean {return true}
/****************************************/
CheckState(): Partial<Record<ModifierState, boolean>> {
return {
[ModifierState.NOT_ON_MINIMAP]: true,
[ModifierState.INVISIBLE]: true,
[ModifierState.INVULNERABLE]: true,
[ModifierState.NO_HEALTH_BAR]: true,
};
}
}
|
jaden-young/NWR
|
src/vscripts/lib/utilities.d.ts
|
<reponame>jaden-young/NWR
/** @noSelfInFile */
declare function GetItemIndex(itemName: string, unitEntity: CBaseEntity): number | undefined;
declare function StackItem(cd: number, max_stacks: number, modifier_name: string, ability: CDOTABaseAbility, caster: CDOTA_BaseNPC): void;
declare function tableContains(list: LuaTable, element: any): boolean;
declare function getIndex(list: LuaTable, element: any): number;
declare function getUnitIndex(list: LuaTable, element: any): number;
declare function getIndexTable(list: LuaTable, element: any): number;
declare function shallowcopy<T>(orig: T): T;
declare function ShuffledList(orig_list: LuaTable): LuaTable;
declare function TableFindKey(table: LuaTable, val: any): unknown | undefined;
declare function split(inputstr: string, sep: string): LuaTable;
declare function StringStartsWith(fullstring: string, substring: string): boolean;
declare function VectorString(v: Vector): string;
declare function tobool(s: string | number): boolean;
declare function tablelength(T: LuaTable): number;
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/sasuke/sasuke_great_fireball_technique.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
interface extra {
sound_eid: EntityIndex
}
@registerAbility()
export class sasuke_great_fireball_technique extends BaseAbility {
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/sasuke/sasuke_great_fireball_technique_technique.vpcf", context);
PrecacheResource("particle", "particles/units/heroes/sasuke/sasuke_great_fireball_technique_impact.vpcf", context);
PrecacheResource("particle", "particles/units/heroes/sasuke/sasuke_great_fireball_technique_debuff.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/sasuke/game_sounds_sasuke.vsndevts", context);
//PrecacheResource("soundfile", "soundevents/heroes/sasuke/game_sounds_vo_sasuke.vsndevts", context);
}
/****************************************/
OnAbilityPhaseStart(): boolean {
EmitSoundOn("Hero_Sasuke.GreatFireball.Talk", this.GetCaster());
EmitSoundOn("Hero_Sasuke.GreatFireball.PreCast", this.GetCaster());
return true
}
/****************************************/
OnSpellStart(): void {
let caster = this.GetCaster();
let position = this.GetCursorPosition();
let radius = this.GetSpecialValueFor("radius");
let speed = this.GetSpecialValueFor("speed");
let direction = position - caster.GetAbsOrigin() as Vector;
direction.z = 0;
direction = direction.Normalized();
let sound_ent = CreateModifierThinker(caster, this, "", {}, caster.GetAbsOrigin(), caster.GetTeamNumber(), false);
EmitSoundOn("Hero_Sasuke.GreatFireball.Cast", sound_ent)
ProjectileManager.CreateLinearProjectile({
Ability: this,
EffectName: "particles/units/heroes/sasuke/sasuke_great_fireball_technique.vpcf",
vSpawnOrigin: caster.GetAttachmentOrigin(caster.ScriptLookupAttachment("attach_mouth")) as Vector,
fDistance: this.GetEffectiveCastRange(position, caster),
Source: caster,
fStartRadius: radius,
fEndRadius: radius,
iUnitTargetTeam: UnitTargetTeam.ENEMY,
iUnitTargetType: UnitTargetType.BASIC + UnitTargetType.HERO,
iUnitTargetFlags: UnitTargetFlags.NONE,
vVelocity: direction * speed as Vector,
ExtraData: {
sound_eid: sound_ent.entindex()
}
});
}
/****************************************/
OnProjectileThink_ExtraData(location: Vector, extraData: extra): void {
let sound_ent = EntIndexToHScript(extraData.sound_eid);
if (!sound_ent || sound_ent.IsNull()) return;
sound_ent.SetAbsOrigin(location);
}
/****************************************/
OnProjectileHit_ExtraData(target: CDOTA_BaseNPC | undefined, location: Vector, extraData: extra): boolean | void {
if (!target || !this || this.IsNull()) {
let sound_ent = EntIndexToHScript(extraData.sound_eid);
if (!sound_ent || sound_ent.IsNull()) return;
UTIL_Remove(sound_ent)
return;
}
let caster = this.GetCaster();
let damage_table : ApplyDamageOptions = {
attacker: caster,
victim: target,
damage: this.GetSpecialValueFor("damage"),
damage_type: this.GetAbilityDamageType(),
ability: this
}
ApplyDamage(damage_table);
target.AddNewModifier(caster, this, "modifier_sasuke_great_fireball_technique", {duration: this.GetSpecialValueFor("duration") * (1 - target.GetStatusResistance())});
ParticleManager.ReleaseParticleIndex(
ParticleManager.CreateParticle("particles/units/heroes/sasuke/sasuke_great_fireball_technique_impact.vpcf", ParticleAttachment.ABSORIGIN, target)
);
EmitSoundOn("Hero_Sasuke.GreatFireball.Impact", target);
}
}
@registerModifier()
export class modifier_sasuke_great_fireball_technique extends BaseModifier
{
move_slow?: number;
dps?: number;
damage_table?: ApplyDamageOptions;
/****************************************/
OnCreated(params: object): void {
let ability = this.GetAbility()!;
this.move_slow = -ability.GetSpecialValueFor("move_slow");
this.dps = ability.GetSpecialValueFor("debuff_dps");
let interval = ability.GetSpecialValueFor("dps_interval");
if (!IsServer()) return;
this.damage_table = {
attacker: this.GetCaster()!,
victim: this.GetParent(),
damage: this.dps * interval,
damage_type: this.GetAbility()?.GetAbilityDamageType()!,
ability: this.GetAbility()
}
this.StartIntervalThink(interval);
this.OnIntervalThink();
}
/****************************************/
OnIntervalThink(): void {
ApplyDamage(this.damage_table!);
SendOverheadEventMessage(undefined, OverheadAlert.BONUS_SPELL_DAMAGE, this.GetParent(), this.damage_table!.damage, undefined);
}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.MOVESPEED_BONUS_PERCENTAGE,
]}
/****************************************/
GetModifierMoveSpeedBonus_Percentage(): number {
return this.move_slow!;
}
/****************************************/
GetEffectName(): string {
return "particles/units/heroes/sasuke/sasuke_great_fireball_technique_debuff.vpcf"
}
/****************************************/
GetEffectAttachType(): ParticleAttachment {
return ParticleAttachment.ABSORIGIN_FOLLOW
}
/****************************************/
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/itachi/itachi_phoenix_sage_flame.ts
|
<filename>src/vscripts/abilities/heroes/itachi/itachi_phoenix_sage_flame.ts
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
interface kv
{
cast_id?: number;
}
interface ModifierWithID extends CDOTA_Buff
{
cast_id_tracker: Partial<Record<number, number>>;
}
interface FlameProjectileInfo
{
position: Vector,
range_mult: number
}
@registerAbility()
export class itachi_phoenix_sage_flame extends BaseAbility
{
center_pos: Vector = Vector(0, 0, 0);
right_pos: Vector = Vector(0, 0, 0);
left_pos: Vector = Vector(0, 0, 0);
mid_center_right_pos: Vector = Vector(0, 0, 0);
mid_center_left_pos: Vector = Vector(0, 0, 0);
top_center_right_pos: Vector = Vector(0, 0, 0);
top_center_left_pos: Vector = Vector(0, 0, 0);
order = Array.from({length: 12}, (_, i) => i);
projectiles_info: Record<number, FlameProjectileInfo> = {
[0]: {position: this.right_pos, range_mult: 0.2},
[1]: {position: this.left_pos, range_mult: 0.2},
[2]: {position: this.center_pos, range_mult: 0.25},
[3]: {position: this.right_pos, range_mult: 0.46875},
[4]: {position: this.center_pos, range_mult: 0.46875},
[5]: {position: this.left_pos, range_mult: 0.46875},
[6]: {position: this.mid_center_right_pos, range_mult: 0.625},
[7]: {position: this.mid_center_left_pos, range_mult: 0.625},
[8]: {position: this.right_pos, range_mult: 0.75},
[9]: {position: this.top_center_right_pos, range_mult: 0.75},
[10]: {position: this.top_center_left_pos, range_mult: 0.75},
[11]: {position: this.left_pos, range_mult: 0.75},
}
/****************************************/
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/itachi/itachi_phoenix_sage_flame.vpcf", context);
PrecacheResource("particle", "particles/units/heroes/itachi/itachi_phoenix_sage_flame_layer.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/itachi/game_sounds_vo_itachi.vsndevts", context);
PrecacheResource("soundfile", "soundevents/heroes/itachi/game_sounds_itachi.vsndevts", context);
}
/****************************************/
OnAbilityPhaseStart(): boolean {
EmitSoundOn("VO_Hero_Itachi.PhoenixSageFlame.Talk", this.GetCaster());
return true
}
/****************************************/
OnSpellStart(): void {
let caster = this.GetCaster();
let position = this.GetCursorPosition();
let count = this.GetSpecialValueFor("projectile_count");
let origin = caster.GetAbsOrigin();
let center_dir = (position - origin as Vector).Normalized();
this.SetupPositions(origin, center_dir);
this.UpdateProjectilesInfo();
this.ShuffleLaunchOrder();
this.SetupProjectiles(count, GameRules.GetDOTATime(true, true));
EmitSoundOn("Hero_Itachi.PhoenixSageFlame.Cast", this.GetCaster());
let layer_fx = ParticleManager.CreateParticle("particles/units/heroes/itachi/itachi_phoenix_sage_flame_layer.vpcf", ParticleAttachment.ABSORIGIN_FOLLOW, caster);
ParticleManager.SetParticleControlEnt(layer_fx, 1, caster, ParticleAttachment.ABSORIGIN, "attach_mouth", caster.GetAbsOrigin(), true);
ParticleManager.SetParticleControlForward(layer_fx, 1, caster.GetForwardVector());
ParticleManager.ReleaseParticleIndex(layer_fx);
}
/****************************************/
SetupPositions(origin: Vector, center_dir: Vector) {
let line_end_pos = origin + center_dir * 800 as Vector;
this.center_pos = origin + center_dir * 800 as Vector
this.right_pos = RotatePosition(origin, QAngle(0, -20, 0), line_end_pos);
this.left_pos = RotatePosition(origin, QAngle(0, 20, 0), line_end_pos);
this.mid_center_right_pos = RotatePosition(origin, QAngle(0, -15, 0), line_end_pos);
this.mid_center_left_pos = RotatePosition(origin, QAngle(0, 15, 0), line_end_pos);
this.top_center_right_pos = RotatePosition(origin, QAngle(0, -7.5, 0), line_end_pos);
this.top_center_left_pos = RotatePosition(origin, QAngle(0, 7.5, 0), line_end_pos);
}
/****************************************/
SetupProjectiles(max_count: number, cast_id: number): void {
let delay = this.GetSpecialValueFor("fire_rate");
for (let i = 0; i < this.order.length; i++) {
this.FireProjectile(this.projectiles_info[this.order[i]].position, this.projectiles_info[this.order[i]].range_mult, cast_id, delay * i);
}
}
/****************************************/
UpdateProjectilesInfo() {
this.projectiles_info[0].position = this.right_pos;
this.projectiles_info[1].position = this.left_pos;
this.projectiles_info[2].position = this.center_pos;
this.projectiles_info[3].position = this.right_pos;
this.projectiles_info[4].position = this.center_pos;
this.projectiles_info[5].position = this.left_pos;
this.projectiles_info[6].position = this.mid_center_right_pos;
this.projectiles_info[7].position = this.mid_center_left_pos;
this.projectiles_info[8].position = this.right_pos;
this.projectiles_info[9].position = this.top_center_right_pos;
this.projectiles_info[10].position = this.top_center_left_pos;
this.projectiles_info[11].position = this.left_pos;
}
/****************************************/
FireProjectile(position: Vector, distance_mult: number, cast_id: number, delay: number): void {
Timers.CreateTimer(delay, () => {
let caster = this.GetCaster();
let range = this.GetCastRange(position, undefined);
let radius = this.GetSpecialValueFor("proj_radius");
let direction = position - caster.GetAbsOrigin() as Vector;
direction.z = 0;
direction = direction.Normalized();
ProjectileManager.CreateLinearProjectile({
Ability: this,
EffectName: "particles/base_attacks/ranged_tower_bad_linear.vpcf",
vSpawnOrigin: caster.GetAttachmentOrigin(caster.ScriptLookupAttachment("attach_mouth")),
fDistance: range * distance_mult,
fStartRadius: radius,
fEndRadius: radius,
Source: caster,
iUnitTargetTeam: UnitTargetTeam.ENEMY,
iUnitTargetType: UnitTargetType.HERO + UnitTargetType.BASIC,
vVelocity: direction * this.GetSpecialValueFor("speed") as Vector,
ExtraData: {
cast_id: cast_id
}
});
})
}
/****************************************/
OnProjectileHit_ExtraData(target: CDOTA_BaseNPC | undefined, location: Vector, extraData: kv): boolean | void {
if (!target) {
let caster = this.GetCaster();
let max_hits = this.GetSpecialValueFor("max_hits");
let duration = this.GetSpecialValueFor("duration");
let id = extraData.cast_id as number;
let enemies = FindUnitsInRadius(
caster.GetTeamNumber(),
location,
undefined,
this.GetSpecialValueFor("proj_radius"),
UnitTargetTeam.ENEMY,
UnitTargetType.BASIC + UnitTargetType.HERO,
UnitTargetFlags.NONE,
FindOrder.ANY,
false
)
enemies.forEach(enemy => {
let modifier = enemy.FindModifierByName("modifier_itachi_phoenix_sage_flame") as ModifierWithID;
if (modifier && modifier.cast_id_tracker[id] && modifier.cast_id_tracker[id]! >= max_hits) return false;
enemy.AddNewModifier(this.GetCaster(), this, "modifier_itachi_phoenix_sage_flame", {duration: duration, cast_id: extraData.cast_id});
EmitSoundOn("Hero_Itachi.PhoenixSageFlame.Hit", enemy);
});
EmitSoundOnLocationWithCaster(location, "Hero_Itachi.PhoenixSageFlame.Impact", this.GetCaster());
this.DisplayTestingParticles(location);
return true;
}
return false;
}
/****************************************/
DisplayTestingParticles(location: Vector) {
let a = ParticleManager.CreateParticle("particles/testing_circle.vpcf", ParticleAttachment.WORLDORIGIN, undefined);
ParticleManager.SetParticleControl(a, 0, location);
ParticleManager.SetParticleControl(a, 2, Vector(this.GetSpecialValueFor("proj_radius"), 0, 0));
ParticleManager.ReleaseParticleIndex(a);
let b = ParticleManager.CreateParticle("particles/testing_circle.vpcf", ParticleAttachment.WORLDORIGIN, undefined);
ParticleManager.SetParticleControl(b, 0, location);
ParticleManager.SetParticleControl(b, 1, Vector(0, 0, 0));
ParticleManager.SetParticleControl(b, 2, Vector(0, 0, 0));
ParticleManager.ReleaseParticleIndex(b);
}
/****************************************/
ShuffleLaunchOrder() {
let i = this.order.length, k, temp;
while(--i > 0){
k = Math.floor(Math.random() * (i+1));
temp = this.order[k];
this.order[k] = this.order[i];
this.order[i] = temp;
}
}
}
@registerModifier()
export class modifier_itachi_phoenix_sage_flame extends BaseModifier implements ModifierWithID
{
magic_res_reduction?: number;
move_slow?: number;
max_hits?: number;
cast_id_tracker: Partial<Record<number, number>> = {};
damage_table?: ApplyDamageOptions;
/****************************************/
OnCreated(params: kv): void {
let ability = this.GetAbility()!;
let damage = ability.GetSpecialValueFor("damage_per_proj");
this.magic_res_reduction = -ability.GetSpecialValueFor("magic_res_reduction") - this.GetCaster()!.FindTalentValue("special_bonus_itachi_1");
this.move_slow = -ability.GetSpecialValueFor("move_slow");
this.max_hits = ability.GetSpecialValueFor("max_hits");
if (!IsServer()) return;
this.cast_id_tracker[params.cast_id!] = 1;
this.SetStackCount(1);
this.damage_table = {
attacker: this.GetCaster() as CDOTA_BaseNPC,
victim: this.GetParent(),
damage: damage,
damage_type: ability.GetAbilityDamageType(),
ability: ability
}
ApplyDamage(this.damage_table);
}
/****************************************/
OnRefresh(params: kv): void {
if (!IsServer()) return;
this.cast_id_tracker[params.cast_id!] ? this.cast_id_tracker[params.cast_id!]!++ : this.cast_id_tracker[params.cast_id!] = 1;
ApplyDamage(this.damage_table!);
this.IncrementStackCount();
}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.MOVESPEED_BONUS_PERCENTAGE,
ModifierFunction.MAGICAL_RESISTANCE_BONUS
]}
/****************************************/
GetModifierMoveSpeedBonus_Percentage(): number {
return this.move_slow! * this.GetStackCount();
}
/****************************************/
GetModifierMagicalResistanceBonus(): number {
return this.magic_res_reduction! * this.GetStackCount();
}
/****************************************/
GetEffectName(): string {
return "particles/econ/events/ti10/hot_potato/hot_potato_debuff.vpcf";
}
/****************************************/
GetEffectAttachType(): ParticleAttachment {
return ParticleAttachment.ABSORIGIN_FOLLOW;
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/shikamaru/shikamaru_innate_passive.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class shikamaru_innate_passive extends BaseAbility
{
OnUpgrade(): void {
//Should refresh modifier on eanch upgrade
let caster = this.GetCaster()
caster.FindModifierByName(this.GetIntrinsicModifierName())?.ForceRefresh()
}
GetIntrinsicModifierName(): string {
return "modifier_shikamaru_innate_passive_intrinsic"
}
ApplyDebuffStacks(target: CDOTA_BaseNPC, stacks_count: number){
let debuff_duration = this.GetSpecialValueFor("debuff_duration")
let debuff_modifier = target.AddNewModifier(this.GetCaster(), this, "modifier_shikamaru_innate_passive_debuff", {duration:debuff_duration})
debuff_modifier.SetStackCount(stacks_count)
}
ResetStacks(){
let caster = this.GetCaster()
let stack_modifier = caster.FindModifierByName(this.GetIntrinsicModifierName())
stack_modifier?.SetStackCount(0)
}
}
@registerModifier()
export class modifier_shikamaru_innate_passive_intrinsic extends BaseModifier
{
IsDebuff(): boolean {
return false
}
IsPurgable(): boolean {
return false
}
IsPermanent(): boolean {
return true
}
IsHidden(): boolean {
return false
}
OnCreated(params: object): void {
let ability = this.GetAbility()
if(!ability){return}
let charge_rate_in_seconds = ability.GetSpecialValueFor("charge_rate_in_seconds")
this.StartIntervalThink(charge_rate_in_seconds)
}
OnIntervalThink(): void {
let ability = this.GetAbility()
if(!ability){return}
let max_stacks = ability.GetSpecialValueFor("max_stacks")
if(this.GetStackCount() < max_stacks){
this.IncrementStackCount()
}
}
}
@registerModifier()
export class modifier_shikamaru_innate_passive_debuff extends BaseModifier
{
total_armor_reduction_per_stack_constant: number = 0
magic_resistance_reduction_per_stack_percentage: number = 0
IsDebuff(): boolean {
return true
}
IsHidden(): boolean {
return false
}
IsPurgable(): boolean {
return true
}
OnCreated(params: object): void {
let ability = this.GetAbility()
if(!ability){return}
this.total_armor_reduction_per_stack_constant = ability.GetSpecialValueFor("total_armor_reduction_per_stack_constant_base") + (ability.GetSpecialValueFor("total_armor_reduction_per_stack_constant_per_level_bonus") * (ability.GetLevel() - 1))
this.magic_resistance_reduction_per_stack_percentage = ability.GetSpecialValueFor("magic_resistance_reduction_per_stack_percentage_base") + (ability.GetSpecialValueFor("magic_resistance_reduction_per_stack_percentage_per_level_bonus") * (ability.GetLevel() - 1))
}
DeclareFunctions(){
return [ModifierFunction.PHYSICAL_ARMOR_BONUS ,
ModifierFunction.MAGICAL_RESISTANCE_BONUS ]
}
GetModifierPhysicalArmorBonus(){
return -1 * (this.total_armor_reduction_per_stack_constant * this.GetStackCount())
}
GetModifierMagicalResistanceBonus(){
return -1 * (this.magic_resistance_reduction_per_stack_percentage * this.GetStackCount())
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/gaara/gaara_innate_passive.ts
|
<reponame>jaden-young/NWR
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter";
@registerAbility()
export class gaara_innate_passive extends BaseAbility
{
OnUpgrade(): void {
//Should refresh modifier on each upgrade
this.GetCaster().FindModifierByName(this.GetIntrinsicModifierName())?.ForceRefresh()
}
GetIntrinsicModifierName(): string {
return "modifier_gaara_innate_passive_intrinsic"
}
ApplyPocketSandDebuff(target: CDOTA_BaseNPC){
if(target.IsBuilding()){return}
let duration = this.GetSpecialValueFor("duration_base") + this.GetSpecialValueFor("duration_per_level_bonus")*(this.GetLevel()-1)
target.AddNewModifier(this.GetCaster(), this, "modifier_gaara_innate_passive_debuff", {duration: duration})
}
}
@registerModifier()
export class modifier_gaara_innate_passive_intrinsic extends BaseModifier {
parent?: CDOTA_BaseNPC;
duration?: number;
IsHidden(): boolean {
return true
}
IsDebuff(): boolean {
return false
}
IsPurgable(): boolean {
return false
}
AllowIllusionDuplicate(): boolean {
return true
}
DeclareFunctions() {
return [ModifierFunction.ON_ATTACK_LANDED]
}
OnCreated(params: object): void {
const ability = this.GetAbility()
this.parent = this.GetParent()
}
OnRefresh(params: object): void {
const ability = this.GetAbility()
}
OnAttackLanded(event: ModifierAttackEvent) {
if(event.attacker !== this.parent){return}
if(event.attacker.GetTeam() === event.target.GetTeam()){return}
(this.GetAbility() as gaara_innate_passive).ApplyPocketSandDebuff(event.target)
}
}
@registerModifier()
export class modifier_gaara_innate_passive_debuff extends BaseModifier {
attack_speed_slow?: number;
vision_reduction_percentage?: number;
IsPurgable(): boolean {
return true;
}
IsDebuff(): boolean {
return true
}
IsHidden(): boolean {
return false
}
OnCreated(params: object): void {
const ability = this.GetAbility()
if(ability){
this.attack_speed_slow = ability.GetSpecialValueFor("attack_speed_slow_base") + ability.GetSpecialValueFor("attack_speed_slow_per_level_bonus")*(ability.GetLevel()-1)
this.vision_reduction_percentage = ability.GetSpecialValueFor("vision_reduction_percentage_base")
}
}
OnRefresh(params: object): void {
const ability = this.GetAbility()
if(ability){
this.attack_speed_slow = ability.GetSpecialValueFor("attack_speed_slow_base") + ability.GetSpecialValueFor("attack_speed_slow_per_level_bonus")*(ability.GetLevel()-1)
this.vision_reduction_percentage = ability.GetSpecialValueFor("vision_reduction_percentage_base")
}
}
DeclareFunctions() {
return [ModifierFunction.ATTACKSPEED_BONUS_CONSTANT,
ModifierFunction.BONUS_VISION_PERCENTAGE]
}
GetModifierAttackSpeedBonus_Constant(){
return (this.attack_speed_slow ?? 0) * -1
}
GetBonusVisionPercentage(){
return (this.vision_reduction_percentage ?? 0) * -1
}
}
|
jaden-young/NWR
|
src/panorama/barebones_notifications.ts
|
<reponame>jaden-young/NWR<filename>src/panorama/barebones_notifications.ts
//@ts-nocheck
function TopNotification( msg ) {
AddNotification(msg, $('#TopNotifications'));
}
function BottomNotification(msg) {
AddNotification(msg, $('#BottomNotifications'));
}
function TopRemoveNotification(msg){
RemoveNotification(msg, $('#TopNotifications'));
}
function BottomRemoveNotification(msg){
RemoveNotification(msg, $('#BottomNotifications'));
}
function RemoveNotification(msg, panel){
var count = msg.count;
if (count > 0 && panel.GetChildCount() > 0){
var start = panel.GetChildCount() - count;
if (start < 0)
start = 0;
for (i=start;i<panel.GetChildCount(); i++){
var lastPanel = panel.GetChild(i);
//lastPanel.SetAttributeInt("deleted", 1);
lastPanel.deleted = true;
lastPanel.DeleteAsync(0);
}
}
}
function AddNotification(msg, panel) {
var newNotification = true;
var lastNotification = panel.GetChild(panel.GetChildCount() - 1)
//$.Msg(msg)
msg.continue = msg.continue || false;
//msg.continue = true;
if (lastNotification != null && msg.continue)
newNotification = false;
if (newNotification){
lastNotification = $.CreatePanel('Panel', panel, '');
lastNotification.AddClass('NotificationLine')
lastNotification.hittest = false;
}
var notification = null;
if (msg.hero != null)
notification = $.CreatePanel('DOTAHeroImage', lastNotification, '');
else if (msg.image != null)
notification = $.CreatePanel('Image', lastNotification, '');
else if (msg.ability != null)
notification = $.CreatePanel('DOTAAbilityImage', lastNotification, '');
else if (msg.item != null)
notification = $.CreatePanel('DOTAItemImage', lastNotification, '');
else
notification = $.CreatePanel('Label', lastNotification, '');
if (typeof(msg.duration) != "number"){
//$.Msg("[Notifications] Notification Duration is not a number!");
msg.duration = 3
}
if (newNotification){
$.Schedule(msg.duration, function(){
//$.Msg('callback')
if (lastNotification.deleted)
return;
lastNotification.DeleteAsync(0);
});
}
if (msg.hero != null){
notification.heroimagestyle = msg.imagestyle || "icon";
notification.heroname = msg.hero
notification.hittest = false;
} else if (msg.image != null){
notification.SetImage(msg.image);
notification.hittest = false;
} else if (msg.ability != null){
notification.abilityname = msg.ability
notification.hittest = false;
} else if (msg.item != null){
notification.itemname = msg.item
notification.hittest = false;
} else{
notification.html = true;
var text = msg.text || "No Text provided";
notification.text = $.Localize(text)
notification.hittest = false;
notification.AddClass('TitleText');
}
if (msg.class)
notification.AddClass(msg.class);
else
notification.AddClass('NotificationMessage');
if (msg.style){
for (var key in msg.style){
var value = msg.style[key]
notification.style[key] = value;
}
}
}
(function () {
GameEvents.Subscribe( "top_notification", TopNotification );
GameEvents.Subscribe( "bottom_notification", BottomNotification );
GameEvents.Subscribe( "top_remove_notification", TopRemoveNotification );
GameEvents.Subscribe( "bottom_remove_notification", BottomRemoveNotification );
})();
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/anko/anko_innate_passive.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter";
@registerAbility()
export class anko_innate_passive extends BaseAbility
{
OnUpgrade(): void {
//Should refresh modifier on eanch upgrade
this.GetCaster().FindModifierByName(this.GetIntrinsicModifierName())?.ForceRefresh()
}
GetIntrinsicModifierName(): string {
return "modifier_anko_innate_passive"
}
Precache(context: CScriptPrecacheContext){
PrecacheResource( "soundfile", "soundevents/heroes/anko/anko_passive_trigger.vsndevts", context )
}
}
@registerModifier()
export class modifier_anko_innate_passive extends BaseModifier {
reset_interval?: number;
total_damage_taken?: number;
damage_threshold: number = 0;
parent?: CDOTA_BaseNPC;
spell_lifesteal?: number;
damage: number = 0;
IsHidden(): boolean {
return false
}
IsDebuff(): boolean {
return false
}
IsPurgable(): boolean {
return false
}
AllowIllusionDuplicate(): boolean {
return true
}
DeclareFunctions() {
return [ModifierFunction.SPELL_LIFESTEAL_AMPLIFY_PERCENTAGE,
ModifierFunction.ON_TAKEDAMAGE]
}
GetModifierSpellLifestealRegenAmplify_Percentage() {
return this.spell_lifesteal
}
OnCreated(params: object): void {
const ability = this.GetAbility()
this.parent = this.GetParent()
if(ability){
this.reset_interval = ability.GetSpecialValueFor("damage_threshold_reset_time")
this.spell_lifesteal = ability.GetSpecialValueFor("spell_lifesteal_base") + ability.GetSpecialValueFor("spell_lifesteal_per_level_bonus")*(ability.GetLevel()-1)
this.damage_threshold = ability.GetSpecialValueFor("damage_threshold_base") + ability.GetSpecialValueFor("damage_threshold_per_level_bonus")*(ability.GetLevel()-1)
}
if(!IsServer()){ return }
this.damage = 0;
}
OnRefresh(params: object): void {
const ability = this.GetAbility()
if(ability){
this.reset_interval = ability.GetSpecialValueFor("damage_threshold_reset_time")
this.spell_lifesteal = ability.GetSpecialValueFor("spell_lifesteal_base") + ability.GetSpecialValueFor("spell_lifesteal_per_level_bonus")*(ability.GetLevel()-1)
this.damage_threshold = ability.GetSpecialValueFor("damage_threshold_base") + ability.GetSpecialValueFor("damage_threshold_per_level_bonus")*(ability.GetLevel()-1)
}
}
CountDamageForPassivePruge(event: ModifierInstanceEvent): void{
if(event.unit === this.parent) {
if(this.parent.PassivesDisabled()) {return} //don't count if caster is broken
if(!event.attacker.GetPlayerOwner()) {return} //don't count if damage suce is not player
this.StartIntervalThink(this.reset_interval ? this.reset_interval : 0)
this.damage += event.damage
if(this.damage < this.damage_threshold){ return }
this.damage = 0
this.parent.Purge(
false, //remove positive buffs
true, //remove debuffs
false, //frame only
true, // removes stuns
true //removes exceptions
)
//TODO: Play SFX\VFX
}
}
ApplySpellLifeSteal(event: ModifierInstanceEvent): void {
//Spell lifesteal bit
if(event.damage_category !== DamageCategory.SPELL) {return}
if(event.damage <= 0) {return}
if(event.unit.GetTeam() === this.parent?.GetTeam()){ return}
//splitting this in case we need different numbers for creeps in future
if(event.unit.IsHero()){
let amount_to_heal = event.damage * (this.spell_lifesteal ?? 0) * 0.01
this.parent?.Heal(amount_to_heal, this.GetAbility())
}else{
let amount_to_heal = event.damage * (this.spell_lifesteal ?? 0) * 0.01
this.parent?.Heal(amount_to_heal, this.GetAbility())
}
//Play spell lifesteal VFX
const lifesteal_vfx = ParticleManager.CreateParticle('particles/items3_fx/octarine_core_lifesteal.vpcf', ParticleAttachment.ABSORIGIN_FOLLOW, this.parent)
ParticleManager.SetParticleControl(lifesteal_vfx, 0, event.attacker.GetAbsOrigin());
ParticleManager.ReleaseParticleIndex(lifesteal_vfx);
}
OnTakeDamage(event: ModifierInstanceEvent): void {
if(!IsServer()) {return}
this.CountDamageForPassivePruge(event)
this.ApplySpellLifeSteal(event)
}
OnIntervalThink(): void {
this.StartIntervalThink(-1)
this.damage = 0
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/yondaime/yondaime_innate_passive.ts
|
<filename>src/vscripts/abilities/heroes/yondaime/yondaime_innate_passive.ts
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class yondaime_innate_passive extends BaseAbility
{
OnUpgrade(): void {
//Should refresh modifier on eanch upgrade
this.GetCaster().FindModifierByName(this.GetIntrinsicModifierName())?.ForceRefresh()
}
GetIntrinsicModifierName(): string {
return "modifier_yondaime_innate_passive_intrinsic"
}
}
@registerModifier()
export class modifier_yondaime_innate_passive_intrinsic extends BaseModifier
{
move_speed_percentage: number = 0
attack_damage_move_speed_percentage: number = 0
IsHidden(): boolean {
return false
}
IsPermanent(): boolean {
return true
}
IsPurgable(): boolean {
return false
}
DeclareFunctions(){
return [ModifierFunction.PREATTACK_BONUS_DAMAGE,
ModifierFunction.MOVESPEED_BONUS_PERCENTAGE]
}
OnCreated(params: object): void {
let ability = this.GetAbility()
if(ability){
this.move_speed_percentage = ability.GetSpecialValueFor("move_speed_percentage_base") + (ability.GetSpecialValueFor("move_speed_percentage_per_level_bonus") * (ability.GetLevel() - 1))
this.attack_damage_move_speed_percentage = ability.GetSpecialValueFor("attack_damage_move_speed_percentage_base") + (ability.GetSpecialValueFor("attack_damage_move_speed_percentage_per_level_bonus") * (ability.GetLevel() - 1))
}
}
OnRefresh(params: object): void {
let ability = this.GetAbility()
if(ability){
this.move_speed_percentage = ability.GetSpecialValueFor("move_speed_percentage_base") + (ability.GetSpecialValueFor("move_speed_percentage_per_level_bonus") * (ability.GetLevel() - 1))
this.attack_damage_move_speed_percentage = ability.GetSpecialValueFor("attack_damage_move_speed_percentage_base") + (ability.GetSpecialValueFor("attack_damage_move_speed_percentage_per_level_bonus") * (ability.GetLevel() - 1))
}
}
GetModifierMoveSpeedBonus_Percentage(){
return this.move_speed_percentage
}
GetModifierPreAttack_BonusDamage(){
let bonus_attack_damage = this.attack_damage_move_speed_percentage * this.GetParent().GetIdealSpeed() * 0.01
this.SetStackCount(bonus_attack_damage)
return bonus_attack_damage
}
}
|
jaden-young/NWR
|
src/vscripts/lib/better_cooldown.d.ts
|
declare interface CDOTABaseAbility {
SetFrozenCooldown(state:boolean):void
SetCooldownSpeed(speed:number):void
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/sai/sai_bash.ts
|
<gh_stars>0
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class sai_bash extends BaseAbility
{
GetIntrinsicModifierName(): string {
return "modifier_sai_bash"
}
}
@registerModifier()
export class modifier_sai_bash extends BaseModifier
{
bash_chance?: number;
bash_damage?: number;
bash_duration?: number;
is_bash?: boolean;
/****************************************/
IsHidden(): boolean {return true}
IsPurgable(): boolean {return false}
RemoveOnDeath(): boolean {return false}
/****************************************/
OnCreated(params: object): void {
let ability = this.GetAbility()!;
this.bash_chance = ability.GetSpecialValueFor("bash_chance");
this.bash_damage = ability.GetSpecialValueFor("bash_damage");
this.bash_duration = ability.GetSpecialValueFor("bash_duration");
}
/****************************************/
OnRefresh(params: object): void {
this.OnCreated(params);
}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.PROCATTACK_BONUS_DAMAGE_PHYSICAL
]}
/****************************************/
GetModifierProcAttack_BonusDamage_Physical(event: ModifierAttackEvent): number {
if (!IsServer()) return 0;
let attacker = event.attacker;
let target = event.target;
let ability = this.GetAbility();
if (!attacker || !target || !ability) return 0;
if (target.IsBuilding() || target.IsOther() || !RollPseudoRandomPercentage(this.bash_chance!, PseudoRandom.CUSTOM_GAME_1, attacker)) return 0;
target.AddNewModifier(attacker, ability, "modifier_bashed", {duration: this.bash_duration! * (1 - target.GetStatusResistance())});
EmitSoundOn("Hero_Sai.Summons.Bash", target);
return this.bash_damage! + attacker.FindTalentValue("special_bonus_sai_5");
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/onoki/onoki_innate_passive.ts
|
<reponame>jaden-young/NWR<filename>src/vscripts/abilities/heroes/onoki/onoki_innate_passive.ts
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class onoki_innate_passive extends BaseAbility
{
OnUpgrade(): void {
//Should refresh modifier on eanch upgrade
this.GetCaster().FindModifierByName(this.GetIntrinsicModifierName())?.ForceRefresh()
}
GetIntrinsicModifierName(): string {
return "modifier_onoki_innate_passive_intrinsic"
}
Precache(context: CScriptPrecacheContext){
PrecacheResource("particle", "particles/units/heroes/onoki/onoki_innate_passive_impact.vpcf", context)
PrecacheResource("particle", "particles/units/heroes/onoki/onoki_innate_passive_debuff.vpcf", context)
PrecacheResource("soundfile", "soundevents/heroes/onoki/onoki_passive_trigger.vsndevts", context )
}
}
@registerModifier()
export class modifier_onoki_innate_passive_intrinsic extends BaseModifier
{
attack_bonus_per_armor: number = 0
armor_reduction_duration: number = 0
IsDebuff(): boolean {
return false
}
IsHidden(): boolean {
return true
}
IsPermanent(): boolean {
return true
}
IsPurgable(): boolean {
return false
}
OnCreated(params: object): void {
let ability = this.GetAbility()
if(ability){
this.attack_bonus_per_armor = ability.GetSpecialValueFor("attack_bonus_per_armor_multiplier")
this.armor_reduction_duration = ability.GetSpecialValueFor("armor_reduction_duration")
}
}
OnRefresh(params: object): void {
let ability = this.GetAbility()
if(ability){
this.attack_bonus_per_armor = ability.GetSpecialValueFor("attack_bonus_per_armor_multiplier")
this.armor_reduction_duration = ability.GetSpecialValueFor("armor_reduction_duration")
}
}
DeclareFunctions(){
return [ModifierFunction.ON_ATTACK_LANDED]
}
OnAttackLanded(event: ModifierAttackEvent){
let ability = this.GetAbility()
if(!ability){return}
if(event.attacker !== this.GetParent()){return}
if(event.target.IsBuilding()){return}
if(!ability.IsCooldownReady()){return}
let damage = this.attack_bonus_per_armor * this.GetParent().GetPhysicalArmorValue(false)
let damage_options = {
victim: event.target,
attacker: this.GetParent(),
damage: damage,
damage_type: DamageTypes.PHYSICAL,
damage_flags: DamageFlag.NONE
}
ApplyDamage(damage_options)
let impact_vfx = ParticleManager.CreateParticle("particles/units/heroes/onoki/onoki_innate_passive_impact.vpcf", ParticleAttachment.ABSORIGIN_FOLLOW, event.target)
ParticleManager.DestroyParticle(impact_vfx, false)
ParticleManager.ReleaseParticleIndex(impact_vfx)
SendOverheadEventMessage(
undefined,
OverheadAlert.BONUS_SPELL_DAMAGE,
event.target,
damage,
this.GetCaster()?.GetPlayerOwner()
)
if(!IsServer()){return}
let mod = event.target.AddNewModifier(this.GetParent(), ability, "modifier_onoki_innate_passive_victim", {duration: this.armor_reduction_duration})
print(mod)
ability.StartCooldown(ability.GetEffectiveCooldown(ability.GetLevel()))
event.target.EmitSound("onoki_passive_trigger")
}
}
@registerModifier()
export class modifier_onoki_innate_passive_victim extends BaseModifier
{
armor_reduction: number = 0
IsDebuff(): boolean {
return true
}
IsHidden(): boolean {
return false
}
OnCreated(): void {
let ability = this.GetAbility()
if(ability){
this.armor_reduction = ability.GetSpecialValueFor("armor_reduction_base") + (ability.GetSpecialValueFor("armor_reduction_per_level_bonus") * (ability.GetCaster().GetLevel() - 1))
}
}
DeclareFunctions(){
return [ModifierFunction.PHYSICAL_ARMOR_BONUS]
}
GetModifierPhysicalArmorBonus(){
return -1 * this.armor_reduction
}
GetEffectName(): string {
return "particles/units/heroes/onoki/onoki_innate_passive_debuff.vpcf"
}
GetEffectAttachType(): ParticleAttachment {
return ParticleAttachment.ABSORIGIN_FOLLOW
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/guy/guy_dynamic_entry.ts
|
<reponame>jaden-young/NWR<gh_stars>0
import { BaseAbility, BaseModifier, BaseModifierMotionHorizontal, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
interface kv {
target: EntityIndex;
}
@registerAbility()
export class guy_dynamic_entry extends BaseAbility
{
lightning_blade_fx?: ParticleID;
active_target?: CDOTA_BaseNPC;
/****************************************/
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/guy/guy_dynamic_entry_impact_base.vpcf", context);
PrecacheResource("particle", "particles/units/heroes/guy/guy_dynamic_entry_six_gates_impact_base.vpcf", context);
PrecacheResource("particle", "particles/units/heroes/guy/guy_dynamic_entry_armor_debuff_base.vpcf", context);
PrecacheResource("particle", "particles/units/heroes/guy/guy_dynamic_entry_armor_debuff_gates.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/guy/game_sounds_guy.vsndevts", context);
PrecacheResource("soundfile", "soundevents/heroes/guy/game_sounds_vo_guy.vsndevts", context);
}
/****************************************/
GetAbilityTextureName(): string {
return (this.GetCaster() && this.GetCaster().HasModifier("modifier_guy_seventh_gate")) ? "guy_dynamic_entry_gates" : "guy_dynamic_entry";
}
/****************************************/
GetCastRange(location: Vector, target: CDOTA_BaseNPC | undefined): number {
if (this.GetCaster().HasModifier("modifier_guy_seventh_gate"))
return super.GetCastRange(location, target) + this.GetCaster().FindTalentValue("special_bonus_guy_5") + this.GetSpecialValueFor("castrange_ult_bonus");
else
return super.GetCastRange(location, target) + this.GetCaster().FindTalentValue("special_bonus_guy_5");
}
/****************************************/
OnAbilityPhaseStart(): boolean {
EmitSoundOn("Hero_Guy.DynamicEntry.Cast", this.GetCaster());
return true
}
/****************************************/
OnSpellStart(): void {
let caster = this.GetCaster();
let target = this.GetCursorTarget();
if (target?.TriggerSpellAbsorb(this)) return;
caster.AddNewModifier(caster, this, "modifier_guy_dynamic_entry", {duration: -1, target: target?.entindex()})
caster.HasModifier("modifier_guy_seventh_gate") ?
EmitSoundOn("VO_Hero_Guy.DynamicEntryGate.Cast", caster) :
EmitSoundOn("VO_Hero_Guy.DynamicEntry.Cast", caster);
}
}
@registerModifier()
export class modifier_guy_dynamic_entry extends BaseModifierMotionHorizontal
{
target?: CDOTA_BaseNPC;
duration?: number;
speed?: number;
damage?: number;
stop_distance?: number;
/****************************************/
IsPurgable(): boolean {return false}
RemoveOnDeath(): boolean {return true}
/****************************************/
OnCreated(params: kv): void {
let ability = this.GetAbility()!;
this.duration = ability.GetSpecialValueFor("duration");
this.speed = ability.GetSpecialValueFor("speed");
this.damage = ability.GetSpecialValueFor("damage");
this.stop_distance = ability.GetSpecialValueFor("stop_distance");
if (!IsServer()) return;
this.target = EntIndexToHScript(params.target) as CDOTA_BaseNPC;
if (!this.ApplyHorizontalMotionController()) {
this.Destroy()
return;
}
}
/****************************************/
OnDestroy(): void {
if (!IsServer()) return;
let parent = this.GetParent();
parent.RemoveHorizontalMotionController(this);
if (this.target && !this.target.IsNull() && this.target.HasModifier("modifier_guy_dynamic_entry_target")) {
this.target.RemoveModifierByName("modifier_guy_dynamic_entry_target");
}
}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.OVERRIDE_ANIMATION,
]}
/****************************************/
CheckState(): Partial<Record<ModifierState, boolean>> {
return {
[ModifierState.NO_UNIT_COLLISION]: true,
[ModifierState.FLYING_FOR_PATHING_PURPOSES_ONLY]: true,
};
}
/****************************************/
UpdateHorizontalMotion(parent: CDOTA_BaseNPC, dt: number): void {
let direction = (this.target!.GetAbsOrigin() - parent.GetAbsOrigin() as Vector).Normalized();
this.CheckConditions();
if (this.CheckDistance()) return;
parent.FaceTowards(this.target!.GetAbsOrigin());
parent.SetAbsOrigin(parent.GetAbsOrigin() + this.speed! * direction * dt as Vector);
}
/****************************************/
OnHorizontalMotionInterrupted(): void {
this.Destroy();
}
/****************************************/
GetOverrideAnimation(): GameActivity{
return GameActivity.DOTA_CHANNEL_ABILITY_1;
}
/****************************************/
CheckConditions(): void {
let parent = this.GetParent();
if (parent.IsStunned() || parent.IsHexed() || parent.IsRooted() || this.target?.IsNull() || !this.target?.IsAlive()) this.Destroy();
}
/****************************************/
CheckDistance(): boolean {
let parent = this.GetParent();
let distance = (parent.GetAbsOrigin() - this.target!.GetAbsOrigin() as Vector).Length2D()
if (distance <= 128) {
let ability = this.GetAbility();
if (!this.target?.IsMagicImmune()) {
ApplyDamage({
attacker: parent,
victim: this.target!,
damage: this.damage!,
damage_type: this.GetAbility()!.GetAbilityDamageType(),
ability: this.GetAbility(),
})
this.target?.AddNewModifier(parent, ability, "modifier_guy_dynamic_entry_debuff", {duration: this.duration! * (1 - this.target.GetStatusResistance())})
}
this.ShowEffects();
this.Destroy()
return true;
} else if (distance > this.stop_distance!) {
this.Destroy();
return true;
}
return false;
}
/****************************************/
ShowEffects() {
let parent = this.GetParent();
let gates_open = parent.HasModifier("modifier_guy_seventh_gate");
let impact_particle = gates_open ? "particles/units/heroes/guy/guy_dynamic_entry_six_gates_impact_base.vpcf" : "particles/units/heroes/guy/guy_dynamic_entry_impact_base.vpcf";
let impact_fx = ParticleManager.CreateParticle(impact_particle, ParticleAttachment.ABSORIGIN_FOLLOW, this.target);
ParticleManager.SetParticleControlEnt(impact_fx, 1, this.target!, ParticleAttachment.ABSORIGIN, "attach_hitloc", this.target!.GetAbsOrigin(), true);
ParticleManager.SetParticleControlEnt(impact_fx, 3, this.target!, ParticleAttachment.ABSORIGIN, "attach_hitloc", this.target!.GetAbsOrigin(), true);
ParticleManager.SetParticleControl(impact_fx, 6, Vector(150, 1, 1));
ParticleManager.ReleaseParticleIndex(impact_fx);
gates_open ? EmitSoundOn("Hero_Guy.DynamicEntryGate.Impact", this.target!) : EmitSoundOn("Hero_Guy.DynamicEntry.Impact", this.target!);
// EmitSoundOn("Hero_Guy.DynamicEntry.ImpactLayer", this.target!);
}
}
@registerModifier()
export class modifier_guy_dynamic_entry_debuff extends BaseModifier
{
armor_reduction?: number;
effect_name: string = "particles/units/heroes/guy/guy_dynamic_entry_armor_debuff_base.vpcf";
/****************************************/
OnCreated(params: object): void {
let ability = this.GetAbility();
let caster = this.GetCaster();
let gates_open = caster?.HasModifier("modifier_guy_seventh_gate");
this.armor_reduction = -ability!.GetSpecialValueFor("armor_reduction");
if (gates_open) {
this.armor_reduction -= ability!.GetSpecialValueFor("armor_ult_bonus");
this.effect_name = "particles/units/heroes/guy/guy_dynamic_entry_armor_debuff_gates.vpcf";
}
}
/****************************************/
DeclareFunctions(){ return [ModifierFunction.PHYSICAL_ARMOR_BONUS]}
/****************************************/
GetModifierPhysicalArmorBonus(): number {
return this.armor_reduction!;
}
/****************************************/
GetEffectName(): string {
return this.effect_name;
}
/****************************************/
GetEffectAttachType(): ParticleAttachment {
return ParticleAttachment.OVERHEAD_FOLLOW;
}
}
@registerModifier()
export class modifier_guy_dynamic_entry_target extends BaseModifier
{
IsHidden(): boolean {return true}
IsPurgable(): boolean {return false}
/****************************************/
CheckState(): Partial<Record<ModifierState, boolean>> {
return {
[ModifierState.PROVIDES_VISION]: true,
};
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/sai/sai_snake_entanglement.ts
|
<reponame>jaden-young/NWR
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
interface SaiInnate extends CDOTABaseAbility
{
ApplyDebuff(target: CDOTA_BaseNPC): void;
}
interface extra
{
snake_eid?: EntityIndex;
create_puddle?: boolean | number;
}
@registerAbility()
export class sai_snake_entanglement extends BaseAbility
{
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/sai/sai_snake_entanglement.vpcf", context);
PrecacheResource("particle", "particles/units/heroes/sai/sai_snake_entanglement_pit.vpcf", context);
PrecacheResource("particle", "particles/units/heroes/sai/sai_snake_entanglement_impact.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/sai/game_sounds_sai.vsndevts", context);
//PrecacheResource("soundfile", "soundevents/heroes/sai/game_sounds_vo_sai.vsndevts", context);
}
/****************************************/
GetAOERadius(): number {
return this.GetSpecialValueFor("radius");
}
/****************************************/
OnAbilityPhaseStart(): boolean {
EmitSoundOn("Hero_Sai.SnakeEntanglement.PreCast", this.GetCaster());
return true
}
/****************************************/
OnSpellStart(): void {
let position = this.GetCursorPosition();
let projectiles = this.GetSpecialValueFor("snake_projectiles");
let duration = this.GetSpecialValueFor("snake_speed") / (position - this.GetCaster().GetAbsOrigin() as Vector).Length2D();
this.InitiateLaunch(position, projectiles, duration);
this.LaunchMainSnake(position)
}
/****************************************/
InitiateLaunch(position: Vector, count: number, duration: number): void {
this.LaunchSnake(position + RandomVector(this.GetSpecialValueFor("radius") / 2) as Vector, duration, false);
count--;
if (count > 0) this.InitiateLaunch(position, count, duration);
}
/****************************************/
LaunchSnake(position: Vector, duration: number, create_puddle: boolean): void {
let caster = this.GetCaster();
let direction = (position - caster.GetAbsOrigin() as Vector).Normalized();
let speed = create_puddle ? this.GetSpecialValueFor("snake_speed") : (position - caster.GetAbsOrigin() as Vector).Length2D() * duration;
let spawn_pos = caster.GetAttachmentOrigin(caster.ScriptLookupAttachment("attach_scroll_center")) + direction * 75 + caster.GetRightVector() * 40 as Vector;
let snake = CreateUnitByName("npc_dota_sai_snake", spawn_pos, false, undefined, undefined, caster.GetTeamNumber());
snake.AddNewModifier(caster, this, "modifier_sai_snake_entanglement_snake", {duration: -1});
snake.SetForwardVector((position - caster.GetAbsOrigin() as Vector).Normalized() as Vector);
snake.StartGesture(GameActivity.DOTA_AMBUSH);
EmitSoundOn("Hero_Sai.SnakeEntanglement.Cast", snake);
ProjectileManager.CreateLinearProjectile({
Ability: this,
EffectName: "",
vSpawnOrigin: spawn_pos,
fDistance: (spawn_pos - position as Vector).Length2D(),
Source: caster,
vVelocity: direction * speed as Vector,
ExtraData: {
snake_eid: snake.entindex(),
create_puddle: create_puddle
}
});
}
/****************************************/
LaunchMainSnake(position: Vector) {
let caster = this.GetCaster();
let direction = (position - caster.GetAbsOrigin() as Vector).Normalized();
let speed = this.GetSpecialValueFor("snake_speed");
let spawn_pos = caster.GetAttachmentOrigin(caster.ScriptLookupAttachment("attach_scroll_center")) + direction * 75 + caster.GetRightVector() * 40 as Vector;
ProjectileManager.CreateLinearProjectile({
Ability: this,
EffectName: "",
vSpawnOrigin: spawn_pos,
fDistance: (spawn_pos - position as Vector).Length2D(),
Source: caster,
vVelocity: direction * speed as Vector,
ExtraData: {
create_puddle: true
}
});
}
/****************************************/
OnProjectileThink_ExtraData(location: Vector, extraData: extra): void {
if (!extraData.snake_eid) return;
let snake = EntIndexToHScript(extraData.snake_eid!) as CDOTA_BaseNPC;
snake?.SetAbsOrigin(GetGroundPosition(location, snake) + Vector(0, 0, 75) as Vector);
}
/****************************************/
OnProjectileHit_ExtraData(target: CDOTA_BaseNPC | undefined, location: Vector, extraData: extra): boolean | void {
let caster = this.GetCaster();
if (extraData.snake_eid) {
let snake = EntIndexToHScript(extraData.snake_eid!);
if (snake) UTIL_Remove(snake);
}
if (extraData.create_puddle == 1) {
CreateModifierThinker(caster, this, "modifier_sai_snake_entanglement", {duration: this.GetSpecialValueFor("duration")}, location, caster.GetTeamNumber(), false);
EmitSoundOnLocationWithCaster(location, "Hero_Sai.SnakeEntanglement.Impact", caster);
let impact_fx = ParticleManager.CreateParticle("particles/units/heroes/sai/sai_snake_entanglement_impact.vpcf", ParticleAttachment.CUSTOMORIGIN, undefined)
ParticleManager.SetParticleControl(impact_fx, 1, GetGroundPosition(location, undefined));
ParticleManager.ReleaseParticleIndex(impact_fx)
}
}
}
@registerModifier()
export class modifier_sai_snake_entanglement extends BaseModifier
{
radius: number = 0;
debuff_duration?: number;
/****************************************/
OnCreated(params: object): void {
if (!IsServer()) return;
let ability = this.GetAbility();
let parent = this.GetParent();
let pos = GetGroundPosition(parent.GetAbsOrigin(), undefined);
pos.z = pos.z + 150;
this.radius = ability!.GetSpecialValueFor("radius");
this.debuff_duration = ability!.GetSpecialValueFor("debuff_duration");
let pit_fx = ParticleManager.CreateParticle("particles/units/heroes/sai/sai_snake_entanglement_pit.vpcf", ParticleAttachment.ABSORIGIN, parent);
ParticleManager.SetParticleControl(pit_fx, 0, pos);
ParticleManager.SetParticleControl(pit_fx, 1, Vector(this.radius, this.radius/40, 1));
ParticleManager.SetParticleControl(pit_fx, 2, Vector(this.GetRemainingTime(), 0, 0));
this.AddParticle(pit_fx, false, false, -1, false, false);
let area_fx = ParticleManager.CreateParticle("particles/units/heroes/sai/sai_snake_entanglement.vpcf", ParticleAttachment.ABSORIGIN, parent)
ParticleManager.SetParticleControl(area_fx, 1, Vector(this.radius, 0, 0))
this.AddParticle(area_fx, false, false, -1, false, false)
this.StartIntervalThink(ability!.GetSpecialValueFor("slow_growth_interval"));
this.OnIntervalThink();
}
OnIntervalThink(): void {
let parent = this.GetParent();
let enemies = FindUnitsInRadius(parent.GetTeamNumber(),
parent.GetAbsOrigin(),
undefined, this.radius,
UnitTargetTeam.ENEMY,
UnitTargetType.BASIC + UnitTargetType.HERO,
UnitTargetFlags.NONE,
FindOrder.ANY,
false
);
enemies.forEach(enemy => {
enemy.AddNewModifier(this.GetCaster(), this.GetAbility(), "modifier_sai_snake_entanglement_slow", {duration: this.debuff_duration});
});
}
}
@registerModifier()
export class modifier_sai_snake_entanglement_slow extends BaseModifier
{
turn_slow?: number;
move_slow_per_sec?: number;
max_move_slow?: number;
current_move_slow?: number;
damage?: number;
damage_table?: ApplyDamageOptions;
/****************************************/
OnCreated(params: object): void {
let ability = this.GetAbility();
let interval = ability!.GetSpecialValueFor("slow_growth_interval");
this.turn_slow = -ability!.GetSpecialValueFor("turn_slow");
this.move_slow_per_sec = -ability!.GetSpecialValueFor("move_slow_per_sec") * interval;
this.max_move_slow = -ability!.GetSpecialValueFor("max_move_slow");
this.damage = (ability!.GetSpecialValueFor("damage_per_sec") + this.GetCaster()!.FindTalentValue("special_bonus_sai_2")) * interval;
this.current_move_slow = this.move_slow_per_sec;
if (!IsServer()) return;
this.damage_table = {
attacker: this.GetCaster()!,
victim: this.GetParent(),
damage: this.damage,
damage_type: DamageTypes.MAGICAL,
ability: ability
}
let innate = this.GetCaster()!.FindAbilityByName("sai_innate_passive") as SaiInnate;
if (innate) innate.ApplyDebuff(this.GetParent());
if (this.damage > 0) {
this.StartIntervalThink(interval);
this.OnIntervalThink();
}
}
OnIntervalThink(): void {
ApplyDamage(this.damage_table!);
}
/****************************************/
OnRefresh(params: object): void {
this.current_move_slow = math.max(this.current_move_slow! + this.move_slow_per_sec!, this.max_move_slow!);
if (!IsServer()) return;
let innate = this.GetCaster()!.FindAbilityByName("sai_innate_passive") as SaiInnate;
if (innate) innate.ApplyDebuff(this.GetParent());
}
/****************************************/
DeclareFunctions(){ return [
ModifierFunction.MOVESPEED_BONUS_PERCENTAGE,
ModifierFunction.TURN_RATE_PERCENTAGE
]}
/****************************************/
GetModifierMoveSpeedBonus_Percentage(): number {
return this.current_move_slow!;
}
/****************************************/
GetModifierTurnRate_Percentage(): number {
return this.turn_slow!;
}
/****************************************/
GetEffectName(): string {
return "particles/units/heroes/sai/sai_snake_entanglement_debuff.vpcf"
}
/****************************************/
GetEffectAttachType(): ParticleAttachment {
return ParticleAttachment.ABSORIGIN_FOLLOW
}
}
@registerModifier()
export class modifier_sai_snake_entanglement_snake extends BaseModifier
{
CheckState(): Partial<Record<ModifierState, boolean>> {
return {
[ModifierState.NO_HEALTH_BAR]: true,
[ModifierState.DISARMED]: true,
[ModifierState.NOT_ON_MINIMAP]: true,
[ModifierState.OUT_OF_GAME]: true,
[ModifierState.INVULNERABLE]: true,
};
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/sai/sai_super_beast_drawing.ts
|
import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter"
interface SaiInnate extends CDOTABaseAbility
{
ApplyDebuff(target: CDOTA_BaseNPC): void;
}
interface extra
{
id?: number;
beast_eid?: EntityIndex;
}
@registerAbility()
export class sai_super_beast_drawing extends BaseAbility
{
drawing_projectiles: any = {};
/****************************************/
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/sai/sai_super_beast_drawing_proj.vpcf", context);
PrecacheResource("particle", "particles/units/heroes/sai/sai_disarm.vpcf", context)
PrecacheResource("soundfile", "soundevents/heroes/sai/game_sounds_sai.vsndevts", context);
PrecacheResource("soundfile", "soundevents/heroes/sai/game_sounds_vo_sai.vsndevts", context);
}
/****************************************/
OnAbilityPhaseStart(): boolean {
EmitSoundOn("VO_Hero_Sai.SuperBeastDrawing.Cast", this.GetCaster());
EmitSoundOn("Hero_Sai.SuperBeastDrawing.PreCast", this.GetCaster());
return true
}
/****************************************/
OnSpellStart(): void {
let caster = this.GetCaster();
let origin = caster.GetAbsOrigin();
let position = origin + (this.GetCursorPosition() - origin as Vector).Normalized() * this.GetEffectiveCastRange(origin, caster) as Vector;
let id = GameRules.GetDOTATime(true, true);
this.drawing_projectiles[id] = {};
this.LaunchDrawing(position, id);
if (caster.HasTalent("special_bonus_sai_6")) {
this.LaunchDrawing(RotatePosition(origin, QAngle(0, -30, 0), position), id);
this.LaunchDrawing(RotatePosition(origin, QAngle(0, 30, 0), position), id);
}
}
/****************************************/
LaunchDrawing(position: Vector, id: number): void {
let caster = this.GetCaster();
let distance = this.GetEffectiveCastRange(position, caster);
let radius = this.GetSpecialValueFor("radius");
let direction = position - caster.GetAbsOrigin() as Vector;
direction.z = 0;
direction = direction.Normalized();
let spawn_pos = caster.GetAttachmentOrigin(caster.ScriptLookupAttachment("attach_hitloc")) + direction * 75 as Vector;
spawn_pos.z = GetGroundPosition(spawn_pos, undefined).z;
let beast = CreateUnitByName("npc_dota_sai_lion", spawn_pos, false, undefined, undefined, caster.GetTeamNumber());
beast.AddNewModifier(caster, this, "modifier_sai_super_beast_drawing_beast", {duration: -1});
beast.SetForwardVector(caster.GetForwardVector());
beast.FaceTowards(position);
beast.StartGesture(GameActivity.DOTA_RUN);
EmitSoundOn("Hero_Sai.SuperBeastDrawing.Cast", beast);
EmitSoundOn("Hero_Sai.SuperBeastDrawing.Roar", beast);
ProjectileManager.CreateLinearProjectile({
Ability: this,
EffectName: "particles/units/heroes/sai/sai_super_beast_drawing_proj.vpcf",
vSpawnOrigin: spawn_pos,
fDistance: distance,
fStartRadius: radius,
fEndRadius: radius,
Source: caster,
iUnitTargetTeam: this.GetAbilityTargetTeam(),
iUnitTargetType: this.GetAbilityTargetType(),
iUnitTargetFlags: this.GetAbilityTargetFlags(),
vVelocity: direction * this.GetSpecialValueFor("speed") as Vector,
ExtraData: {
id: id,
beast_eid: beast.entindex()
}
});
}
OnProjectileThink_ExtraData(location: Vector, extraData: extra): void {
let beast = EntIndexToHScript(extraData.beast_eid!) as CDOTA_BaseNPC;
beast?.SetAbsOrigin(GetGroundPosition(location, beast));
}
/****************************************/
OnProjectileHit_ExtraData(target: CDOTA_BaseNPC | undefined, location: Vector, extraData: extra): boolean | void {
if (!target) {
this.KillBeast(extraData.beast_eid!);
return true;
}
if (this.drawing_projectiles[extraData.id as number][target.entindex()]) return false;
let caster = this.GetCaster();
let duration = this.GetSpecialValueFor("root_duration");
let innate = caster.FindAbilityByName("sai_innate_passive") as SaiInnate;
this.KillBeast(extraData.beast_eid!);
if (innate) innate.ApplyDebuff(target);
ApplyDamage({
attacker: caster,
victim: target,
damage: this.GetSpecialValueFor("damage"),
damage_type: this.GetAbilityDamageType(),
ability: this
})
target.AddNewModifier(caster, this, "modifier_sai_super_beast_drawing", {duration: duration * (1 - target.GetStatusResistance())});
this.drawing_projectiles[extraData.id as number][target.entindex()] = true;
EmitSoundOnLocationWithCaster(location, "Hero_Sai.SuperBeastDrawing.Impact", caster);
if ((target.GetAbsOrigin() - caster.GetAbsOrigin() as Vector).Length2D() >= this.GetSpecialValueFor("point_blank_radius")) {
let impact_fx = ParticleManager.CreateParticle("particles/units/heroes/sai/sai_super_beast_drawing_projh.vpcf", ParticleAttachment.ABSORIGIN, target);
ParticleManager.SetParticleControl(impact_fx, 3, target.GetAbsOrigin());
ParticleManager.ReleaseParticleIndex(impact_fx);
}
return true;
}
/****************************************/
KillBeast(id: EntityIndex) {
let beast = EntIndexToHScript(id);
if (beast)
UTIL_Remove(beast)
}
}
@registerModifier()
export class modifier_sai_super_beast_drawing extends BaseModifier
{
IsPurgable(): boolean {return true}
/****************************************/
CheckState(): Partial<Record<ModifierState, boolean>> {
return {
[ModifierState.ROOTED]: true,
[ModifierState.DISARMED]: true
};
}
/****************************************/
GetEffectName(): string {
return "particles/units/heroes/sai/sai_disarm.vpcf";
}
/****************************************/
GetEffectAttachType(): ParticleAttachment {
return ParticleAttachment.OVERHEAD_FOLLOW;
}
}
@registerModifier()
export class modifier_sai_super_beast_drawing_beast extends BaseModifier
{
CheckState(): Partial<Record<ModifierState, boolean>> {
return {
[ModifierState.NO_HEALTH_BAR]: true,
[ModifierState.DISARMED]: true,
[ModifierState.NOT_ON_MINIMAP]: true,
[ModifierState.OUT_OF_GAME]: true,
[ModifierState.INVULNERABLE]: true,
};
}
}
|
jaden-young/NWR
|
src/vscripts/abilities/heroes/sakura/sakura_mystical_palm_technique.ts
|
import { BaseAbility, registerAbility } from "../../../lib/dota_ts_adapter"
@registerAbility()
export class sakura_mystical_palm_technique extends BaseAbility {
Precache(context: CScriptPrecacheContext): void{
PrecacheResource("particle", "particles/units/heroes/sakura/sakura_mystical_palm_technique.vpcf", context);
PrecacheResource("soundfile", "soundevents/heroes/sakura/game_sounds_sakura.vsndevts", context);
//PrecacheResource("soundfile", "soundevents/heroes/sakura/game_sounds_vo_sakura.vsndevts", context);
}
/****************************************/
OnAbilityPhaseStart(): boolean {
EmitSoundOn("Hero_Sakura.MysticalPalm.PreCast", this.GetCaster());
EmitSoundOn("Hero_Sakura.MysticalPalm.Flick", this.GetCaster());
return true
}
/****************************************/
OnSpellStart(): void {
let caster = this.GetCaster();
let target = this.GetCursorTarget();
let base_heal = this.GetSpecialValueFor("base_heal");
let max_hp_heal = this.GetSpecialValueFor("max_hp_heal");
let total = math.floor(base_heal + target!.GetMaxHealth() * max_hp_heal / 100);
target?.HealWithParams(total, this, false, true, caster, false);
target?.Purge(false, true, false, true, true);
let heal_fx = ParticleManager.CreateParticle("particles/units/heroes/hero_oracle/oracle_purifyingflames_hit.vpcf", ParticleAttachment.ABSORIGIN_FOLLOW, target);
ParticleManager.ReleaseParticleIndex(heal_fx);
EmitSoundOn("Hero_Sakura.MysticalPalm.Heal", target!);
let heal_amount_fx = ParticleManager.CreateParticleForTeam("particles/msg_fx/msg_heal.vpcf", ParticleAttachment.ABSORIGIN_FOLLOW, target, caster.GetTeamNumber());
ParticleManager.SetParticleControl(heal_amount_fx, 1, Vector(0, total, 0))
ParticleManager.SetParticleControl(heal_amount_fx, 2, Vector(2, total.toString().length + 1, 0))
ParticleManager.SetParticleControl(heal_amount_fx, 3, Vector(0, 255, 0))
ParticleManager.ReleaseParticleIndex(heal_amount_fx)
}
}
|
aniltaskiran/tuist
|
projects/cloud/app/frontend/components/pages/organization/OrganizationPage.tsx
|
<reponame>aniltaskiran/tuist
import React, { useCallback, useState, useContext } from 'react';
import {
Page,
Card,
ResourceList,
Avatar,
TextStyle,
Stack,
ActionList,
Popover,
Button,
FormLayout,
TextField,
} from '@shopify/polaris';
import { useParams } from 'react-router';
import { Role, Organization as _ } from '@/graphql/types';
import { observer } from 'mobx-react-lite';
import { HomeStoreContext } from '@/stores/HomeStore';
import OrganizationPageStore from './OrganizationPageStore';
interface User {
id: string;
email: string;
name: string;
avatarUrl: string | undefined;
role: Role;
}
const UserRolePopover = observer(({ user }: { user: User }) => {
const { organizationStore } = useContext(HomeStoreContext);
const [isRolePopoverActive, setRolePopoverActive] = useState(false);
const toggleRolePopoverActive = useCallback(
() => setRolePopoverActive((active) => !active),
[],
);
const changeRole = useCallback(
async ({ newRole }: { newRole: Role }) => {
await organizationStore.changeUserRole(user.id, newRole);
toggleRolePopoverActive();
},
[],
);
return (
<div style={{ width: 100 }}>
<Popover
active={isRolePopoverActive}
activator={
<Button disclosure onClick={toggleRolePopoverActive}>
{user.role.charAt(0).toUpperCase() + user.role.slice(1)}
</Button>
}
onClose={toggleRolePopoverActive}
>
<ActionList
items={[
{
content: 'Admin',
onAction: () => {
changeRole({ newRole: Role.Admin });
},
},
{
content: 'User',
onAction: () => {
changeRole({ newRole: Role.User });
},
},
]}
/>
</Popover>
</div>
);
});
const UserItem = ({
user,
isAdmin,
}: {
user: User;
isAdmin: boolean;
}) => {
const { organizationStore } = useContext(HomeStoreContext);
return (
<div style={{ padding: '10px 100px 10px 20px' }}>
<Stack alignment={'center'}>
<Avatar customer size="medium" source={user.avatarUrl} />
<Stack.Item fill={true}>
<Stack vertical={true} spacing={'none'}>
<TextStyle variation="strong">{user.name}</TextStyle>
<TextStyle variation="subdued">{user.email}</TextStyle>
</Stack>
</Stack.Item>
{isAdmin ? (
<UserRolePopover user={user} />
) : (
<TextStyle>
{user.role.charAt(0).toUpperCase() + user.role.slice(1)}
</TextStyle>
)}
{isAdmin && (
<Button
destructive={true}
onClick={() => {
organizationStore.removeMember(user.id);
}}
>
Remove member
</Button>
)}
</Stack>
</div>
);
};
const OrganizationPage = observer(() => {
const { accountName: organizationName } = useParams();
const { organizationStore, userStore } =
useContext(HomeStoreContext);
const isAdmin =
(userStore.me &&
organizationStore.admins
.map((admin) => admin.id)
.includes(userStore.me.id)) ??
false;
const [organizationPageStore] = useState(
() => new OrganizationPageStore(organizationStore),
);
return (
<Page
primaryAction={
<Popover
active={organizationPageStore.isInvitePopoverActive}
activator={
<Button
primary
onClick={() => {
organizationPageStore.inviteMemberButtonClicked();
}}
>
Invite member
</Button>
}
onClose={() => {
organizationPageStore.invitePopoverClosed();
}}
sectioned
>
<FormLayout>
<TextField
label="Invitee email"
value={organizationPageStore.inviteeEmail}
onChange={(newValue) => {
organizationPageStore.inviteeEmail = newValue;
}}
/>
<Button
primary
onClick={() => {
organizationStore.inviteMember(
organizationPageStore.inviteeEmail,
);
organizationPageStore.invitePopoverClosed();
}}
>
Invite member
</Button>
</FormLayout>
</Popover>
}
title={organizationName}
>
<Card title="Members">
<ResourceList
resourceName={{ singular: 'member', plural: 'members' }}
items={organizationStore.members}
renderItem={(item) => {
return <UserItem user={item} isAdmin={isAdmin} />;
}}
/>
</Card>
{organizationPageStore.isPendingInvitationsVisible && (
<Card title="Pending invitations">
<ResourceList
resourceName={{
singular: 'pending invitation',
plural: 'pending invitations',
}}
items={
organizationStore.organization?.pendingInvitations ?? []
}
renderItem={({ inviteeEmail, id }) => {
return (
<div style={{ padding: '10px 100px 10px 20px' }}>
<Stack alignment={'center'}>
<Avatar customer size="medium" />
<Stack.Item fill={true}>
<TextStyle variation="strong">
{inviteeEmail}
</TextStyle>
</Stack.Item>
{isAdmin && (
<Stack>
<Button
onClick={() => {
organizationStore.resendInvite(id);
}}
>
Resend invite
</Button>
<Button
destructive
onClick={() => {
organizationStore.cancelInvite(id);
}}
>
Cancel invite
</Button>
</Stack>
)}
</Stack>
</div>
);
}}
/>
</Card>
)}
</Page>
);
});
export default OrganizationPage;
|
aniltaskiran/tuist
|
projects/cloud/app/frontend/models/Project.ts
|
import { ProjectDetailFragment } from '@/graphql/types';
import { Account, mapS3Bucket, S3Bucket } from '.';
export interface Project {
id: string;
account: Account;
remoteCacheStorage: S3Bucket | null;
token: string;
}
export const mapProject = ({
id,
account,
remoteCacheStorage,
token,
}: ProjectDetailFragment) => {
let mappedRemoteCacheStorage: S3Bucket | undefined | null;
if (
remoteCacheStorage === null ||
remoteCacheStorage === undefined
) {
mappedRemoteCacheStorage = remoteCacheStorage;
} else {
mappedRemoteCacheStorage = mapS3Bucket(remoteCacheStorage);
}
return {
id,
account: {
id: account.id,
owner: {
type:
account.owner.__typename === 'Organization'
? 'organization'
: 'user',
id: account.owner.id,
},
name: account.name,
},
remoteCacheStorage: mappedRemoteCacheStorage,
token,
} as Project;
};
|
aniltaskiran/tuist
|
projects/cloud/app/frontend/components/App.tsx
|
<filename>projects/cloud/app/frontend/components/App.tsx
import React from 'react';
import GraphqlProvider from '@/networking/GraphqlProvider';
import ErrorBoundary from '@/components/boundaries/ErrorBoundary';
import '@shopify/polaris/dist/styles.css';
import {
Routes,
Route,
useLocation,
BrowserRouter,
Link as ReactRouterLink,
useNavigate,
} from 'react-router-dom';
import NoPageFound from './NoPageFound';
import NewProject from './NewProject';
import Dashboard from './Dashboard';
import Home from './Home';
import { useMeQuery } from '@/graphql/types';
import RemoteCachePage from './pages/remote-cache/RemoteCachePage';
import OrganizationPage from './pages/organization/OrganizationPage';
import TuistCloudAppProvider from './TuistCloudAppProvider';
import AcceptInvitationPage from './pages/invitations/AcceptInvitationPage';
const AppRoutes = () => {
const location = useLocation();
const navigate = useNavigate();
const { data, loading, error } = useMeQuery();
if (loading) {
return <div>loading</div>;
} else if (error) {
return <div>{JSON.stringify(error)}</div>;
} else {
if (location.pathname == '/') {
const lastVisitedProject = data?.me.lastVisitedProject;
const projects = data?.me.projects ?? [];
const navigateToProjectPath =
lastVisitedProject?.slug ?? projects[0]?.slug;
if (navigateToProjectPath) {
navigate(`/${navigateToProjectPath}`);
} else {
navigate('/new');
}
}
return (
<Routes>
<Route
path="/invitations/:token"
element={<AcceptInvitationPage />}
/>
<Route path="/:accountName/:projectName" element={<Home />}>
{/* TODO: Return dashboard here once we have what to display there */}
<Route path="" element={<RemoteCachePage />} />
<Route path="remote-cache" element={<RemoteCachePage />} />
<Route path="organization" element={<OrganizationPage />} />
</Route>
<Route path="/new" element={<NewProject />} />
<Route element={<NoPageFound />} />
</Routes>
);
}
};
const App = (): JSX.Element => {
return (
<ErrorBoundary>
<GraphqlProvider>
<div style={{ height: '500px' }}>
<TuistCloudAppProvider>
<BrowserRouter>
<AppRoutes />
</BrowserRouter>
</TuistCloudAppProvider>
</div>
</GraphqlProvider>
</ErrorBoundary>
);
};
export default App;
|
aniltaskiran/tuist
|
projects/cloud/app/frontend/stores/ProjectStore.ts
|
<gh_stars>0
import { ProjectQuery, ProjectDocument } from '@/graphql/types';
import { ApolloClient } from '@apollo/client';
import { makeAutoObservable, runInAction } from 'mobx';
import { mapProject, Project } from '@/models/Project';
export default class ProjectStore {
project: Project;
client: ApolloClient<object>;
constructor(client: ApolloClient<object>) {
this.client = client;
makeAutoObservable(this);
}
async load(name: string, accountName: string) {
const { data } = await this.client.query<ProjectQuery>({
query: ProjectDocument,
variables: {
name,
accountName,
},
});
runInAction(() => {
if (data == null || data.project == null) {
return;
}
this.project = mapProject(data.project);
});
}
}
|
aniltaskiran/tuist
|
projects/cloud/app/frontend/components/pages/remote-cache/RemoteCachePage.tsx
|
<gh_stars>0
import React, {
useCallback,
useContext,
useEffect,
useState,
} from 'react';
import {
Page,
FormLayout,
TextField,
Card,
Button,
Select,
Stack,
} from '@shopify/polaris';
import RemoteCachePageStore from './RemoteCachePageStore';
import { observer } from 'mobx-react-lite';
import { useApolloClient } from '@apollo/client';
import { HomeStoreContext } from '@/stores/HomeStore';
import { runInAction } from 'mobx';
const RemoteCachePage = observer(() => {
const client = useApolloClient();
const { projectStore } = useContext(HomeStoreContext);
const [remoteCachePageStore] = useState(
() => new RemoteCachePageStore(client, projectStore),
);
useEffect(() => {
remoteCachePageStore.load();
}, [projectStore.project]);
const handleSelectChange = useCallback(
(newValue) => {
remoteCachePageStore.handleSelectOption(newValue);
},
[remoteCachePageStore],
);
const handleBucketNameChange = useCallback(
(newValue) => {
runInAction(() => {
remoteCachePageStore.bucketName = newValue;
});
},
[remoteCachePageStore],
);
const handleRegionChange = useCallback(
(newValue) => {
runInAction(() => {
remoteCachePageStore.region = newValue;
});
},
[remoteCachePageStore],
);
const handleAccessKeyIdChange = useCallback(
(newValue) => {
runInAction(() => {
remoteCachePageStore.accessKeyId = newValue;
});
},
[remoteCachePageStore],
);
const handleSecretAccessKeyChange = useCallback(
(newValue) => {
runInAction(() => {
remoteCachePageStore.secretAccessKey = newValue;
});
},
[remoteCachePageStore],
);
const handleRemoveSecretAccessKey = useCallback(() => {
remoteCachePageStore.removeAccessKey();
}, [remoteCachePageStore]);
const handleApplyChangesClicked = useCallback(() => {
if (projectStore.project == undefined) {
return;
}
remoteCachePageStore.applyChangesButtonClicked(
projectStore.project.account.id,
);
}, [remoteCachePageStore, projectStore]);
return (
<Page title="Remote Cache">
<Card title="S3 Bucket setup" sectioned>
<FormLayout>
<Select
label="S3 Bucket"
options={remoteCachePageStore.bucketOptions}
onChange={handleSelectChange}
value={remoteCachePageStore.selectedOption}
/>
<TextField
type="text"
label="Bucket name"
value={remoteCachePageStore.bucketName}
onChange={handleBucketNameChange}
/>
<TextField
type="text"
label="Region"
value={remoteCachePageStore.region}
onChange={handleRegionChange}
/>
<TextField
type="text"
label="Access key ID"
value={remoteCachePageStore.accessKeyId}
onChange={handleAccessKeyIdChange}
/>
<Stack alignment="trailing" distribution="fill">
<TextField
disabled={
remoteCachePageStore.isSecretAccessKeyTextFieldDisabled
}
type="password"
label="Secret access key"
value={remoteCachePageStore.secretAccessKey}
onChange={handleSecretAccessKeyChange}
/>
{remoteCachePageStore.isCreatingBucket === false && (
<Button onClick={handleRemoveSecretAccessKey}>
Remove access key
</Button>
)}
</Stack>
<Button
primary
loading={remoteCachePageStore.isApplyChangesButtonLoading}
disabled={
remoteCachePageStore.isApplyChangesButtonDisabled
}
onClick={handleApplyChangesClicked}
>
{remoteCachePageStore.isCreatingBucket
? 'Create bucket'
: 'Edit bucket'}
</Button>
</FormLayout>
</Card>
<Card title="CI cloud token" sectioned>
<Button
loading={remoteCachePageStore.isCopyProjectButtonLoading}
onClick={() => {
remoteCachePageStore.copyProjectToken();
}}
>
Copy CI cloud token
</Button>
</Card>
</Page>
);
});
export default RemoteCachePage;
|
aniltaskiran/tuist
|
projects/cloud/app/frontend/components/pages/remote-cache/__tests__/RemoteCachePageStore.test.ts
|
import ProjectStore from '@/stores/ProjectStore';
import RemoteCachePageStore from '../RemoteCachePageStore';
import { S3Bucket } from '@/models';
import { S3BucketInfoFragment } from '@/graphql/types';
import { copyToClipboard } from '@/utilities/copyToClipboard';
jest.mock('@apollo/client');
jest.mock('@/stores/ProjectStore');
jest.mock('@/utilities/copyToClipboard');
describe('RemoteCachePageStore', () => {
const client = {
query: jest.fn(),
mutate: jest.fn(),
} as any;
const projectStore = {} as ProjectStore;
beforeEach(() => {
jest.clearAllMocks();
projectStore.project = {
id: 'project',
account: {
id: 'account-id',
name: 'acount-name',
owner: {
id: 'owner',
type: 'organization',
},
},
remoteCacheStorage: null,
token: '',
};
});
it('keeps apply changes button disabled when not all fields are filled', () => {
// Given
const remoteCachePageStore = new RemoteCachePageStore(
client,
projectStore,
);
// When
remoteCachePageStore.bucketName = '1';
remoteCachePageStore.accessKeyId = '1';
// Then
expect(
remoteCachePageStore.isApplyChangesButtonDisabled,
).toBeTruthy();
});
it('marks apply changes button enabled when all fields are filled', () => {
// Given
const remoteCachePageStore = new RemoteCachePageStore(
client,
projectStore,
);
// When
remoteCachePageStore.bucketName = '1';
remoteCachePageStore.accessKeyId = '1';
remoteCachePageStore.secretAccessKey = '1';
remoteCachePageStore.region = '1';
// Then
expect(
remoteCachePageStore.isApplyChangesButtonDisabled,
).toBeFalsy();
});
it('returns new as selected option when remoteCacheStorage is null', () => {
// Given
projectStore.project = {
id: 'project',
account: {
id: 'account-id',
name: 'acount-name',
owner: {
id: 'owner',
type: 'organization',
},
},
remoteCacheStorage: null,
token: '',
};
// When
const remoteCachePageStore = new RemoteCachePageStore(
client,
projectStore,
);
// Then
expect(remoteCachePageStore.selectedOption).toEqual('new');
expect(remoteCachePageStore.isCreatingBucket).toBeTruthy();
});
it('returns remote cache storage name if it is set in the project', () => {
// Given
projectStore.project.remoteCacheStorage = {
accessKeyId: 'accessKeyId',
id: 'id',
name: 'bucket',
secretAccessKey: 'secret',
region: 'region',
};
// When
const remoteCachePageStore = new RemoteCachePageStore(
client,
projectStore,
);
// Then
expect(remoteCachePageStore.selectedOption).toEqual('bucket');
});
it('copy pastes project token of the remote cache', () => {
// Given
projectStore.project = {
id: 'project',
account: {
id: 'account-id',
name: 'acount-name',
owner: {
id: 'owner',
type: 'organization',
},
},
remoteCacheStorage: null,
token: 'token',
};
const remoteCachePageStore = new RemoteCachePageStore(
client,
projectStore,
);
// When
remoteCachePageStore.copyProjectToken();
// Then
expect(copyToClipboard as jest.Mock).toHaveBeenCalledWith(
'token',
);
expect(remoteCachePageStore.isCopyProjectButtonLoading).toBe(
true,
);
jest.advanceTimersByTime(1000);
expect(remoteCachePageStore.isCopyProjectButtonLoading).toBe(
false,
);
});
it('loads remote cache page', async () => {
// Given
projectStore.project.remoteCacheStorage = {
accessKeyId: 'key-id-1',
id: 'id-1',
name: 'S3 bucket one',
secretAccessKey: 'secret',
region: 'region',
};
const remoteCachePageStore = new RemoteCachePageStore(
client,
projectStore,
);
client.query.mockResolvedValueOnce({
data: {
s3Buckets: [
{
accessKeyId: 'key-id-1',
accountId: 'account-id-1',
id: 'id-1',
name: 'S3 bucket one',
region: 'region',
__typename: 'S3Bucket',
},
{
accessKeyId: 'key-id-2',
accountId: 'account-id-2',
id: 'id-2',
name: 'S3 bucket two',
region: 'region',
__typename: 'S3Bucket',
},
] as S3BucketInfoFragment[],
},
});
// When
await remoteCachePageStore.load();
// Then
expect(remoteCachePageStore.bucketName).toEqual('S3 bucket one');
expect(remoteCachePageStore.accessKeyId).toEqual('key-id-1');
expect(remoteCachePageStore.secretAccessKey).toEqual('secret');
expect(remoteCachePageStore.s3Buckets).toEqual([
{
accessKeyId: 'key-id-1',
secretAccessKey: undefined,
id: 'id-1',
name: 'S3 bucket one',
region: 'region',
},
{
accessKeyId: 'key-id-2',
secretAccessKey: undefined,
id: 'id-2',
name: 'S3 bucket two',
region: 'region',
},
]);
expect(remoteCachePageStore.bucketOptions).toEqual([
{
label: 'Create new bucket',
value: 'new',
},
{
label: 'S3 bucket one',
value: 'S3 bucket one',
},
{
label: 'S3 bucket two',
value: 'S3 bucket two',
},
]);
});
it('creates a new bucket', async () => {
// Given
const remoteCachePageStore = new RemoteCachePageStore(
client,
projectStore,
);
remoteCachePageStore.bucketName = 'S3 bucket';
remoteCachePageStore.secretAccessKey = 'secret';
remoteCachePageStore.accessKeyId = 'access-key-id';
remoteCachePageStore.region = 'region';
client.mutate.mockReturnValueOnce({
data: {
createS3Bucket: {
accessKeyId: 'access-key-id',
accountId: 'account-id',
id: 'id-1',
name: 'S3 bucket',
secretAccessKey: 'secret',
region: 'region',
__typename: 'S3Bucket',
},
},
});
const expectedS3Bucket: S3Bucket = {
accessKeyId: 'access-key-id',
id: 'id-1',
name: 'S3 bucket',
secretAccessKey: 'secret',
region: 'region',
};
// When
await remoteCachePageStore.applyChangesButtonClicked(
'account-id',
);
// Then
expect(
remoteCachePageStore.projectStore.project.remoteCacheStorage,
).toEqual(expectedS3Bucket);
expect(remoteCachePageStore.s3Buckets).toEqual([
expectedS3Bucket,
]);
});
it('updates the current bucket', async () => {
// Given
projectStore.project.remoteCacheStorage = {
accessKeyId: 'key-id-1',
id: 'id-1',
name: 'S3 bucket',
secretAccessKey: 'secret',
region: 'region',
};
const remoteCachePageStore = new RemoteCachePageStore(
client,
projectStore,
);
const expectedS3Bucket: S3Bucket = {
accessKeyId: 'changed access key id',
id: 'id-1',
name: 'new name',
secretAccessKey: 'new secret',
region: 'region',
};
client.mutate.mockReturnValueOnce({
data: {
updateS3Bucket: {
accessKeyId: expectedS3Bucket.accessKeyId,
accountId: 'account-id',
id: expectedS3Bucket.id,
name: expectedS3Bucket.name,
secretAccessKey: expectedS3Bucket.secretAccessKey,
region: expectedS3Bucket.region,
__typename: 'S3Bucket',
},
},
});
client.query.mockResolvedValueOnce({
data: {
s3Buckets: [
{
accessKeyId: 'key-id-1',
accountId: 'account-id',
id: 'id-1',
name: 'S3 bucket',
secretAccessKey: 'secret',
region: 'region',
__typename: 'S3Bucket',
},
] as S3BucketInfoFragment[],
},
});
await remoteCachePageStore.load();
// When
await remoteCachePageStore.applyChangesButtonClicked(
'account-id',
);
// Then
expect(
remoteCachePageStore.projectStore.project.remoteCacheStorage,
).toEqual(expectedS3Bucket);
expect(remoteCachePageStore.s3Buckets).toEqual([
expectedS3Bucket,
]);
expect(remoteCachePageStore.selectedOption).toEqual(
expectedS3Bucket.name,
);
});
});
|
kenryooo/basic-auth-lambda-edge
|
src/index.ts
|
<reponame>kenryooo/basic-auth-lambda-edge<gh_stars>0
declare const Buffer: any
declare const console: any
import * as ip from 'ip'
import { Callback, CloudFrontRequestEvent, Context } from 'aws-lambda'
export const handler = (event: CloudFrontRequestEvent, context: Context, callback: Callback) => {
const request = event.Records[0].cf.request
const errorContent = '\
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\
<html><head>\
<title>401 Authorization Required</title>\
</head><body>\
<h1>Authorization Required</h1>\
<p>This server could not verify that you are authorized to access the document\
requested. Either you supplied the wrong credentials (e.g., bad password), or your\
browser doesn\'t understand how to supply the credentials required.</p>\
</body></html>\
';
const allowCidrSubnets = [
'cidr1',
'cidr2'
];
allowCidrSubnets.forEach(subnet => {
if (ip.cidrSubnet(subnet).contains(request.clientIp)) {
console.log('subnet: ' + subnet + ', request.clientIp: ' + request.clientIp)
callback(null, request);
}
})
const credentials = [
{
'user':'hoge',
'password':'<PASSWORD>'
}
]
var authorities = request.headers.Authorization || request.headers.authorization;
if (authorities) {
let authorized = false;
credentials.forEach(credential => {
const secret = new Buffer(credential.user + ':' + credential.password).toString('base64');
for (let i = 0; i < authorities.length; i++) {
if (authorities[i].value.split(" ")[1] === secret) {
authorized = true;
}
}
})
if (authorized) {
console.log("match: " + authorities);
callback(null, request);
}
else {
console.log("not match: " + authorities);
callback(null, {
status: '403',
statusDescription: '403 Forbidden',
headers: {
'content-type': [{ key: 'Content-Type', value: 'text/html; charset=UTF-8' }]
},
body: errorContent.toString()
});
}
}
else {
callback(null, {
status: '401',
statusDescription: '401 Unauthorized',
headers: {
'www-authenticate': [{ key: 'WWW-Authenticate', value: 'Basic' }]
}
});
}
};
|
jarry-xiao/mux_wallet
|
tests/mux.ts
|
import * as anchor from "@project-serum/anchor";
import { Program, BN } from "@project-serum/anchor";
import { Mux } from "../target/types/mux";
import { PublicKey, Keypair, SystemProgram } from "@solana/web3.js";
import { assert } from "chai";
const SOL1 = 1000000000;
const logTx = async (provider, tx) => {
console.log(
(await provider.connection.getConfirmedTransaction(tx, "confirmed")).meta
.logMessages
);
};
const getRandomAmount = (min, range) => {
return min + Math.floor(Math.random() * range);
};
const donate = async (program, benefactor, fundWalletKey, amount) => {
await program.provider.send(
new anchor.web3.Transaction().add(
anchor.web3.SystemProgram.transfer({
fromPubkey: benefactor.publicKey,
toPubkey: fundWalletKey,
lamports: amount,
})
),
[benefactor],
{ commitment: "confirmed" }
);
};
const createFund = async (program, creator, verbose = false) => {
let [walletStateKey, _walletStateBump] = await PublicKey.findProgramAddress(
[creator.publicKey.toBuffer()],
program.programId
);
let [fundWalletKey, _fundWalletBump] = await PublicKey.findProgramAddress(
[walletStateKey.toBuffer()],
program.programId
);
let [creatorStateKey, _creatorStateBump] = await PublicKey.findProgramAddress(
[walletStateKey.toBuffer(), creator.publicKey.toBuffer()],
program.programId
);
const tx = await program.rpc.createFund(new BN(10000), {
accounts: {
walletState: walletStateKey,
fundWallet: fundWalletKey,
creator: creator.publicKey,
creatorState: creatorStateKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
signers: [creator],
});
await program.provider.connection.confirmTransaction(tx, "confirmed");
if (verbose) await logTx(program.provider, tx);
return [walletStateKey, fundWalletKey, creatorStateKey];
};
const createAndTransferStake = async (
program,
walletStateKey,
fundWalletKey,
recipient,
sender,
senderStateKey,
numShares,
verbose = false
) => {
let [recipientStateKey, _recipientStateBump] =
await PublicKey.findProgramAddress(
[walletStateKey.toBuffer(), recipient.publicKey.toBuffer()],
program.programId
);
let createStakeAccountTx = await program.transaction.createStakeAccount({
accounts: {
walletState: walletStateKey,
payer: sender.publicKey,
user: recipient.publicKey,
userState: recipientStateKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
signers: [sender],
});
let transferTx = await program.transaction.transferShares(new BN(numShares), {
accounts: {
walletState: walletStateKey,
fundWallet: fundWalletKey,
sender: sender.publicKey,
senderState: senderStateKey,
recipientState: recipientStateKey,
recipient: recipient.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
signers: [sender],
});
const tx = await program.provider.send(
new anchor.web3.Transaction().add(createStakeAccountTx).add(transferTx),
[sender]
);
await program.provider.connection.confirmTransaction(tx, "confirmed");
if (verbose) await logTx(program.provider, tx);
};
const transferStake = async (
program,
walletStateKey,
fundWalletKey,
recipient,
sender,
senderStateKey,
numShares,
verbose = false
) => {
let [recipientStateKey, _recipientStateBump] =
await PublicKey.findProgramAddress(
[walletStateKey.toBuffer(), recipient.publicKey.toBuffer()],
program.programId
);
const tx = await program.rpc.transferShares(new BN(numShares), {
accounts: {
walletState: walletStateKey,
fundWallet: fundWalletKey,
sender: sender.publicKey,
senderState: senderStateKey,
recipientState: recipientStateKey,
recipient: recipient.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
signers: [sender],
});
await program.provider.connection.confirmTransaction(tx, "confirmed");
if (verbose) await logTx(program.provider, tx);
};
const claim = async (
program,
walletStateKey,
fundWalletKey,
recipient,
verbose = false
) => {
let [recipientStateKey, _recipientStateBump] =
await PublicKey.findProgramAddress(
[walletStateKey.toBuffer(), recipient.publicKey.toBuffer()],
program.programId
);
const tx = await program.rpc.claim({
accounts: {
walletState: walletStateKey,
fundWallet: fundWalletKey,
recipient: recipient.publicKey,
recipientState: recipientStateKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
});
await program.provider.connection.confirmTransaction(tx, "confirmed");
if (verbose) await logTx(program.provider, tx);
};
describe("mux", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.Provider.env());
const program = anchor.workspace.Mux as Program<Mux>;
const creator = Keypair.generate();
const benefactor = Keypair.generate();
let daoMembers: Keypair[] = [];
for (let i = 0; i < 50; ++i) {
daoMembers.push(Keypair.generate());
}
it("Initialize start state", async () => {
// Airdropping tokens to a payer.
await program.provider.connection.confirmTransaction(
await program.provider.connection.requestAirdrop(
benefactor.publicKey,
100000000000000
),
"confirmed"
);
await program.provider.connection.confirmTransaction(
await program.provider.connection.requestAirdrop(
creator.publicKey,
10000000000
),
"confirmed"
);
});
it("Test Fund", async () => {
let walletState;
console.log("Creating wallet");
const [walletStateKey, fundWalletKey, creatorStateKey] = await createFund(
program,
creator,
true
);
let totalSent = 0;
console.log("Seeding inital stake");
for (let i = 0; i < 10; ++i) {
let amount = getRandomAmount(SOL1, SOL1);
totalSent += amount;
await donate(program, benefactor, fundWalletKey, amount);
const recipient = daoMembers[i];
let bps = 50 * (i + 1);
console.log(`Sending ${bps} bps to ${recipient.publicKey.toBase58()}`);
await createAndTransferStake(
program,
walletStateKey,
fundWalletKey,
recipient,
creator,
creatorStateKey,
bps
);
}
walletState = await program.account.walletState.fetch(
walletStateKey,
"confirmed"
);
let dust = walletState.totalShares.toNumber() - walletState.dust.toNumber();
totalSent += dust;
await donate(program, benefactor, fundWalletKey, dust);
const epoch1Amount = totalSent;
console.log("Claim rewards for all initialized members");
let snapshots = [];
for (const [i, recipient] of daoMembers.entries()) {
if (i >= 10) {
break;
}
await claim(program, walletStateKey, fundWalletKey, recipient);
let balance = await program.provider.connection.getBalance(
recipient.publicKey,
"confirmed"
);
snapshots.push(balance);
}
await claim(program, walletStateKey, fundWalletKey, creator);
walletState = await program.account.walletState.fetch(
walletStateKey,
"confirmed"
);
assert.ok(walletState.dust.toNumber() == 0);
assert.ok(walletState.lastSnapshot.toNumber() == 0);
console.log("Added 50 bps to each Dao member");
for (const [i, recipient] of daoMembers.entries()) {
console.log(" ", i, recipient.publicKey.toBase58());
if (i < 10) {
await transferStake(
program,
walletStateKey,
fundWalletKey,
recipient,
creator,
creatorStateKey,
50
);
} else {
await createAndTransferStake(
program,
walletStateKey,
fundWalletKey,
recipient,
creator,
creatorStateKey,
50
);
}
}
let amount = getRandomAmount(SOL1, SOL1);
totalSent += amount;
await donate(program, benefactor, fundWalletKey, amount);
await claim(program, walletStateKey, fundWalletKey, creator);
walletState = await program.account.walletState.fetch(
walletStateKey,
"confirmed"
);
console.log(
"Fund balance: ",
await program.provider.connection.getBalance(fundWalletKey, "confirmed")
);
console.log("Total Sent Without Dust: ", totalSent);
console.log("Total Deposits", walletState.totalDeposits.toNumber());
console.log("Dust", walletState.dust.toNumber());
dust = walletState.totalShares.toNumber() - walletState.dust.toNumber();
console.log("Amount to send", dust);
totalSent += dust;
await donate(program, benefactor, fundWalletKey, dust);
console.log(
"Fund balance: ",
await program.provider.connection.getBalance(fundWalletKey, "confirmed")
);
console.log("Total Sent: ", totalSent);
console.log("Epoch 1: ", epoch1Amount);
console.log("Withdrawing for first 20 DAO members");
for (const [i, recipient] of daoMembers.entries()) {
if (i >= 20) {
break;
}
await claim(program, walletStateKey, fundWalletKey, recipient);
}
console.log("Sending 1 more SOL");
totalSent += SOL1;
await donate(program, benefactor, fundWalletKey, SOL1);
console.log("Withdrawing all remaining funds");
for (const recipient of daoMembers) {
await claim(program, walletStateKey, fundWalletKey, recipient);
}
await claim(program, walletStateKey, fundWalletKey, creator);
walletState = await program.account.walletState.fetch(
walletStateKey,
"confirmed"
);
assert.ok(walletState.dust.toNumber() == 0);
assert.ok(walletState.lastSnapshot.toNumber() == 0);
console.log("Fund wallet has 0 remaining balance");
const creatorState = await program.account.stake.fetch(creatorStateKey);
console.log(
`${creator.publicKey.toBase58()} (${creatorState.numShares.toNumber()}): `,
await program.provider.connection.getBalance(creator.publicKey)
);
for (const [i, recipient] of daoMembers.entries()) {
const recipientState = await program.account.stake.fetch(
(
await PublicKey.findProgramAddress(
[walletStateKey.toBuffer(), recipient.publicKey.toBuffer()],
program.programId
)
)[0]
);
let balance = await program.provider.connection.getBalance(
recipient.publicKey,
"confirmed"
);
console.log(
`${recipient.publicKey.toBase58()} (${recipientState.numShares.toNumber()}): `,
balance
);
if (i >= 10) {
assert.ok(balance == (totalSent - epoch1Amount) / 200);
} else {
let bps = recipientState.numShares.toNumber();
assert.ok(
balance == ((totalSent - epoch1Amount) * bps) / 10000 + snapshots[i]
);
}
}
console.log("");
console.log(
"Fund balance: ",
await program.provider.connection.getBalance(fundWalletKey, "confirmed")
);
});
});
|
antirek/automation-ts-sample
|
types.ts
|
<gh_stars>1-10
module.exports = {
worker: '',
}
|
antirek/automation-ts-sample
|
objects.ts
|
<gh_stars>1-10
const { v4: uuidv4 } = require('uuid');
export interface LogStep {
id: string,
type: string,
params: {},
input: {},
output: {},
nextStepId: string,
}
export interface IStep {
id: string;
type: string;
}
export interface IStepStart extends IStep {
params: {},
next: string,
getNextStepId(): string;
process(data: any | void): void;
}
export interface IStepExecutor extends IStep {
params: {};
next: string;
process(data: any): void;
getNextStepId(): string;
}
export interface IStepSelector extends IStep {
params: {},
next: string;
process(data: any): void;
getNextStepId(): string;
}
export class StepStart implements IStepStart {
id: string;
type: string;
params: {};
next: string;
constructor({id, type, params, next}: IStepStart) {
this.id = id;
this.type = type;
this.params = params;
this.next = next;
}
getNextStepId() {
return this.next;
}
process(data: any | void) {
return {nextStepId: this.next, result: data};
}
}
export class ExecutorFactory {
static createExecutor(executorName) {
return {
exec: (params, data) => {
return {status: 'ok'}
}
}
}
}
export class SelectorFactory {
static createSelector(selectorName) {
return {
exec: (params, data) => {
const nextId = 'next';
return nextId;
}
}
}
}
export class StepExecutor implements IStepExecutor {
id: string;
type: string;
params: {};
next: string;
executor: {
exec(params: object, data:string): object
};
constructor({id, type, params, executor, next}) {
this.id = id;
this.type = type;
this.params = params;
this.next = next;
this.executor = ExecutorFactory.createExecutor(executor);
}
getNextStepId() {
return this.next;
}
process(data) {
return this.executor.exec(this.params, data);
}
}
export class StepSelector implements IStepSelector {
id: string;
type: string;
params: {};
next: string;
selector: {
exec(params: object, data:string): string
};
constructor({id, type, params, selector}) {
this.id = id;
this.type = type;
this.params = params;
this.next = null;
this.selector = SelectorFactory.createSelector(selector);
}
getNextStepId() {
return this.next;
}
process(data) {
this.next = this.selector.exec(this.params, data)
return {next: this.next, data};
}
}
export class StepFactory {
static createStep(type, data) {
switch (type){
case 'start':
return new StepStart(data);
case 'executor':
return new StepExecutor(data);
case 'selector':
return new StepSelector(data);
default:
return null;
}
}
}
export interface Connection {
id: string,
uri: string,
}
export interface Flow {
id: string,
steps: IStep[],
connections: Connection[],
}
export class FlowTask {
id: string;
flow: Flow;
currentStepId: string;
currentInput: object;
currentResult: object;
index: number;
logSteps: LogStep[];
status: string;
vars: object;
steps: {};
nextStepId: string;
constructor(flow) {
this.id = uuidv4()
this.flow = flow;
this.index = 0;
this.logSteps = [];
this.status = 'init';
this.vars = {};
this.steps = this.createStepsFromFlow(flow);
this.nextStepId = null;
}
private createStepsFromFlow (flow: Flow) {
const steps = {};
flow.steps.map(step => {
steps[step.id] = StepFactory.createStep(step.type, step);
})
return steps;
}
getStep(stepId: string) {
return this.steps[stepId];
}
getFirstStep() {
this.currentStepId = 'start';
this.status = 'start';
this.index = 1;
return this.getStep(this.currentStepId);
}
getCurrentStep() {
if(!this.currentStepId) {
return this.getFirstStep();
}
return this.getStep(this.currentStepId);
}
process(data) {
if (data) {
this.currentInput = data;
}
const currentStep = this.getCurrentStep();
this.status = 'processing';
const {nextStepId, result} = currentStep.process(this.currentInput, this.vars);
this.status = 'wait';
this.nextStepId = nextStepId;
this.currentResult = result;
this.index++;
this.log();
}
log () {
const currentStep = this.getCurrentStep();
this.addLogStep({
id: currentStep.id,
type: currentStep.type,
params: currentStep.params,
input: this.currentInput,
output: this.currentResult,
nextStepId: this.nextStepId,
})
}
moveFlowToNextStep() {
if (!this.nextStepId) {
return false;
}
this.currentStepId = this.getStep(this.nextStepId).id;
this.currentInput = this.currentResult;
this.currentResult = null;
this.nextStepId = null;
return true;
}
addLogStep(obj: LogStep) {
this.logSteps.push(obj);
}
getId() {
return this.id;
}
getStatus() {
return this.status;
}
setVar(variable: string, value: any) {
this.vars[variable] = value;
}
getVar(variable: string) {
return this.vars[variable];
}
getQueueTaskId() {
return this.id + '%' + this.index + '%' + this.currentStepId;
}
static getTaskIdFromQueueTaskId(queueTaskId) {
return queueTaskId.split('%')[0];
}
}
export class FlowTaskInventory {
flowtasks: FlowTask[];
constructor () {
this.flowtasks = [];
}
add(flowtask: FlowTask) {
this.flowtasks.push(flowtask);
}
get(id: string) {
return this.flowtasks.find(ft => ft.getId() === id);
}
remove(id: string) {
this.flowtasks;
}
}
|
antirek/automation-ts-sample
|
flow.ts
|
module.exports = [
{
id: 'test',
params: {
title: 'test',
},
connections: [
{
id: 'crm',
type: 'crm',
crm: 'custom',
params: {
url: 'http://localhost:3000/api',
auth: 'key',
key: '3285094054305',
},
},
{
id: 'email-yandex',
type: 'email',
params: {
name: '<EMAIL>',
password: '<PASSWORD>',
}
}
],
steps: [
{
id: 'start',
type: 'start',
out: 'httpRequestParams',
next: 'exec-httprequest',
},
{
id: 'exec-httprequest',
type: 'executor',
executor: 'httprequestExecutor',
params: {
validate: true,
connectionId: 'crm',
},
next: 'selector-one',
},
{
id: 'selector-one',
type: 'selector',
selector: 'successFailSelector',
params: {
list: {
'success': 'successmodificator-email1',
'fail': 'failmodificator-email2'
},
},
},
{
id: 'successmodificator-email1',
type: 'modificator',
modificator: 'successhttprequest2emailModificator',
next: 'executor-email',
},
{
id: 'failmodificator-email2',
type: 'modificator',
modificator: 'failhttprequest2email',
next: 'executor-email',
},
{
id: 'executor-email',
type: 'executor',
executor: 'email',
},
{
id: 'executor-email',
type: 'end',
executor: 'email',
},
],
},
]
|
antirek/automation-ts-sample
|
index.ts
|
const express = require('express');
const { Queue, QueueEvents, Job } = require('bullmq');
const { v4: uuidv4 } = require('uuid');
const { inspect } = require('util');
const flows = require('./flow');
const cache = require('./cache')();
const {FlowTask, FlowTaskInventory, Flow} = require('./objects');
const flowTaskInventory = new FlowTaskInventory();
const app = express();
app.use(express.json());
const port = 3000;
const getFlow = (id: string) => {
// console.log('flows', flows);
return flows.find(item => item.id === id);
}
cache.setConnections('test', getFlow('test').connections);
const queues = {
validate: new Queue('validate'),
httprequest: new Queue('httprequest'),
log: new Queue('log'),
select: new Queue('select'),
email: new Queue('email'),
}
const qe = {
validate: new QueueEvents('validate'),
httprequest: new QueueEvents('httprequest'),
log: new QueueEvents('log'),
select: new QueueEvents('select'),
email: new QueueEvents('email'),
}
const onCompleted = async (job) => {
console.log('job:', job, 'completed');
const data = job.returnvalue;
const flowTaskId = FlowTask.getTaskIdFromQueueTaskId(job.jobId);
const flowtask = flowTaskInventory.get(flowTaskId);
const nextStep = flowtask.getNextStep(data);
//console.log('flowtask', inspect(flowtask,{ showHidden: true, depth: null }));
console.log('next step', nextStep);
if(!nextStep) {
console.log('flow end, no next step in flow');
return;
}
const q = queues[nextStep.type];
flowtask.setCurrentInput(data);
const jobId = flowtask.getQueueTaskId();
console.log({jobId, data})
q.add(flowTaskId, {
params: nextStep.params,
data: job.returnvalue,
}, {
jobId
});
}
for (const key in qe) {
if (qe.hasOwnProperty(key)) {
qe[key].on('completed', onCompleted);
}
}
app.get('/', (req, res) => {
res.send('Hello World!')
});
app.post('/flow/:id', async (req, res) => {
const flowId = req.params.id;
const data = req.body;
const flow = getFlow(flowId);
if (!flow) {
console.log('no flow', flowId);
return;
}
const flowtask = new FlowTask(flow);
flowtask.setCurrentInput(data);
flowTaskInventory.add(flowtask);
const flowTaskId = flowtask.getId();
res.send(flowTaskId);
const step = flowtask.getFirstStep();
const q = queues.validate;
q.add(flowTaskId, {
params: step.params,
data
}, {jobId: flowtask.getQueueTaskId()});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
|
antirek/automation-ts-sample
|
run.ts
|
<reponame>antirek/automation-ts-sample
const {FlowTask, FlowTaskInventory, Flow} = require('./objects');
const flows = require('./flow');
const getFlow = (id: string) => {
// console.log('flows', flows);
return flows.find(item => item.id === id);
}
const flow = getFlow('test');
const flowtask = new FlowTask(flow);
///console.log(flowtask);
const firstStep = flowtask.getFirstStep();
flowtask.process({erer:'qw'});
console.log('1', flowtask);
flowtask.moveFlowToNextStep();
flowtask.process();
console.log('2', flowtask);
flowtask.moveFlowToNextStep();
flowtask.process();
console.log('3', flowtask);
//console.log(firstStep, result);
/**
const secondStep = flowtask.getNextStep();
result = secondStep.process(result);
console.log(secondStep, result);
const thirdStep = flowtask.getNextStep();
result = thirdStep.process(result);
console.log(thirdStep, result);
*/
|
antirek/automation-ts-sample
|
cache.ts
|
const redis = require('redis');
const { promisify } = require("util");
const client = redis.createClient();
module.exports = () => {
const get = promisify(client.get).bind(client);
const set = promisify(client.set).bind(client);
const setConnections = async (flowId, connections) => {
await set('connections:' + flowId, JSON.stringify(connections));
}
const getConnections = async (flowId) => {
const connections = await get('connections:' + flowId);
return JSON.parse(connections);
}
const getConnection = async (flowId, connectionId) => {
const connections = await getConnections(flowId);
return connections.find(c => c.id === connectionId);
}
return {
get,
set,
setConnections,
getConnection,
}
}
|
AlexeyBond/image-size
|
lib/types/png.ts
|
<reponame>AlexeyBond/image-size<gh_stars>1000+
import { IImage } from './interface'
const pngSignature = 'PNG\r\n\x1a\n'
const pngImageHeaderChunkName = 'IHDR'
// Used to detect "fried" png's: http://www.jongware.com/pngdefry.html
const pngFriedChunkName = 'CgBI'
export const PNG: IImage = {
validate(buffer) {
if (pngSignature === buffer.toString('ascii', 1, 8)) {
let chunkName = buffer.toString('ascii', 12, 16)
if (chunkName === pngFriedChunkName) {
chunkName = buffer.toString('ascii', 28, 32)
}
if (chunkName !== pngImageHeaderChunkName) {
throw new TypeError('Invalid PNG')
}
return true
}
return false
},
calculate(buffer) {
if (buffer.toString('ascii', 12, 16) === pngFriedChunkName) {
return {
height: buffer.readUInt32BE(36),
width: buffer.readUInt32BE(32)
}
}
return {
height: buffer.readUInt32BE(20),
width: buffer.readUInt32BE(16)
}
}
}
|
AlexeyBond/image-size
|
lib/types/dds.ts
|
<reponame>AlexeyBond/image-size<gh_stars>1000+
import { IImage } from './interface'
export const DDS: IImage = {
validate(buffer) {
return buffer.readUInt32LE(0) === 0x20534444
},
calculate(buffer) {
return {
height: buffer.readUInt32LE(12),
width: buffer.readUInt32LE(16)
}
}
}
|
AlexeyBond/image-size
|
specs/valid.spec.ts
|
import { expect } from 'chai'
import { sync as globSync } from 'glob'
import { extname, resolve } from 'path'
import { openSync, readSync } from 'fs'
import { imageSize } from '../lib'
import { detector } from '../lib/detector'
import { ISizeCalculationResult } from '../lib/types/interface'
const bufferSize = 8192
const sizes: { [key: string]: ISizeCalculationResult} = {
default: {
width: 123,
height: 456
},
'specs/images/valid/cur/sample.cur': {
width: 32, height: 32
},
'specs/images/valid/ico/sample.ico': {
width: 32, height: 32
},
'specs/images/valid/ico/sample-compressed.ico': {
width: 32, height: 32
},
'specs/images/valid/ico/sample-256.ico': {
width: 256, height: 256
},
'specs/images/valid/ico/sample-256-compressed.ico': {
width: 256, height: 256
},
'specs/images/valid/icns/sample.icns': {
width: 16,
height: 16,
images: [
{ width: 16, height: 16, type: 'is32' },
{ width: 16, height: 16, type: 's8mk' },
{ width: 32, height: 32, type: 'il32' },
{ width: 32, height: 32, type: 'l8mk' },
{ width: 48, height: 48, type: 'ih32' },
{ width: 48, height: 48, type: 'h8mk' },
{ width: 128, height: 128, type: 'it32' },
{ width: 128, height: 128, type: 't8mk' }
],
type: 'icns'
},
'specs/images/valid/ico/multi-size.ico': {
width: 256,
height: 256,
images: [
{width: 256, height: 256},
{width: 128, height: 128},
{width: 96, height: 96},
{width: 72, height: 72},
{width: 64, height: 64},
{width: 48, height: 48},
{width: 32, height: 32},
{width: 24, height: 24},
{width: 16, height: 16}
]
},
'specs/images/valid/ico/multi-size-compressed.ico': {
width: 256,
height: 256,
images: [
{width: 256, height: 256},
{width: 128, height: 128},
{width: 96, height: 96},
{width: 72, height: 72},
{width: 64, height: 64},
{width: 48, height: 48},
{width: 32, height: 32},
{width: 24, height: 24},
{width: 16, height: 16}
]
},
'specs/images/valid/jpg/large.jpg': {
width: 1600,
height: 1200
},
'specs/images/valid/jpg/very-large.jpg': {
width: 4800,
height: 3600
},
'specs/images/valid/jpg/1x2-flipped-big-endian.jpg': {
width: 1,
height: 2,
orientation: 8
},
'specs/images/valid/jpg/1x2-flipped-little-endian.jpg': {
width: 1,
height: 2,
orientation: 8
},
'specs/images/valid/png/sample_fried.png': {
width: 128,
height: 68
}
}
// Test all valid files
describe('Valid images', () => {
const validFiles = globSync('specs/images/valid/**/*.*')
.filter(file => extname(file) !== '.md')
validFiles.forEach(file => describe(file, () => {
let type: string | undefined
let bufferDimensions: ISizeCalculationResult
let asyncDimensions: ISizeCalculationResult
beforeEach(done => {
const buffer = Buffer.alloc(bufferSize)
const filepath = resolve(file)
const descriptor = openSync(filepath, 'r')
readSync(descriptor, buffer, 0, bufferSize, 0)
type = detector(buffer)
// tiff cannot support buffers, unless the buffer contains the entire file
if (type !== 'tiff') {
bufferDimensions = imageSize(buffer)
}
imageSize(file, (err, dim) => {
if (err || !dim) {
done(err)
} else {
asyncDimensions = dim
done()
}
})
})
it('should return correct size for ' + file, () => {
const expected = sizes[file as keyof typeof sizes] || sizes.default
expect(asyncDimensions.width).to.equal(expected.width)
expect(asyncDimensions.height).to.equal(expected.height)
if (asyncDimensions.images) {
asyncDimensions.images.forEach((item, index) => {
if (expected.images) {
const expectedItem = expected.images[index]
expect(item.width).to.equal(expectedItem.width)
expect(item.height).to.equal(expectedItem.height)
if (expectedItem.type) {
expect(item.type).to.equal(expectedItem.type)
}
}
})
}
if (expected.orientation) {
expect(asyncDimensions.orientation).to.equal(expected.orientation)
}
if (type !== 'tiff') {
expect(bufferDimensions.width).to.equal(expected.width)
expect(bufferDimensions.height).to.equal(expected.height)
if (bufferDimensions.images) {
bufferDimensions.images.forEach((item, index) => {
if (expected.images) {
const expectedItem = expected.images[index]
expect(item.width).to.equal(expectedItem.width)
expect(item.height).to.equal(expectedItem.height)
}
})
}
}
})
}))
})
|
AlexeyBond/image-size
|
lib/types/tiff.ts
|
// based on http://www.compix.com/fileformattif.htm
// TO-DO: support big-endian as well
import * as fs from 'fs'
import { IImage } from './interface'
import { readUInt } from '../readUInt'
// Read IFD (image-file-directory) into a buffer
function readIFD(buffer: Buffer, filepath: string, isBigEndian: boolean) {
const ifdOffset = readUInt(buffer, 32, 4, isBigEndian)
// read only till the end of the file
let bufferSize = 1024
const fileSize = fs.statSync(filepath).size
if (ifdOffset + bufferSize > fileSize) {
bufferSize = fileSize - ifdOffset - 10
}
// populate the buffer
const endBuffer = Buffer.alloc(bufferSize)
const descriptor = fs.openSync(filepath, 'r')
fs.readSync(descriptor, endBuffer, 0, bufferSize, ifdOffset)
fs.closeSync(descriptor)
return endBuffer.slice(2)
}
// TIFF values seem to be messed up on Big-Endian, this helps
function readValue(buffer: Buffer, isBigEndian: boolean): number {
const low = readUInt(buffer, 16, 8, isBigEndian)
const high = readUInt(buffer, 16, 10, isBigEndian)
return (high << 16) + low
}
// move to the next tag
function nextTag(buffer: Buffer) {
if (buffer.length > 24) {
return buffer.slice(12)
}
}
// Extract IFD tags from TIFF metadata
function extractTags(buffer: Buffer, isBigEndian: boolean) {
const tags: {[key: number]: number} = {}
let temp: Buffer | undefined = buffer
while (temp && temp.length) {
const code = readUInt(temp, 16, 0, isBigEndian)
const type = readUInt(temp, 16, 2, isBigEndian)
const length = readUInt(temp, 32, 4, isBigEndian)
// 0 means end of IFD
if (code === 0) {
break
} else {
// 256 is width, 257 is height
// if (code === 256 || code === 257) {
if (length === 1 && (type === 3 || type === 4)) {
tags[code] = readValue(temp, isBigEndian)
}
// move to the next tag
temp = nextTag(temp)
}
}
return tags
}
// Test if the TIFF is Big Endian or Little Endian
function determineEndianness(buffer: Buffer) {
const signature = buffer.toString('ascii', 0, 2)
if ('II' === signature) {
return 'LE'
} else if ('MM' === signature) {
return 'BE'
}
}
const signatures = [
// '492049', // currently not supported
'49492a00', // Little endian
'4d4d002a', // Big Endian
// '4d4d002a', // BigTIFF > 4GB. currently not supported
]
export const TIFF: IImage = {
validate(buffer) {
return signatures.includes(buffer.toString('hex', 0, 4))
},
calculate(buffer, filepath) {
if (!filepath) {
throw new TypeError('Tiff doesn\'t support buffer')
}
// Determine BE/LE
const isBigEndian = determineEndianness(buffer) === 'BE'
// read the IFD
const ifdBuffer = readIFD(buffer, filepath, isBigEndian)
// extract the tags from the IFD
const tags = extractTags(ifdBuffer, isBigEndian)
const width = tags[256]
const height = tags[257]
if (!width || !height) {
throw new TypeError('Invalid Tiff. Missing tags')
}
return { height, width }
}
}
|
AlexeyBond/image-size
|
lib/readUInt.ts
|
type Bits = 16 | 32
type MethodName = 'readUInt16BE' | 'readUInt16LE' | 'readUInt32BE' | 'readUInt32LE'
// Abstract reading multi-byte unsigned integers
export function readUInt(buffer: Buffer, bits: Bits, offset: number, isBigEndian: boolean): number {
offset = offset || 0
const endian = isBigEndian ? 'BE' : 'LE'
const methodName: MethodName = ('readUInt' + bits + endian) as MethodName
return buffer[methodName].call(buffer, offset)
}
|
AlexeyBond/image-size
|
lib/types/interface.ts
|
export interface ISize {
width: number | undefined
height: number | undefined
orientation?: number
type?: string
}
export interface ISizeCalculationResult extends ISize {
images?: ISize[]
}
export interface IImage {
validate: (buffer: Buffer) => boolean
calculate: (buffer: Buffer, filepath?: string) => ISizeCalculationResult
}
|
AlexeyBond/image-size
|
lib/types/bmp.ts
|
<reponame>AlexeyBond/image-size
import { IImage } from './interface'
export const BMP: IImage = {
validate(buffer) {
return ('BM' === buffer.toString('ascii', 0, 2))
},
calculate(buffer) {
return {
height: Math.abs(buffer.readInt32LE(22)),
width: buffer.readUInt32LE(18)
}
}
}
|
AlexeyBond/image-size
|
specs/others.spec.ts
|
<reponame>AlexeyBond/image-size
import { resolve } from 'path'
import { openSync, readSync } from 'fs'
import { expect } from 'chai'
import { imageSize, types, disableTypes, disableFS } from '../lib'
// If something other than a buffer or filepath is passed
describe('Invalid invocation', () => {
describe('passing buffer for tiff', () => {
const bufferSize = 2048
const file = 'specs/images/valid/tiff/little-endian.tiff'
it('should throw', () => {
const buffer = Buffer.alloc(bufferSize)
const filepath = resolve(file)
const descriptor = openSync(filepath, 'r')
readSync(descriptor, buffer, 0, bufferSize, 0)
expect(() => imageSize(buffer)).to.throw(TypeError, 'Tiff doesn\'t support buffer')
})
})
describe('for a disabled image type', () => {
before(() => disableTypes(['jpg', 'bmp']))
after(() => disableTypes([]))
it('should throw', () => {
expect(() => imageSize('specs/images/valid/jpg/sample.jpg'))
.to.throw(TypeError, 'disabled file type: jpg')
expect(() => imageSize('specs/images/valid/bmp/sample.bmp'))
.to.throw(TypeError, 'disabled file type: bmp')
expect(() => imageSize('specs/images/valid/png/sample.png'))
.to.not.throw()
})
})
describe('when FS reads are disabled', () => {
before(() => disableFS(true))
after(() => disableFS(false))
it ('should only allow buffer inputs', () => {
expect(() => imageSize('specs/images/valid/jpg/sample.jpg'))
.to.throw(TypeError, 'invalid invocation. input should be a Buffer')
})
})
})
describe('Callback ', () => {
it('should be called only once', (done) => {
const tmpError = new Error()
const origException = process.listeners('uncaughtException').pop()
if (origException) {
process.removeListener('uncaughtException', origException)
}
process.once('uncaughtException', (err) => {
expect(err).to.equal(tmpError)
})
imageSize('specs/images/valid/jpg/sample.jpg', () => {
process.nextTick(() => done())
throw tmpError
})
})
})
describe('.types property', () => {
it('should expose supported file types', () => {
expect(types).to.eql(['bmp', 'cur', 'dds', 'gif', 'icns', 'ico', 'j2c', 'jp2', 'jpg', 'ktx', 'png', 'pnm', 'psd', 'svg', 'tiff', 'webp'])
})
})
|
AlexeyBond/image-size
|
specs/invalid.spec.ts
|
import { expect } from 'chai'
import { sync as globSync } from 'glob'
import { imageSize } from '../lib'
// Test all invalid files
describe('Invalid Images', () => {
const invalidFiles = globSync('specs/images/invalid/**/*.*')
invalidFiles.forEach((file) => {
describe(file, () => {
it('should throw when called synchronously', () => {
expect(() => imageSize(file)).to.throw(TypeError, 'Invalid')
})
it('should callback with error when called asynchronously', done => {
imageSize(file, e => {
expect(e).to.be.instanceOf(TypeError)
expect(e?.message).to.match(/^Invalid \w+$/)
done()
})
})
})
})
describe('non-existent file', () => {
const fakeFile = 'fakefile.jpg'
it('should throw when called synchronously', () => {
expect(() => imageSize(fakeFile)).to.throw(Error, 'ENOENT')
})
it('should callback with error when called asynchronously', (done) => {
imageSize(fakeFile, e => {
expect(e?.message).to.match(/^ENOENT.*$/)
done()
})
})
})
})
|
AlexeyBond/image-size
|
lib/types/gif.ts
|
<filename>lib/types/gif.ts
import { IImage } from './interface'
const gifRegexp = /^GIF8[79]a/
export const GIF: IImage = {
validate(buffer) {
const signature = buffer.toString('ascii', 0, 6)
return (gifRegexp.test(signature))
},
calculate(buffer) {
return {
height: buffer.readUInt16LE(8),
width: buffer.readUInt16LE(6)
}
}
}
|
AlexeyBond/image-size
|
specs/fs-close.spec.ts
|
import { expect } from 'chai'
import * as sinon from 'sinon'
import * as fs from 'fs'
import { imageSize } from '../lib'
describe('after done reading from files', () => {
const readFromClosed = (fd: number) => fs.readSync(fd, Buffer.alloc(1), 0, 1, 0)
describe('should close the file descriptor', () => {
it('async', done => {
const spy = sinon.spy(fs.promises, 'open')
imageSize('specs/images/valid/jpg/large.jpg', () => {
expect(spy.calledOnce).to.be.true
const fsPromise = spy.returnValues[0]
fsPromise.then((handle) => {
expect(() => readFromClosed(handle.fd)).to.throw(Error)
spy.restore()
done()
})
})
})
// TODO: revisit this spec. how to ensure that we never leave descriptors open
it('sync', () => {
const spy = sinon.spy(fs, 'openSync')
imageSize('specs/images/valid/jpg/large.jpg')
expect(() => readFromClosed(spy.returnValues[0])).to.throw(Error, 'bad file descriptor')
spy.restore()
})
})
})
|
AlexeyBond/image-size
|
specs/imports.spec.ts
|
<filename>specs/imports.spec.ts
import { expect } from 'chai'
import imageSize, { imageSize as imageSizeNamed } from '../lib'
describe('Imports', () => {
it('should import both default and named export', () => {
expect(imageSize).to.equal(imageSizeNamed)
})
})
|
AlexeyBond/image-size
|
lib/types/jpg.ts
|
// NOTE: we only support baseline and progressive JPGs here
// due to the structure of the loader class, we only get a buffer
// with a maximum size of 4096 bytes. so if the SOF marker is outside
// if this range we can't detect the file size correctly.
import { IImage, ISize } from './interface'
import { readUInt } from '../readUInt'
const EXIF_MARKER = '45786966'
const APP1_DATA_SIZE_BYTES = 2
const EXIF_HEADER_BYTES = 6
const TIFF_BYTE_ALIGN_BYTES = 2
const BIG_ENDIAN_BYTE_ALIGN = '4d4d'
const LITTLE_ENDIAN_BYTE_ALIGN = '4949'
// Each entry is exactly 12 bytes
const IDF_ENTRY_BYTES = 12
const NUM_DIRECTORY_ENTRIES_BYTES = 2
function isEXIF(buffer: Buffer): boolean {
return (buffer.toString('hex', 2, 6) === EXIF_MARKER)
}
function extractSize(buffer: Buffer, index: number): ISize {
return {
height : buffer.readUInt16BE(index),
width : buffer.readUInt16BE(index + 2)
}
}
function extractOrientation(exifBlock: Buffer, isBigEndian: boolean) {
// TODO: assert that this contains 0x002A
// let STATIC_MOTOROLA_TIFF_HEADER_BYTES = 2
// let TIFF_IMAGE_FILE_DIRECTORY_BYTES = 4
// TODO: derive from TIFF_IMAGE_FILE_DIRECTORY_BYTES
const idfOffset = 8
// IDF osset works from right after the header bytes
// (so the offset includes the tiff byte align)
const offset = EXIF_HEADER_BYTES + idfOffset
const idfDirectoryEntries = readUInt(exifBlock, 16, offset, isBigEndian)
for (let directoryEntryNumber = 0; directoryEntryNumber < idfDirectoryEntries; directoryEntryNumber++) {
const start = offset + NUM_DIRECTORY_ENTRIES_BYTES + (directoryEntryNumber * IDF_ENTRY_BYTES)
const end = start + IDF_ENTRY_BYTES
// Skip on corrupt EXIF blocks
if (start > exifBlock.length) {
return
}
const block = exifBlock.slice(start, end)
const tagNumber = readUInt(block, 16, 0, isBigEndian)
// 0x0112 (decimal: 274) is the `orientation` tag ID
if (tagNumber === 274) {
const dataFormat = readUInt(block, 16, 2, isBigEndian)
if (dataFormat !== 3) {
return
}
// unsinged int has 2 bytes per component
// if there would more than 4 bytes in total it's a pointer
const numberOfComponents = readUInt(block, 32, 4, isBigEndian)
if (numberOfComponents !== 1) {
return
}
return readUInt(block, 16, 8, isBigEndian)
}
}
}
function validateExifBlock(buffer: Buffer, index: number) {
// Skip APP1 Data Size
const exifBlock = buffer.slice(APP1_DATA_SIZE_BYTES, index)
// Consider byte alignment
const byteAlign = exifBlock.toString('hex', EXIF_HEADER_BYTES, EXIF_HEADER_BYTES + TIFF_BYTE_ALIGN_BYTES)
// Ignore Empty EXIF. Validate byte alignment
const isBigEndian = byteAlign === BIG_ENDIAN_BYTE_ALIGN
const isLittleEndian = byteAlign === LITTLE_ENDIAN_BYTE_ALIGN
if (isBigEndian || isLittleEndian) {
return extractOrientation(exifBlock, isBigEndian)
}
}
function validateBuffer(buffer: Buffer, index: number): void {
// index should be within buffer limits
if (index > buffer.length) {
throw new TypeError('Corrupt JPG, exceeded buffer limits')
}
// Every JPEG block must begin with a 0xFF
if (buffer[index] !== 0xFF) {
throw new TypeError('Invalid JPG, marker table corrupted')
}
}
export const JPG: IImage = {
validate(buffer) {
const SOIMarker = buffer.toString('hex', 0, 2)
return ('ffd8' === SOIMarker)
},
calculate(buffer) {
// Skip 4 chars, they are for signature
buffer = buffer.slice(4)
let orientation: number | undefined
let next: number
while (buffer.length) {
// read length of the next block
const i = buffer.readUInt16BE(0)
if (isEXIF(buffer)) {
orientation = validateExifBlock(buffer, i)
}
// ensure correct format
validateBuffer(buffer, i)
// 0xFFC0 is baseline standard(SOF)
// 0xFFC1 is baseline optimized(SOF)
// 0xFFC2 is progressive(SOF2)
next = buffer[i + 1]
if (next === 0xC0 || next === 0xC1 || next === 0xC2) {
const size = extractSize(buffer, i + 5)
// TODO: is orientation=0 a valid answer here?
if (!orientation) {
return size
}
return {
height: size.height,
orientation,
width: size.width
}
}
// move to the next block
buffer = buffer.slice(i + 2)
}
throw new TypeError('Invalid JPG, no size found')
}
}
|
AlexeyBond/image-size
|
lib/types/webp.ts
|
<gh_stars>1000+
// based on https://developers.google.com/speed/webp/docs/riff_container
import { IImage, ISize } from './interface'
function calculateExtended(buffer: Buffer): ISize {
return {
height: 1 + buffer.readUIntLE(7, 3),
width: 1 + buffer.readUIntLE(4, 3)
}
}
function calculateLossless(buffer: Buffer): ISize {
return {
height: 1 + (((buffer[4] & 0xF) << 10) | (buffer[3] << 2) | ((buffer[2] & 0xC0) >> 6)),
width: 1 + (((buffer[2] & 0x3F) << 8) | buffer[1])
}
}
function calculateLossy(buffer: Buffer): ISize {
// `& 0x3fff` returns the last 14 bits
// TO-DO: include webp scaling in the calculations
return {
height: buffer.readInt16LE(8) & 0x3fff,
width: buffer.readInt16LE(6) & 0x3fff
}
}
export const WEBP: IImage = {
validate(buffer) {
const riffHeader = 'RIFF' === buffer.toString('ascii', 0, 4)
const webpHeader = 'WEBP' === buffer.toString('ascii', 8, 12)
const vp8Header = 'VP8' === buffer.toString('ascii', 12, 15)
return (riffHeader && webpHeader && vp8Header)
},
calculate(buffer) {
const chunkHeader = buffer.toString('ascii', 12, 16)
buffer = buffer.slice(20, 30)
// Extended webp stream signature
if (chunkHeader === 'VP8X') {
const extendedHeader = buffer[0]
const validStart = (extendedHeader & 0xc0) === 0
const validEnd = (extendedHeader & 0x01) === 0
if (validStart && validEnd) {
return calculateExtended(buffer)
} else {
// TODO: breaking change
throw new TypeError('Invalid WebP')
}
}
// Lossless webp stream signature
if (chunkHeader === 'VP8 ' && buffer[0] !== 0x2f) {
return calculateLossy(buffer)
}
// Lossy webp stream signature
const signature = buffer.toString('hex', 3, 6)
if (chunkHeader === 'VP8L' && signature !== '9d012a') {
return calculateLossless(buffer)
}
throw new TypeError('Invalid WebP')
}
}
|
heikomat/series-rename
|
src/index.ts
|
<reponame>heikomat/series-rename
#!/usr/bin/env node
import {FileBrowser} from './filebrowser';
new FileBrowser()
.start();
|
heikomat/series-rename
|
src/filebrowser.ts
|
import {promises as fsPromises, rename} from 'fs';
import {Select, Input, Confirm} from 'enquirer/lib/prompts';
import path from 'path';
import rimraf from 'rimraf';
import TVDB from 'node-tvdb';
type KeyPressData = {
sequence: string,
name: string,
ctrl: boolean,
meta: boolean,
shift: boolean,
};
type SeriesLanguage = {
id: number,
abbreviation: string,
name: string,
englishName: string,
}
type Episode = {
id: number,
airedSeason: number,
airedSeasonID: number,
airedEpisodeNumber: number,
episodeName: string,
firstAired: string,
overview: string,
productionCode: string,
showUrl: string,
lastUpdated: number,
dvdDiscid: string,
dvdSeason: number,
dvdEpisodeNumber: number
dvdChapter: number,
absoluteNumber: number,
filename: string,
seriesId: number,
lastUpdatedBy: number,
thumbAuthor: number,
thumbAdded: string,
thumbWidth: string,
thumbHeight: string,
imdbId: string,
siteRating: number,
siteRatingCount: number
}
type Series = {
aliases: Array<string>,
banner: string,
firsAired: string,
id: number,
network: string,
overview: string,
seriesName: string,
slug: string,
status: string,
episodes: Array<Episode>
}
type ArrayPromptOption = {
name: string,
message: string,
value: any,
disabled?: boolean,
}
type FolderSeasonMatch = {
folderName: string,
season: number,
}
interface EpisodeMapping extends ArrayPromptOption {
value: {
originalPath: string,
updatedPath: string,
rename: boolean,
episode: Episode,
episodeNumber: string,
seasonNumber: number,
seasonFolder: string,
}
}
interface SeasonMapping {
[season: number]: {
folderName?: string,
episodeMappings: Array<EpisodeMapping>
}
}
const tvdb = new TVDB(process.env.TVDB_API_KEY);
const videoFileExtensions = ['.mp4', '.mkv', '.avi'];
const episodeRegexes = [
{regex: /[eE]\d+/, numberStart: 1},
{regex: /[xX]\d+/, numberStart: 1},
{regex: /\d+/, numberStart: 0}
];
const episodeReplaces = [
{regex: /ä/g, replacement: 'ae'},
{regex: /ö/g, replacement: 'oe'},
{regex: /ü/g, replacement: 'ue'},
{regex: /ß/g, replacement: 'ss'},
{regex: /Ä/g, replacement: 'AE'},
{regex: /Ö/g, replacement: 'OE'},
{regex: /Ü/g, replacement: 'UE'},
{regex: /\?/g, replacement: ''},
{regex: /,/g, replacement: ''},
{regex: /: /g, replacement: '-'},
{regex: /:/g, replacement: '-'},
{regex: /"/g, replacement: '\''},
{regex: / /g, replacement: '.'},
{regex: /\//g, replacement: '_'},
{regex: /\t/g, replacement: ''},
]
export class FileBrowser {
private startDirectory: string;
private currentDirectory: string;
private highlightedFolder: string = '..';
private currentPrompt:
'folder-selection'
| 'rename'
| 'create-folder'
| 'delete-folder'
| 'series-language'
| 'series-name'
| 'series-suggestions'
| 'episode-renames'
| 'assign-episode'
| 'move-folder'
| 'non-video-purge'
| 'hoist-files';
private filesPrompt: Select;
private confirmDeletePrompt: Confirm;
private confirmHoistPrompt: Confirm;
private moveFolderPrompt: Select;
private confirmPurgePrompt: Confirm;
private seriesLanguagePrompt: Select;
private seriesNamePrompt: Input;
private seriesSelectionPrompt: Select;
private episodeRenamePrompt: Select;
private episodeAssignPrompt: Select;
private currentFolderToMove: string;
private currentMoveTarget: string;
private currentSeriesDirectory: string;
private currentSeriesLanguage: SeriesLanguage;
private currentSeriesName: string;
private currentSeries: Series;
private currentEpisodeRenames: SeasonMapping;
private currentEpisodeAssign: EpisodeMapping;
constructor(startDirectory: string = process.cwd()) {
this.startDirectory = startDirectory;
this.currentDirectory = this.startDirectory;
}
public async start(): Promise<void> {
process.stdin.on('keypress', this.handleKeyPress);
console.clear();
this.promptMainMenu();
}
private async promptMainMenu(): Promise<void> {
this.currentPrompt = 'folder-selection';
const [files, folders] = await Promise.all([
this.getFileNames(this.currentDirectory),
this.getFolderNames(this.currentDirectory),
])
const folderOptions = folders.map((folderName: string) => {
return {name: folderName, message: folderName, value: folderName, disabled: false}
});
const fileOptopns = files.map((folderName: string) => {
return {name: folderName, message: folderName, value: folderName, disabled: ''}
});
const options = [
{name: '..', message: '..', value: '..'},
...folderOptions,
...fileOptopns,
]
this.filesPrompt = new Select({
message: null,
choices: options,
header: this.currentDirectory,
initial: this.highlightedFolder,
footer: '[R]ename, [C]reate folder, [D]elete, [M]ove, [U]pdate, [H]oist files, [P]urge non-videos, [S]tandardize names, [E]xit',
});
const selectedFolder = await this.filesPrompt.run();
this.filesPrompt.stop();
if (selectedFolder === '..') {
this.highlightedFolder = path.basename(this.currentDirectory);
} else {
this.highlightedFolder = '..';
}
this.currentDirectory = path.join(this.currentDirectory, selectedFolder);
console.clear();
this.promptMainMenu();
}
private async promptRename(filePath: string) {
this.currentPrompt = 'rename';
const directory = path.dirname(filePath);
const filename = path.basename(filePath);
const renamePrompt = new Input({
message: `rename ${filename}`,
header: directory,
footer: 'esc = abort',
initial: filename,
});
console.clear();
try {
const newName = await renamePrompt.run();
renamePrompt.stop();
const oldPath = path.join(directory, filename);
const newPath = path.join(directory, newName);
await fsPromises.rename(oldPath, newPath);
this.highlightedFolder = newName;
} catch (error) {
renamePrompt.stop();
// probably just aborted
}
console.clear();
this.promptMainMenu();
}
private async promptCreateFolder(targetDirectory: string) {
this.currentPrompt = 'create-folder';
const createFolderPrompt = new Input({
message: 'name',
header: targetDirectory,
footer: 'esc = abort',
});
console.clear();
try {
const folderName = await createFolderPrompt.run();
createFolderPrompt.stop();
await fsPromises.mkdir(path.join(targetDirectory, folderName));
this.highlightedFolder = folderName;
} catch (error) {
createFolderPrompt.stop();
// probably just aborted
}
console.clear();
this.promptMainMenu();
}
private async promptDeleteFolder(filePath: string) {
this.currentPrompt = 'delete-folder';
this.confirmDeletePrompt = new Confirm({
message: `deleting ${filePath}. Are you sure?`,
footer: 'esc = abort',
});
console.clear();
try {
const userAgreed = await this.confirmDeletePrompt.run();
this.confirmDeletePrompt.stop();
if (userAgreed) {
await new Promise((resolve) => {
rimraf(filePath, resolve);
})
this.highlightedFolder = '..';
}
} catch (error) {
this.confirmDeletePrompt.stop();
// probably just aborted
}
console.clear();
this.promptMainMenu();
}
private async hoistFiles(directory: string) {
this.currentPrompt = 'hoist-files';
const files = await this.getAllFilesInFolder(directory);
console.clear();
this.confirmHoistPrompt = new Confirm({
message: `hoisting ${files.length} files. Are you sure?`,
footer: 'esc = abort',
});
try {
const userAgreed = await this.confirmHoistPrompt.run();
this.confirmHoistPrompt.stop();
if (userAgreed) {
// move all children to the target directory
await Promise.all(files.map((filePath: string) => {
const filename = path.basename(filePath);
const targetFile = path.join(directory, filename);
if (filePath === targetFile) {
return undefined;
}
return fsPromises.rename(filePath, targetFile);
}));
// delete all the now empty folders
const remainingFolders = await this.getFolderNames(directory);
await Promise.all(remainingFolders.map((folderName) => {
return new Promise((resolve) => {
rimraf(path.join(directory, folderName), resolve);
})
}));
this.highlightedFolder = '..';
}
} catch (error) {
this.confirmHoistPrompt.stop();
// probably just aborted
}
console.clear();
this.promptMainMenu();
}
private async promptMoveFolder(currentDirectory: string, folderToMove: string): Promise<void> {
this.currentPrompt = 'move-folder';
this.currentFolderToMove = folderToMove;
const folders = await this.getFolderNames(currentDirectory)
const folderNameToMove = path.basename(folderToMove);
this.currentMoveTarget = path.join(currentDirectory, folderNameToMove);
const folderAlreadyExists = folders.some((folderName) => {
return folderName === folderNameToMove;
});
const targetIsAcceptable = !folderAlreadyExists;
const folderOptions = folders.map((folderName: string) => {
const targetIsInsideSelf = path.join(currentDirectory, folderName).startsWith(folderToMove);
let folderIsDisabled: string | boolean = false;
if (targetIsInsideSelf) {
folderIsDisabled = '(can\'t move a folder into itself)';
}
return {name: folderName, message: folderName, value: folderName, disabled: folderIsDisabled}
});
const options = [
{name: '..', message: '..', value: '..'},
...folderOptions,
]
const header = folderAlreadyExists
? `move: ${folderToMove}\n to: '${folderNameToMove}' already exists here. choose a different location.`
: `move: ${folderToMove}\n to: ${path.join(currentDirectory, folderNameToMove)}`;
const footer = targetIsAcceptable
? '[a]ccept, esc = abort'
: 'esc = abort'
this.moveFolderPrompt = new Select({
message: null,
choices: options,
header: header,
initial: this.highlightedFolder,
footer: footer,
});
console.clear();
try {
const selectedFolder = await this.moveFolderPrompt.run();
this.moveFolderPrompt.stop();
this.promptMoveFolder(path.join(currentDirectory, selectedFolder), folderToMove);
} catch {
this.moveFolderPrompt.stop();
console.clear();
this.promptMainMenu();
}
}
private async moveFolder(folderToMove: string, target: string) {
await fsPromises.rename(folderToMove, target);
console.clear();
this.promptMainMenu();
}
private async promptNonVideoPurge(folderToPurge: string): Promise<void> {
this.currentPrompt = 'non-video-purge';
const files = await this.getAllFilesInFolder(folderToPurge);
const nonVideoFiles = files.filter((filename: string) => {
const fileExtension = path.extname(filename).toLowerCase();
const fileIsVideo = videoFileExtensions.includes(fileExtension);
return !fileIsVideo;
});
console.clear();
this.confirmPurgePrompt = new Confirm({
message: `deleting ${nonVideoFiles.length} non-video files. Are you sure?`,
footer: 'esc = abort',
});
try {
const userAgreed = await this.confirmPurgePrompt.run();
this.confirmPurgePrompt.stop();
if (userAgreed) {
// delete all non-video-files
await Promise.all(nonVideoFiles.map((fileName: string) => {
return fsPromises.unlink(fileName);
}));
}
} catch (error) {
this.confirmPurgePrompt.stop();
// probably just aborted
}
console.clear();
this.promptMainMenu();
}
private async promptSeriesRename(seriesDirectory: string): Promise<void> {
this.currentSeriesDirectory = seriesDirectory;
console.clear();
this.promptSeriesLanguage(seriesDirectory);
}
private async promptSeriesLanguage(seriesDirectory) {
this.currentPrompt = 'series-language';
this.currentEpisodeRenames = undefined;
const languages: Array<SeriesLanguage> = await tvdb.getLanguages();
const options = languages.map((language: any) => {
return {
name: language.abbreviation,
message: language.englishName,
value: language,
};
});
this.seriesLanguagePrompt = new Select({
message: null,
choices: options,
header: `Folder: ${seriesDirectory}`,
initial: 'de',
footer: 'esc = abort',
});
try {
await this.seriesLanguagePrompt.run();
this.currentSeriesLanguage = this.seriesLanguagePrompt.selected.value;
this.seriesLanguagePrompt.stop();
console.clear();
this.promptSeriesName(seriesDirectory, this.currentSeriesLanguage);
} catch {
this.seriesLanguagePrompt.stop();
console.clear();
this.promptMainMenu();
}
}
private async promptSeriesName(seriesDirectory: string, seriesLanguage: SeriesLanguage) {
this.currentPrompt = 'series-name';
const seriesName = path.basename(seriesDirectory);
this.seriesNamePrompt = new Input({
message: `series name`,
header: `Folder: ${seriesDirectory}\nLanguage: ${seriesLanguage.englishName}`,
footer: 'esc = abort',
initial: seriesName,
});
try {
this.currentSeriesName = await this.seriesNamePrompt.run();
this.seriesNamePrompt.stop();
console.clear();
this.promptSeriesSuggestions(seriesDirectory, seriesLanguage, this.currentSeriesName);
} catch (error) {
// probably just aborted
this.seriesNamePrompt.stop();
console.clear();
this.promptSeriesLanguage(seriesDirectory);
}
}
private async promptSeriesSuggestions(seriesDirectory: string, seriesLanguage: SeriesLanguage, seriesName: string) {
this.currentPrompt = 'series-suggestions';
this.currentEpisodeRenames = undefined;
let possibleSeries: Array<Series>;
try {
possibleSeries = await tvdb.getSeriesByName(seriesName, {lang: seriesLanguage.abbreviation})
} catch {
console.clear();
console.log('Series not found. Did you spell it correctly?');
this.promptSeriesName(seriesDirectory, seriesLanguage);
return;
}
const options = possibleSeries.map((series: Series) => {
return {
name: series.id,
message: series.seriesName,
value: series,
};
});
this.seriesSelectionPrompt = new Select({
message: null,
choices: options,
header: `Folder: ${seriesDirectory}\nLanguage: ${seriesLanguage.englishName}\nSearchTerm: ${seriesName}`,
footer: 'esc = abort',
});
try {
await this.seriesSelectionPrompt.run();
this.currentSeries = this.seriesSelectionPrompt.selected.value;
this.seriesSelectionPrompt.stop();
console.clear();
this.promptEpisodeRenames(seriesDirectory, seriesLanguage, this.currentSeries);
} catch {
this.seriesSelectionPrompt.stop();
console.clear();
this.promptSeriesName(seriesDirectory, seriesLanguage);
}
}
private async promptEpisodeRenames(seriesDirectory: string, seriesLanguage: SeriesLanguage, selectedSeries: Series) {
this.currentPrompt = 'episode-renames';
const seriesDetails = await tvdb.getSeriesAllById(selectedSeries.id, {lang: seriesLanguage.abbreviation});
if (this.currentEpisodeRenames === undefined) {
this.currentEpisodeRenames = await this.generateEpisodeNames(seriesDirectory, seriesDetails);
}
const seasons = Object.keys(this.currentEpisodeRenames).sort();
const options = [];
for (const season of seasons) {
options.push({
name: `season${season}`,
message: `--- Season ${season} (${this.currentEpisodeRenames[season].folderName}) ---`,
value: `season${season}`,
disabled: '',
}, ...this.currentEpisodeRenames[season].episodeMappings)
}
this.episodeRenamePrompt = new Select({
message: null,
choices: options,
header: `Folder: ${seriesDirectory}\nLanguage: ${seriesLanguage.englishName}\nSeries: ${selectedSeries.seriesName}`,
footer: '[a]ccept, esc = abort',
initial: this.currentEpisodeAssign ? this.currentEpisodeAssign.name : undefined,
});
try {
await this.episodeRenamePrompt.run();
this.currentEpisodeAssign = this.episodeRenamePrompt.selected;
this.episodeRenamePrompt.stop();
console.clear();
this.promptEpisodeAssign(seriesDirectory, seriesLanguage, seriesDetails, this.currentEpisodeAssign);
} catch {
this.episodeRenamePrompt.stop();
console.clear();
this.promptSeriesName(seriesDirectory, seriesLanguage);
}
}
private async promptEpisodeAssign(seriesDirectory: string, seriesLanguage: SeriesLanguage, selectedSeries: Series, episodeMapping: EpisodeMapping) {
this.currentPrompt = 'assign-episode';
const possibleEpisodes = this.generateEpisodeSelection(selectedSeries, episodeMapping.value.seasonNumber);
const seasons = Object.keys(possibleEpisodes).sort();
const options = [];
for (const season of seasons) {
options.push({
name: `season${season}`,
message: `--- Season ${season} ---`,
value: `season${season}`,
disabled: '',
}, ...possibleEpisodes[season].episodeMappings)
}
this.episodeAssignPrompt = new Select({
message: null,
choices: options,
header: `File: ${episodeMapping.value.originalPath}\nLanguage: ${seriesLanguage.englishName}\nSeries: ${selectedSeries.seriesName}`,
footer: 'esc = abort',
});
try {
await this.episodeAssignPrompt.run();
const selectedEpisode: Episode = this.episodeAssignPrompt.selected.value;
const episodesInSeason = selectedSeries.episodes.filter((seriesEpisode: Episode) => {
return seriesEpisode.airedSeason === selectedEpisode.airedSeason;
});
const seasonMappings = this.currentEpisodeRenames[episodeMapping.value.seasonNumber];
for (let i = 0; i < seasonMappings.episodeMappings.length; i++) {
if (seasonMappings.episodeMappings[i].name === episodeMapping.name) {
seasonMappings.episodeMappings[i] = this.generateEpisodeName(
selectedSeries.seriesName,
episodeMapping.value.seasonFolder,
episodeMapping.value.seasonNumber,
path.basename(episodeMapping.value.originalPath),
episodesInSeason,
selectedEpisode.airedEpisodeNumber,
)
console.log(seasonMappings.episodeMappings[i]);
}
}
this.currentEpisodeRenames[episodeMapping.value.seasonNumber].episodeMappings.sort(this.sortEpisodeMappings);
this.episodeAssignPrompt.stop();
console.clear();
this.promptEpisodeRenames(seriesDirectory, seriesLanguage, selectedSeries);
} catch {
this.episodeAssignPrompt.stop();
console.clear();
this.promptSeriesName(seriesDirectory, seriesLanguage);
}
}
private async renameEpisodes(episodeRenames: SeasonMapping) {
let renamedFileCount = 0;
const seasonMappings = Object.values(episodeRenames).map((season: {folderName?: string, episodeMappings: Array<EpisodeMapping>}): Promise<Array<void>> => {
const episodeMappings = season.episodeMappings.map(async(episodeMapping: EpisodeMapping): Promise<void> =>{
if (episodeMapping.value.rename !== false) {
renamedFileCount++;
return fsPromises.rename(episodeMapping.value.originalPath, episodeMapping.value.updatedPath);
}
});
return Promise.all(episodeMappings);
});
await Promise.all(seasonMappings);
console.log(`renamed ${renamedFileCount} files`);
}
private async getAllFilesInFolder(folderPath: string): Promise<Array<string>> {
const currentFolderItems = await fsPromises.readdir(folderPath);
const [files, folders] = await Promise.all([
this.filterAsync(currentFolderItems, async (itemName: string): Promise<boolean> => {
const isFolder = await this.isFolder(path.join(folderPath, itemName));
return !isFolder
}),
this.filterAsync(currentFolderItems, async (itemName: string): Promise<boolean> => {
const isFolder = await this.isFolder(path.join(folderPath, itemName));
return isFolder
}),
]);
const filesInThisFolder = files.map((fileName: string) => {
return path.join(folderPath, fileName);
})
const filesInSubFolders = await Promise.all(folders.map((folderName: string) => {
return this.getAllFilesInFolder(path.join(folderPath, folderName));
}));
return [
...filesInThisFolder,
...filesInSubFolders.flat(),
]
}
private async getFolderNames(basePath: string): Promise<Array<string>> {
const currentFolderItems = await fsPromises.readdir(basePath);
return this.filterAsync(currentFolderItems, async (itemName: string): Promise<boolean> => {
const isFolder = await this.isFolder(path.join(basePath, itemName));
return isFolder
});
}
private async getFileNames(basePath: string): Promise<Array<string>> {
const currentFolderItems = await fsPromises.readdir(basePath);
return this.filterAsync(currentFolderItems, async (itemName: string): Promise<boolean> => {
const isFolder = await this.isFolder(path.join(basePath, itemName));
return !isFolder
});
}
private async isFolder(folderPath: string): Promise<boolean> {
let folderStats;
try {
folderStats = await fsPromises.stat(folderPath);
} catch {
return false;
}
return folderStats.isDirectory();
}
private async filterAsync<TArrayElement>(
arrayToFilter: Array<TArrayElement>,
filterMethod: (element: TArrayElement, index: number, originalArray: Array<TArrayElement>) => Promise<boolean>,
): Promise<Array<TArrayElement>> {
const filterResults: Array<boolean> = await Promise.all(arrayToFilter.map(filterMethod));
return arrayToFilter.filter((element: TArrayElement, index: number): boolean => {
const elementCanStayInArray: boolean = filterResults[index];
return elementCanStayInArray;
});
}
private handleKeyPress = (key: string, data: KeyPressData) : void=> {
if (this.currentPrompt === 'folder-selection') {
this.handleFolderSelectionKeyPress(key, data);
}
if (this.currentPrompt === 'move-folder') {
this.handleMoveFolderKeyPress(key, data);
}
if (this.currentPrompt === 'hoist-files') {
this.handleHoistFilesKeyPress(key, data);
}
if (this.currentPrompt === 'non-video-purge') {
this.handleNonVideoPurgeKeyPress(key, data);
}
if (this.currentPrompt === 'series-language') {
this.handleSeriesLanguageKeyPress(key, data);
}
if (this.currentPrompt === 'series-suggestions') {
this.handleSeriesSuggestionsKeyPress(key, data);
}
if (this.currentPrompt === 'episode-renames') {
this.handleEpisodeRenamesKeyPress(key, data);
}
if (this.currentPrompt === 'assign-episode') {
this.handleAssignEpisodeKeyPress(key, data);
}
}
private handleFolderSelectionKeyPress(key: string, data: KeyPressData): void {
this.highlightedFolder = this.filesPrompt.selected.value;
const selectedFolder = path.join(this.currentDirectory, this.filesPrompt.selected.value);
if (key === 'r') {
this.filesPrompt.stop();
this.promptRename(selectedFolder);
}
if (key === 'c') {
this.filesPrompt.stop();
this.promptCreateFolder(this.currentDirectory);
}
if (key === 'd') {
this.filesPrompt.stop();
this.promptDeleteFolder(selectedFolder);
}
if (key === 'h') {
this.filesPrompt.stop();
this.hoistFiles(this.currentDirectory);
}
if (key === 'm') {
this.filesPrompt.stop();
this.promptMoveFolder(this.currentDirectory, selectedFolder);
}
if (key === 'u') {
this.filesPrompt.stop();
console.clear();
this.promptMainMenu();
}
if (key === 'p') {
this.filesPrompt.stop();
this.promptNonVideoPurge(this.currentDirectory);
}
if (key === 'e') {
this.filesPrompt.stop();
}
if (key === 's') {
this.filesPrompt.stop();
this.promptSeriesRename(this.currentDirectory);
}
}
private handleMoveFolderKeyPress(key: string, data: KeyPressData): void {
if (key === 'a') {
this.moveFolderPrompt.stop();
this.moveFolder(this.currentFolderToMove, this.currentMoveTarget);
}
if (data.name === 'backspace') {
this.moveFolderPrompt.stop();
console.clear();
this.promptMainMenu();
}
}
private handleHoistFilesKeyPress(key: string, data: KeyPressData): void {
if (data.name === 'backspace') {
this.confirmHoistPrompt.stop();
console.clear();
this.promptMainMenu();
}
}
private handleNonVideoPurgeKeyPress(key: string, data: KeyPressData): void {
if (data.name === 'backspace') {
this.confirmPurgePrompt.stop();
console.clear();
this.promptMainMenu();
}
}
private handleSeriesLanguageKeyPress(key: string, data: KeyPressData): void {
if (data.name === 'backspace') {
this.seriesLanguagePrompt.stop();
console.clear();
this.promptMainMenu();
}
}
private handleSeriesSuggestionsKeyPress(key: string, data: KeyPressData): void {
if (data.name === 'backspace') {
this.seriesSelectionPrompt.stop();
console.clear();
this.promptSeriesName(this.currentSeriesDirectory, this.currentSeriesLanguage);
}
}
private handleEpisodeRenamesKeyPress(key: string, data: KeyPressData): void {
if (data.name === 'backspace') {
this.episodeRenamePrompt.stop();
console.clear();
this.promptSeriesSuggestions(this.currentSeriesDirectory, this.currentSeriesLanguage, this.currentSeriesName);
}
if (key === 'a') {
this.episodeRenamePrompt.stop();
console.clear();
this.renameEpisodes(this.currentEpisodeRenames);
this.promptMainMenu();
}
}
private handleAssignEpisodeKeyPress(key: string, data: KeyPressData): void {
if (data.name === 'backspace') {
this.episodeAssignPrompt.stop();
console.clear();
this.promptEpisodeRenames(this.currentSeriesDirectory, this.currentSeriesLanguage, this.currentSeries);
}
}
private generateEpisodeSelection(seriesDetails: Series, targetSeason?: number): SeasonMapping {
const result = {};
for (const episode of seriesDetails.episodes) {
const season = episode.airedSeason;
if (targetSeason !== undefined && season !== targetSeason) {
continue;
}
if (result[season] === undefined) {
result[season] = {episodeMappings: []}
}
result[season].episodeMappings.push(this.generateEpisodeMapping(seriesDetails, episode));
}
return result;
}
private generateEpisodeMapping(seriesDetails: Series, episode: Episode): ArrayPromptOption {
const episodesInSeason = seriesDetails.episodes.filter((seriesEpisode: Episode) => {
return seriesEpisode.airedSeason === episode.airedSeason;
});
const prefixedEpisodeNumber = this.generateEpisodeNumber(episode.airedEpisodeNumber, episodesInSeason.length);
return {
name: `${episode.id}`,
message: `E${prefixedEpisodeNumber}: ${episode.episodeName}`,
value: episode,
}
}
private async generateEpisodeNames(seriesDirectory: string, seriesDetails: Series): Promise<SeasonMapping> {
const folders = await this.getFolderNames(seriesDirectory);
const seasonRegex = /\d+/;
const seasonFolders = folders.map((folderName: string): FolderSeasonMatch => {
const folderSeasonNumber = folderName.match(seasonRegex);
if (folderSeasonNumber === null) {
return undefined;
}
return {
folderName: folderName,
season: parseInt(folderSeasonNumber[0]),
}
}).filter((folderSeasonInfo: FolderSeasonMatch): boolean => {
return folderSeasonInfo !== undefined;
});
const episodeMappings = await Promise.all(seasonFolders.map((folderSeasonInfo: FolderSeasonMatch): Promise<Array<ArrayPromptOption>> => {
const seasonFolder = path.join(seriesDirectory, folderSeasonInfo.folderName)
return this.generateEpisodeNamesForSeason(seasonFolder, folderSeasonInfo.season, seriesDetails);
}));
const result: SeasonMapping = {};
for (let i = 0; i < seasonFolders.length; i++) {
result[seasonFolders[i].season] = {
folderName: seasonFolders[i].folderName,
episodeMappings: episodeMappings[i],
}
}
return result;
}
private async generateEpisodeNamesForSeason(seasonFolder: string, season: number, seriesDetails: Series): Promise<Array<EpisodeMapping>> {
const episodesInSeason = seriesDetails.episodes.filter((episode: Episode) => {
return episode.airedSeason === season;
});
const filesInSeasonFolder = await this.getFileNames(seasonFolder);
return filesInSeasonFolder.map((fileName) => {
return this.generateEpisodeName(seriesDetails.seriesName, seasonFolder, season, fileName, episodesInSeason);
})
.filter((episodeMapping: EpisodeMapping) => {
return episodeMapping !== undefined;
})
.sort(this.sortEpisodeMappings)
}
private sortEpisodeMappings(episodeMapping1: EpisodeMapping, episodeMapping2: EpisodeMapping): number {
const episode1 = episodeMapping1.value.episode !== undefined
? episodeMapping1.value.episode.airedEpisodeNumber
: undefined;
const episode2 = episodeMapping2.value.episode !== undefined
? episodeMapping2.value.episode.airedEpisodeNumber
: undefined;
if (episode1 === episode2) {
return 0;
}
if (episode1 === undefined) {
return 1
}
if (episode2 === undefined) {
return -1;
}
return episode1 - episode2;
}
private generateEpisodeName(
seriesName: string,
seasonFolder: string,
seasonNumber: number,
fileName: string,
episodesInSeason: Array<Episode>,
forceEpisodeNumber?: number,
): EpisodeMapping {
const fileExtension = path.extname(fileName).toLowerCase();
const fileIsVideo = videoFileExtensions.includes(fileExtension);
if (!fileIsVideo) {
return this.unchangedEpisodeMapping(seasonFolder, seasonNumber, fileName);
}
let episodeNumber = forceEpisodeNumber;
if (episodeNumber === undefined) {
for (const {regex, numberStart} of episodeRegexes) {
const episodeNumberMatch = fileName.match(regex);
if (episodeNumberMatch !== null) {
episodeNumber = parseInt(episodeNumberMatch[0].substring(numberStart))
break;
}
}
}
if (episodeNumber === undefined) {
return this.unchangedEpisodeMapping(seasonFolder, seasonNumber, fileName);
}
const episode = episodesInSeason.find((episode: Episode) => {
return episode.airedEpisodeNumber === episodeNumber;
});
if (episode === undefined) {
return this.unchangedEpisodeMapping(seasonFolder, seasonNumber, fileName);
}
const prefixedEpisodeNumber = this.generateEpisodeNumber(episodeNumber, episodesInSeason.length);
const sanatizedName = this.generateEpisodeFileName(
fileExtension,
seriesName,
episode.airedSeason,
episode.episodeName,
episode.airedEpisodeNumber,
episodesInSeason.length
);
return {
name: sanatizedName,
message: `E${prefixedEpisodeNumber}: ${fileName} > ${sanatizedName}`,
value: {
originalPath: path.join(seasonFolder, fileName),
updatedPath: path.join(seasonFolder, sanatizedName),
episode: episode,
rename: fileName !== sanatizedName,
episodeNumber: prefixedEpisodeNumber,
seasonNumber: seasonNumber,
seasonFolder: seasonFolder,
}
}
}
private generateEpisodeNumber(episodeNumber: number, episodesInSeason: number) {
if (episodesInSeason < 100) {
return this.twoZero(episodeNumber);
}
return this.threeZero(episodeNumber);
}
private unchangedEpisodeMapping(seasonFolder: string, seasonNumber: number, fileName: string): EpisodeMapping {
return {
name: fileName,
message: `--- ${fileName}`,
value: {
originalPath: path.join(seasonFolder, fileName),
updatedPath: path.join(seasonFolder, fileName),
episode: undefined,
rename: false,
episodeNumber: undefined,
seasonNumber: seasonNumber,
seasonFolder: seasonFolder,
}
}
}
private generateEpisodeFileName(
fileExtension: string,
seriesName: string,
seasonNumber: number,
episodeName: string,
episodeNumber: number,
episodesInSeason: number
): string {
let newEpisodeName = `${seriesName}.S${this.twoZero(seasonNumber)}E${this.generateEpisodeNumber(episodeNumber, episodesInSeason)}.${episodeName}${fileExtension}`;
for (const {regex, replacement} of episodeReplaces) {
newEpisodeName = newEpisodeName.replace(regex, replacement);
}
return newEpisodeName;
}
private twoZero(input: number): string {
if (input < 10) {
return `0${input}`;
}
return `${input}`;
}
private threeZero(input: number): string {
if (input < 100) {
return `0${this.twoZero(input)}`;
}
return `${input}`;
}
}
|
radiokang/Rocket.Chat.Electron
|
src/app/PersistableValues.ts
|
import type { Certificate } from 'electron';
import { Download } from '../downloads/common';
import { Server } from '../servers/common';
import { WindowState } from '../ui/common';
type PersistableValues_0_0_0 = {
currentServerUrl: string;
currentView: 'add-new-server' | null;
doCheckForUpdatesOnStartup: boolean;
allowedJitsiServers: Record<string, boolean>;
externalProtocols: Record<string, boolean>;
isEachUpdatesSettingConfigurable: boolean;
isMenuBarEnabled: boolean;
isShowWindowOnUnreadChangedEnabled: boolean;
isSideBarEnabled: boolean;
isTrayIconEnabled: boolean;
isUpdatingEnabled: boolean;
rootWindowState: WindowState;
servers: Server[];
skippedUpdateVersion: string | null;
trustedCertificates: Record<Server['url'], Certificate['fingerprint']>;
};
type PersistableValues_3_1_0 = Omit<
PersistableValues_0_0_0,
'currentServerUrl' | 'currentView'
> & {
currentView?:
| Exclude<PersistableValues_0_0_0['currentView'], null>
| { url: string }
| 'downloads'
| 'settings';
downloads?: Record<Download['itemId'], Download>;
};
type PersistableValues_3_5_0 = PersistableValues_3_1_0 & {
isReportEnabled: boolean;
isFlashFrameEnabled: boolean;
isInternalVideoChatWindowEnabled: boolean;
};
export type PersistableValues = Pick<
PersistableValues_3_5_0,
keyof PersistableValues_3_5_0
>;
export const migrations = {
'>=3.1.0': (before: PersistableValues_0_0_0): PersistableValues_3_1_0 => {
const { currentServerUrl, ...rest } = before;
return {
...rest,
currentView: currentServerUrl
? { url: currentServerUrl }
: rest.currentView ?? 'add-new-server',
downloads: {},
};
},
'>=3.5.0': (before: PersistableValues_3_1_0): PersistableValues_3_5_0 => ({
...before,
isReportEnabled: true,
isInternalVideoChatWindowEnabled: true,
isFlashFrameEnabled:
process.platform === 'win32' || process.platform === 'darwin',
}),
};
|
KatagiriSo/rdhtmlresolve_js
|
src/rdhtmlresolve.ts
|
<reponame>KatagiriSo/rdhtmlresolve_js
import { utilFunc } from './util';
import * as fs from 'fs';
import * as path from 'path';
import * as readline from 'readline';
import * as argv from 'argv'
// Settng
interface Setting {
debugLog:boolean,
distFolderName:string,
srcFolderName:string,
basePath:string,
regPattern:RegExp
regFileNamePattern:RegExp
regCopyFileNamePattern:RegExp
}
const setting:Setting = {
debugLog:true,
distFolderName:"html",
srcFolderName:"html_src",
basePath:"./",
regPattern: /<!--\s*#include\s*virtual="(.*?)"\s*-->/,
regFileNamePattern:/.*\.(html|css|md)/,
regCopyFileNamePattern:/.*\.(png)/
}
argv.option({
name: 'clear',
short: 'c',
type: "string",
description: "clear",
example: "'rdhtmlresolve -c'"
})
const args = argv.run()
console.log(args);
if (args.options["clear"]) {
console.log("clear!");
}
|
KatagiriSo/rdhtmlresolve_js
|
src/hello.ts
|
import { utilFunc } from './util';
import * as fs from 'fs';
import * as path from 'path';
import * as readline from 'readline'
console.log("Hello, typescript!");
console.log(utilFunc("test"));
console.log(process.cwd());
console.log(JSON.stringify(process.env));
// read
const filePath:string = path.join(process.cwd(), "dist/util.js");
const text = fs.readFileSync(`${filePath}`, {encoding:"utf-8"});
console.log(text);
// write
fs.writeFileSync(path.join(process.cwd(), "dist/test.js"), "hello?");
// copy
fs.copyFileSync(path.join(process.cwd(), "dist/test.js"), path.join(process.cwd(), "dist/test2.js"));
// ls
const list = fs.readdirSync(path.join(process.cwd(), "/"), {withFileTypes:true});
console.log("readdirSync:"+list.map((f)=>f.name));
// readline and write
const readStream = fs.createReadStream(filePath, {encoding:"utf-8"});
const writeStream = fs.createWriteStream(path.join(process.cwd(), "dist/util2.js"));
const rwInterface = readline.createInterface({
input: readStream,
output: writeStream
});
rwInterface.on("line", (input) => {
writeStream.write(input+'\n');
});
rwInterface.on('close', () => {
console.log("end");
});
// reg
console.log('reg');
const results = "hogePoiPoge84754puge".match(/.*(Poi).*(\d{5}).*/);
if (results) {
for (const result of results) {
console.log("->"+result);
}
}
// ->hogePoiPoge84754puge
// ->Poi
// ->84754
|
KatagiriSo/rdhtmlresolve_js
|
src/util.ts
|
<gh_stars>0
export function utilFunc(txt:string):string {
return "["+txt+"]";
}
|
sharpfeel/vuex-cuer
|
src/example/store/example.store.ts
|
<reponame>sharpfeel/vuex-cuer<filename>src/example/store/example.store.ts
import * as Cuer from "vuex-cuer";
const state = {
/**
* some note.
*/
value: 1,
value2: 2,
value3: "3"
};
class Mutations extends Cuer.Mutations<ExampleStore> {
/**
* 加 `1`
*/
addOne() {
this.add(1);
}
/**
* 加 `v`
*/
add(v: number) {
this.state.value += v;
}
}
class Actions extends Cuer.Actions<ExampleStore> {
/**
* `1` 秒后加1
*/
delayAddOne() {
return this.delayAdd({
second: 1,
value: 1
});
}
/**
* `second` 秒后加 `value`
*/
delayAdd(data: { second: number; value: number }) {
return new Promise(resolve => {
setTimeout(() => {
this.store.commits.addOne();
resolve();
}, 1000 * data.second);
});
}
}
class Getters extends Cuer.Getters<ExampleStore> {
/**
* some note...
*/
get value() {
return state.value;
}
}
class ExampleStore extends Cuer.StoreCuer<
typeof state,
Mutations,
Actions,
Getters
> {
constructor() {
super(state, {
mutations: new Mutations(),
actions: new Actions(),
getters: new Getters()
});
}
}
const store = new ExampleStore();
export default store;
|
sharpfeel/vuex-cuer
|
tests/test.store.ts
|
<filename>tests/test.store.ts<gh_stars>1-10
import * as Cuer from "vuex-cuer";
const state = {
/**
* state.v
*/
v: 1
};
class Mutations extends Cuer.Mutations<TestStore> {
/**
* mutation1
*/
mutation1() {
this.state.v++; //操作state
}
/**
* mutation2
*/
mutation2(v: number) {
this.state.v += v; //操作state
this.mutation1(); //调用同级函数
this.store.commits.mutation1(); //通过commits调用同级函数
this.store.commit("mutation1"); //通过commit函数调用同级函数
}
}
class Actions extends Cuer.Actions<TestStore> {
/**
* action1
*/
action1() {
this.state.v++;
}
/**
* action2
*/
action2() {
this.state.v++;
this.action1();
this.store.commits.mutation2(1);
this.store.commit("mutation1");
this.store.dispatch("test2");
}
}
class TestStore extends Cuer.StoreCuer<typeof state, Mutations, Actions> {
constructor() {
super(state, {
mutations: new Mutations(),
actions: new Actions()
});
}
}
const store = new TestStore();
store.dispatchs.action1(); //通过store调用
export default store;
|
sharpfeel/vuex-cuer
|
src/mapping.ts
|
export type MappingKey<T, V extends Record<keyof V, keyof T>> = V | (keyof T)[];
type MapValueOf<T> = (key: keyof T) => () => T[keyof T];
type MapMethodOf<T> = (key: keyof T) => T[keyof T];
/**
* 对象的字符串数组映射
* @param valueOf
* @param arr
*/
export function mapValueOfKeys<T, V extends keyof T>(
arr: V[],
valueOf: MapValueOf<T>
) {
const ret = {} as { [K in V]: () => T[K] };
arr.forEach(key => {
ret[key] = valueOf(key) as () => T[Extract<V, keyof T>];
});
return ret;
}
/**
* 对象的json映射
* @param valueOf
* @param json
*/
export function mapValueOfJson<T, V extends Record<keyof V, keyof T>>(
json: V,
valueOf: MapValueOf<T>
) {
const ret = {} as { [K in keyof V]: () => T[V[K]] };
for (const k in json) {
ret[k] = valueOf(json[k]) as T[V[Extract<keyof V, string>]];
}
return ret;
}
/**
* 函数的数组映射
* @param valueOf
* @param arr
*/
export function mapMethodOfKeys<T, V extends keyof T>(
arr: V[],
valueOf: MapMethodOf<T>
) {
const ret = {} as { [K in V]: T[K] };
arr.forEach(key => {
ret[key] = valueOf(key) as T[Extract<V, keyof T>];
});
return ret;
}
/**
* 函数的json映射
* @param valueOf
* @param json
*/
export function mapMethodOfJson<T, V extends Record<keyof V, keyof T>>(
json: V,
valueOf: MapMethodOf<T>
) {
const ret = {} as { [K in keyof V]: T[V[K]] };
for (const k in json) {
ret[k] = valueOf(json[k]) as T[V[Extract<keyof V, string>]];
}
return ret;
}
|
sharpfeel/vuex-cuer
|
src/restrain.ts
|
<gh_stars>1-10
import { Params, KeyOf } from "./type";
import { Dispatch, Commit, Payload } from "vuex";
/**
* 约束 `commit`
*/
export interface CommitEx<M> extends Commit {
<K extends keyof M>(key: K, payload: Params<M[K]>[0]): unknown;
}
/**
* 约束 `dispatch`
*/
export interface DispatchEx<A> extends Dispatch {
<K extends keyof A>(key: K, payload: Params<A[K]>[0]): Promise<unknown>;
}
/**
* 约束 `subscribe` 和 `subscribeAction`
*/
export interface PayloadEx<M> extends Payload {
type: KeyOf<M>;
payload: unknown;
}
|
sharpfeel/vuex-cuer
|
src/type.ts
|
<gh_stars>1-10
/**
* 函数通用类型
*/
export type Method = (...args: unknown[]) => unknown;
/**
* 函数通用类型集合
*/
export type Methods = { [key: string]: Method };
export type KeyOf<T> = Extract<keyof T, string>;
/**
* 解析函数的参数
*/
export type Params<T> = Parameters<Extract<T, Method>>;
|
sharpfeel/vuex-cuer
|
src/index.ts
|
<filename>src/index.ts
import Vuex, {
ActionContext,
ActionTree,
MutationTree,
Store,
StoreOptions,
MutationPayload,
ActionPayload,
SubscribeActionOptions,
ActionSubscriber
} from "vuex";
import {
mapValueOfKeys,
mapValueOfJson,
mapMethodOfKeys,
mapMethodOfJson
} from "./mapping";
import { keys, cover, rewrite, bindStore, bindState } from "./util";
import { PayloadEx, CommitEx, DispatchEx } from "./restrain";
import Vue from "vue";
Vue.use(Vuex);
export interface IState<S = unknown> {
state: S;
}
export abstract class ICuer<T extends IState = IState> {
protected readonly state!: T["state"];
protected readonly store!: T;
}
/**
* commit 方法集合类
* @example //示例:
* class ExampleMutations extends Mutations<ExampleStore>{
- test(){
- this.state.xxx //访问 state
- this.store.getters.xxx //访问 getter
- this.xxx //调用当前类的 commit
- this.store.commit("xxx") //调用 commit
- this.store.commits.xxx //调用 commit
- }
* }
*/
export class Mutations<T extends IState> extends ICuer<T> {
//[key: string]: ((payload?: any) => unknown) | T | T["state"];
}
/**
* dispatch 函数集合类
* @example //示例:
* class ExampleActions extends Actions<ExampleStore>{
- test(){
- this.state.xxx //访问 state
- this.store.getters.xxx //访问 getter
- this.xxx //调用当前类的 dispatch
- this.store.commit("xxx", payload?) //调用 commit
- this.store.commits.xxx(payload?) //调用 commit
- this.store.dispatch("xxx", payload?) //调用 dispatch
- this.store.dispatchs.xxx(payload?) //调用 dispatchs
- }
* }
*/
export class Actions<T extends IState> extends ICuer<T> {
//[key: string]: ((payload?: any) => unknown) | T | T["state"];
}
/**
* dispatch 函数集合类
* @example //示例:
* class ExampleGetters extends Getters<ExampleStore>{
- get test() {
- this.state.xxx //访问 state
- this.getters.xxx //访问 getter
- this.xxx //访问当前类的 getter
- return xxx;
- }
* }
*/
export class Getters<T extends IState> extends ICuer<T> {
//[key: string]: (() => unknown) | T | T["state"];
}
/**
* todo:registerModule
* todo:unregisterModule
*/
/**
* store
* @example //示例:
* class ExampleStore extends StoreCuer<typeof state, Mutations, Actions, Getters>{
- constructor() {
- super(state, {
- mutations: new ExampleMutations(),
- actions: new ExampleActions(),
- getters: new ExampleGetters()
- });
- }
* }
*
*
* @example //使用:
* const store = new ExampleStore();
*
* store.state.xxx //访问 state
* store.getters.xxx //访问 getter
* store.xxx //访问 Store 的函数
* store.commit("xxx", payload?) //调用 (优化约束,以强化提示)
* store.commits.xxx(payload?) //调用 commit
* store.dispatch("xxx", payload?) //调用 (优化约束,以强化提示)
* store.dispatchs.xxx(payload?) //调用 dispatch
* store.subscribe(fn) // (优化约束,以强化提示)
* store.subscribeAction(fn) // (优化约束,以强化提示)
* store.mapState({...}) // 映射 state
* store.mapStateOfKeys(...) // 映射 state
* store.mapGetters({...}) // 映射 getters
* store.mapGettersOfKeys(...) // 映射 getters
* store.mapActions({...}) // 映射 actions
* store.mapActionsOfKeys(...) // 映射 actions
* store.mapMutations({...}) // 映射 mutations
* store.mapMutationsOfKeys(...) // 映射 mutations
*/
export class StoreCuer<
S,
M extends ICuer = ICuer,
A extends ICuer = ICuer,
G extends ICuer = ICuer
> extends Store<S> {
readonly commits!: M;
readonly dispatchs!: A;
readonly getters!: G;
commit!: CommitEx<M>;
dispatch!: DispatchEx<A>;
constructor(
state: S,
options?: {
/**
* 继承 Mutations 的类的实例
*/
mutations?: M;
/**
* 继承 Actions 的类的实例
*/
actions?: A;
/**
* 继承 Getters 的类的实例
*/
getters?: G;
/**
* StoreOptions.plugins
*/
plugins?: StoreOptions<S>["plugins"];
/**
* StoreOptions.strict
*/
strict?: StoreOptions<S>["strict"];
}
) {
const mutations: MutationTree<S> = {};
const commits = options?.mutations;
const commitKeys = keys(commits);
cover(commits, commitKeys, (key, method) => {
mutations[key] = (state: S, payload?: unknown) => {
method.call(bindState(this.commits, state), payload);
};
});
const actions: ActionTree<S, S> = {};
const dispatchs = options?.actions;
const dispatchKeys = keys(dispatchs);
cover(dispatchs, dispatchKeys, (key, method) => {
actions[key] = (injectee: ActionContext<S, S>, payload?: unknown) =>
method.call(bindState(this.dispatchs, injectee.state), payload);
});
super({
state: state,
mutations,
actions,
//getters,
plugins: options?.plugins,
strict: options?.strict
});
console.log("[vuex-cuer]", {
state: state,
mutations: commitKeys,
actions: dispatchKeys
});
rewrite(commits, commitKeys, key => {
return (payload?: unknown) => this.commit(key, payload);
});
if (commits) {
this.commits = bindStore(commits, this);
}
rewrite(dispatchs, dispatchKeys, key => {
return (payload?: unknown) => this.dispatch(key, payload);
});
if (dispatchs) {
this.dispatchs = bindStore(dispatchs, this);
}
const getters = options?.getters;
if (getters) {
this.getters = bindStore(getters, this);
}
}
subscribe<P extends MutationPayload = PayloadEx<M>>(
fn: ActionSubscriber<P, S>
) {
return super.subscribe(fn);
}
subscribeAction<P extends ActionPayload = PayloadEx<A>>(
fn: SubscribeActionOptions<P, S>
) {
return super.subscribeAction(fn);
}
/**
* 映射 `state`
* @param keys
*/
mapState<V extends Record<keyof V, keyof S>>(keys: V) {
return mapValueOfJson<S, V>(keys, k => () => this.state[k]);
}
/**
* 映射 `state`
* @param keys
*/
mapStateOfKeys<V extends keyof S>(...keys: V[]) {
return mapValueOfKeys<S, V>(keys, k => () => this.state[k]);
}
/**
* 映射 `getters`
* @param keys
*/
mapGetters<V extends Record<keyof V, keyof G>>(keys: V) {
return mapValueOfJson<G, V>(keys, k => () => this.getters[k]);
}
/**
* 映射 `getters`
* @param keys
*/
mapGettersOfKeys<V extends keyof G>(...keys: V[]) {
return mapValueOfKeys<G, V>(keys, key => () => this.getters[key]);
}
/**
* 映射 `dispatchs`
* @param keys
*/
mapActions<V extends Record<keyof V, keyof A>>(keys: V) {
return mapMethodOfJson<A, V>(keys, k => this.dispatchs[k]);
}
/**
* 映射 `dispatchs`
* @param keys
*/
mapActionsOfKeys<V extends keyof A>(...keys: V[]) {
return mapMethodOfKeys<A, V>(keys, k => this.dispatchs[k]);
}
/**
* 映射 `commits`
* @param keys
*/
mapMutations<V extends Record<keyof V, keyof M>>(keys: V) {
return mapMethodOfJson<M, V>(keys, k => this.commits[k]);
}
/**
* 映射 `commits`
* @param keys
*/
mapMutationsOfKeys<V extends keyof M>(...keys: V[]) {
return mapMethodOfKeys<M, V>(keys, key => this.commits[key]);
}
}
|
sharpfeel/vuex-cuer
|
src/example/main.ts
|
import Vue from "vue";
import App from "./App.vue";
import exampleStore from "@/store/example.store.ts";
Vue.config.productionTip = false;
Vue.prototype.$exampleStore = exampleStore;
new Vue({
render: h => h(App)
}).$mount("#app");
declare module "vue/types/vue" {
interface Vue {
$exampleStore: typeof exampleStore;
}
}
|
sharpfeel/vuex-cuer
|
src/util.ts
|
<reponame>sharpfeel/vuex-cuer<filename>src/util.ts
import { KeyOf, Method, Methods } from "./type";
/**
* 获取`ICuer`对象上的原链函数
* @param obj
*/
export function keys<T>(obj?: T) {
if (obj != null) {
return Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(
v => v != "constructor"
) as KeyOf<T>[];
}
return [];
}
/**
* 覆盖 ICuer 对象,转换成 store 属性的类型
* @param obj
* @param keys
*/
export function cover<T>(
obj: T | undefined,
keys: KeyOf<T>[],
replace: (key: KeyOf<T>, m: Method) => void
) {
if (obj != null) {
const ms: Methods = {};
keys.forEach(key => {
ms[key] = (obj[key] as unknown) as Method;
if (ms[key]) {
replace(key, ms[key]);
}
});
}
}
/**
*
* @param obj
* @param key
* @param v
*/
export function assign<T, K extends string, V>(obj: T, key: K, v: V) {
((obj as unknown) as { [P in K]: V })[key] = v;
return obj;
}
/**
* 绑定state
* @param obj
* @param cuer
*/
export function bindState<T, V>(obj: T, state: V) {
return assign(obj, "state", state);
}
/**
* 绑定store
* @param cuer
* @param obj
*/
export function bindStore<T, V>(obj: T, cuer: V) {
return assign(obj, "store", cuer);
}
/**
* 重写 对象 属性
*/
export function rewrite<T>(
obj: T | undefined,
keys: KeyOf<T>[],
write: (key: KeyOf<T>) => unknown
) {
if (obj != null) {
keys.forEach(key => {
obj[key] = write(key) as T[KeyOf<T>];
});
}
}
|
abhija77/book_store_back
|
src/indexation.ts
|
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class Indexation {
@PrimaryGeneratedColumn()
id: number;
@Column()
token: string;
@Column({
type: "longtext"
})
index: string;
}
|
abhija77/book_store_back
|
src/app.controller.ts
|
import { Controller, Get, HttpException, HttpService, Param, Query, Response } from '@nestjs/common';
import { AppService } from './app.service';
import axios, { Axios } from "axios";
import BookInterface from './model/book.model';
import { Any } from 'typeorm';
import { IncomingMessage, ServerResponse } from 'http';
import { url } from 'inspector';
const HOST_GUTENBERG = "https://gutendex.com";
@Controller()
export class AppController {
constructor(private readonly appService: AppService, private http: HttpService) { }
@Get("/books")
async getBooks(@Query("topic") topic: string, @Query("lang") lang: string, @Query("limit") limit: number, @Query("search") search: string): Promise<any> {
const askTopic = topic != null;
const askLang = lang != null;
const askSearch = search != null;
let url = `${HOST_GUTENBERG}/books`;
if (askLang && askTopic)
url += `?topic=${topic}&languages=${lang}`;
else if (askLang)
url += `?languages=${lang}`;
else if (askTopic)
url += `?topic=${topic}`;
let response: any[] = await axios.get(url).then(value => value.data.results);
if(askSearch){
const resp = await this.appService.findIndexationOne(search);
if(resp){
const idBooks = JSON.parse(resp.index).map(val => val.book);
response = response.filter(book => idBooks.indexOf(book.id) > -1);
} else {
console.log("NOT");
}
}
if (limit && limit > 1)
response = response.slice(0, limit - 1);
return response;
}
@Get("/book/detail/:id")
async getBookDetail(@Param("id") id: number) {
let response = await axios.get(`${HOST_GUTENBERG}/books/${id}`).then(value => value.data);
return response;
}
@Get("/addBooks")
async addBooks() {
let url = `${HOST_GUTENBERG}/books`;
return this.appService.createMany(url);
}
// @Get("/jaccard/:word")
// async jaccard(@Param("word") word: string) {
// let v1 = {
// "le": 1,
// "moteur":
// 1,
// "de":
// 2,
// "recherche":
// 2,
// "ideal":
// 1,
// "doit":
// 1,
// "comprendre":
// 1,
// "exactement":
// 2,
// "l":
// 1,
// "objet":
// 1,
// "la":
// 1,
// "pour":
// 1,
// "fournir":
// 1,
// "les":
// 1,
// "informations":
// 1,
// "demandees":
// 1
// }
// let v2 = {
// "le":
// 2
// }
// // return this.appService.algojaccard(v1, v2);
// return this.appService.algojaccard(word)
// }
@Get("indexationJaccard")
async indexationJaccard() {
return this.appService.indexationJaccard();
}
@Get("/indexation")
async indexation() {
return this.appService.indexation();
}
}
|
abhija77/book_store_back
|
src/app.service.ts
|
<reponame>abhija77/book_store_back
/* eslint-disable prettier/prettier */
import { HttpService, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import axios, { Axios, AxiosResponse } from 'axios';
import { Observable, timeout } from 'rxjs';
import { Connection, getConnection, Repository } from 'typeorm';
import { Book } from './book';
import { Indexation } from './indexation';
import { IndexationJaccard } from './indexationJaccard';
import BookWords from './model/book-words.model';
import BookInterface from './model/book.model';
const wordsNotAllowed = [
"de",
"le",
"la",
"les",
"du",
"des",
"un",
"une",
".",
",",
"a",
"the",
"an",
"to",
"if",
"we",
"on",
"at",
"us",
"our",
"of",
"or",
"and",
"by",
"this",
"is",
"are",
"for",
"in",
"you",
"it",
"tm",
"re"
]
@Injectable()
export class AppService {
constructor(private http: HttpService, private connection: Connection, @InjectRepository(Book)
private booksRepository: Repository<BookInterface>, @InjectRepository(Indexation) private indexationRepo: Repository<Indexation>, @InjectRepository(IndexationJaccard) private indexationJaccardRepo: Repository<IndexationJaccard>) {
}
createBook(): any {
return null;
}
tokenize(text) {
const allWords: string[] = text.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/\r\n]/gi, " ")
.split(" ")
.filter(word => word != '')
.map(word => word.toLowerCase());
const wordsF = allWords
.filter(val => {
const value = val.toLowerCase();
return !wordsNotAllowed.find(val => val == value);
}
);
return { size: allWords.length, words: wordsF };
}
resolveText(text: string) {
const words: BookWords[] = [];
const list = this.tokenize(text);
let wordMostPresent: BookWords = null;
let wordNumber: number = list.size;
list.words.forEach((value: string) => {
const word: BookWords[] = words.filter((book: BookWords) => book.token.toLowerCase() === value.toLowerCase() && book.token.length == value.length);
let obj = word.length > 0 ?
word[0]
: {
token: value.toLowerCase(),
occurence: 0,
ratio: 0
}
obj.occurence++;
if (word.length == 0) {
words.push(obj);
}
});
words.forEach((word: BookWords) => {
if (wordMostPresent == null || word.occurence > wordMostPresent.occurence) {
wordMostPresent = word
}
word.ratio = word.occurence / wordNumber;
});
return words;
}
async createMany(url: any) {
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
const res = await axios.get(url).then(value => value.data);
let results = res.results;
results.forEach(async element => {
let book: Book = new Book()
book.url_content = element.formats["text/plain; charset=utf-8"];
if (book.url_content != null && book.url_content.includes("txt")) {
book.id_book = element.id
try {
await queryRunner.manager.save(book)
await queryRunner.commitTransaction();
}
catch (err) {
await queryRunner.rollbackTransaction();
console.log("erreur : " + err)
return err;
}
}
});
}
findAll(): Promise<BookInterface[]> {
return this.booksRepository.find();
}
async getTokens(url) {
const res = await axios.get(url)
.then(value => { console.log(value.status); return value.data; })
.catch(error => { console.log("erreur : " + error) })
let resResolved;
if (res) {
resResolved = this.resolveText(res);
}
return resResolved;
}
async algojaccard(v1, v2) {
// /*Nombre d’éléments contenus dans les deux vecteurs (intersection)*/
// let i: number = 0;
// /*Nombre d’éléments total des deux vecteurs (union)*/
// let u: number = 0;
// /*On parcourt le premier vecteur d’occurrence*/
// for (const [w, c] of (Object.entries(v1) as [string, number][])) {
// /*On ajoute le nombre d’occurrence du mot à l'union*/
// u = u + c;
// /*Si le mot est présent dans le second vecteur on ajoute le nombre d’occurrence à l'intersection*/
// if (v2[w] != null) {
// i += c + v2[w];
// }
// }
// /*On parcourt le second vecteur d’occurrence pour ajouter les occurrences à l'union*/
// for (const [w, c] of (Object.entries(v1) as [string, number][])) {
// u += c;
// }
// /*On retourne l'Indice de Jaccard*/
// return i / u;
// }
}
//InProgress
async getIndexTable() {
let indexTable = {};
let books = await this.findAll();
for (const book of books) {
let listToken;
console.log(book);
try {
listToken = await this.getTokens(book.url_content);
} catch (e) {
console.error(e);
}
console.log("running");
if (listToken != null && listToken != []) {
listToken.forEach(tokens => {
let objWord;
if (indexTable[tokens.token]) {
objWord = { "book": book.id_book, "occurences": tokens.occurence, "ratio": tokens.ratio };
}
else {
objWord = { "book": book.id_book, "occurences": tokens.occurence, "ratio": tokens.ratio };
indexTable[tokens.token] = [];
}
indexTable[tokens.token].push(objWord)
});
}
}
Object.keys(indexTable).forEach(async tok => {
const index = new Indexation();
index.token = tok;
index.index = JSON.stringify(indexTable[tok]);
await this.indexationRepo.save(index);
})
console.log(indexTable);
return indexTable;
}
async indexation() {
console.log("START INDEXATION");
return await this.getIndexTable();
}
async indexationJaccard() {
//récupérer liste des livres
let listBooks: BookInterface[] = await this.findAll();
let listIndexationJaccard = await this.indexationJaccardRepo.find();
//récupérer tokens pour chaque livre
if listIndexationJaccard == []) {
let books = []
for (const book of listBooks) {
let tokensBook = await this.getTokens(book.url_content);
books.push({ "id": book.id_book, "token": tokensBook });
}
const indexationJaccard = new IndexationJaccard();
indexationJaccard.indexJaccard = JSON.stringify(books);
await this.indexationJaccardRepo.save(indexationJaccard)
}
console.log(listIndexationJaccard);
//créer table indexation jaccard
//comparer 2 à 2 livre selon jaccard
//stocker resultats sous forme: une ligne = nom du livre : [nom du livre=>distance,...]
//stocker base de données la table d'indexation selon le modéle : une ligne = id,id_book,nom du livre,distances
}
async findIndexationOne(word) {
return this.indexationRepo.findOne({
where: {
token: word
}
})
}
}
|
abhija77/book_store_back
|
src/model/book-words.model.ts
|
export default interface BookWords {
token: string;
occurence: number;
ratio: number;
}
|
abhija77/book_store_back
|
src/indexationJaccard.ts
|
<filename>src/indexationJaccard.ts
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class IndexationJaccard {
@PrimaryGeneratedColumn()
id: number;
@Column({
type: "longtext"
})
indexJaccard: string;
}
|
abhija77/book_store_back
|
src/book.ts
|
import internal from "stream";
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class Book {
@PrimaryGeneratedColumn()
id: number;
@Column()
id_book: number;
@Column({
type: "mediumtext",
nullable: true
})
url_content: string;
}
|
abhija77/book_store_back
|
src/model/book.model.ts
|
<filename>src/model/book.model.ts
export default interface BookInterface {
id: number;
id_book: number;
tokenList: string;
url_content: string;
}
|
abhija77/book_store_back
|
src/app.module.ts
|
import { HttpModule, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { Book } from './book';
import { Indexation } from './indexation';
// import { InvertedToken } from './inverted-token';
@Module({
imports: [TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'phpmyadmin',
password: '<PASSWORD>',
database: 'book_store',
entities: [Book, Indexation],
synchronize: true
}),
HttpModule,
TypeOrmModule.forFeature([Book,Indexation]),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
|
deislabs/wasm-linker-js
|
src/linker.ts
|
<gh_stars>10-100
import * as asyncify from "asyncify-wasm";
import { Store } from "./store";
/**
* A JavaScript object that can be used to link WebAssembly instances.
*
* This is a helper class to be used when instantiating WebAssembly
* modules with imports. It can be used to define individual imports
* (like functions, or memories), or link entire modules when
* instantiating modules that depend on other modules.
*/
export class Linker {
public store: Store;
public useAsyncify: boolean;
constructor(useAsyncify: boolean = false, store: Store = new Store()) {
this.useAsyncify = useAsyncify;
this.store = store;
}
/**
* Adds a new WebAssembly.ImportValue to the imports cache.
*
* Example:
* ```js
const { Linker } = require("@deislabs/wasm-linker-js");
const { parseText } = require("binaryen");
const assert = require("assert");
(async () => {
const usingAdd = `
(module
(import "calculator" "add" (func $calc_add (param i32 i32) (result i32))
(export "add" (func $add))
(func $add (param i32) (param i32) (result i32)
(return
(call $calc_add
(local.get 0)
(local.get 1)
)
)
)
)
`;
var linker = new Linker();
// the "usingAdd" module above imports calculator.add
// we define it and provide a JS implementation, then
// instantiate it.
linker.define("calculator", "add", (a, b) => a + b);
var calc = await linker.instantiate(
parseText(usingAdd).emitBinary());
assert.equal(await calc.instance.exports.add(1, 2), 3)
* ```
*/
define(module: string, name: string, item: WebAssembly.ImportValue): void {
return this.store.addImport(module, name, item);
}
/**
* Instantiate and add a module to the linker's instance cache.
*
* Example:
* ```js
const { Linker } = require("@deislabs/wasm-linker-js");
const { parseText } = require("binaryen");
const assert = require("assert");
(async () => {
const usingAdd = `
(module
(import "calculator" "add" (func $calc_add (param i32 i32) (result i32)))
(export "add" (func $add))
(func $add (param i32) (param i32) (result i32)
(return
(call $calc_add
(local.get 0)
(local.get 1)
)
)
)
)
`;
const add = `
(module
(memory 1 1)
(export "memory" (memory 0))
(export "add" (func $add))
(func $add (param i32) (param i32) (result i32)
(return
(i32.add
(local.get 0)
(local.get 1)
)
)
)
)
`;
var linker = new Linker();
// the "usingAdd" module above imports calculator.add
// we link a module that we know exports the functionality
// required, then instantiate the module that uses it.
await linker.module(
"calculator",
new WebAssembly.Module(parseText(add).emitBinary())
);
var calc = await linker.instantiate(parseText(add).emitBinary());
assert.equal(await calc.instance.exports.add(1, 41), 42);
})();
*```
*/
async module(name: string, module: WebAssembly.Module): Promise<void> {
return this.store.addInstance(name, await this.instantiate(module));
}
/**
* Instantiate a module using `instantiateStreaming` and add its exports
* to the linker's cache.
* Not available in Safari and Node.js.
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming
* Example:
* ```js
var linker = new Linker();
await linker.moduleStreaming("calculator", fetch("calculator.wasm"));
var mod = await linker.instantiateStreaming(
fetch("using_calculator.wasm")
);
console.log(mod.instance.exports.multiply(3, 4));
```
*/
async moduleStreaming(name: string, source: Response): Promise<void> {
return this.store.addInstance(
name,
await (await this.instantiateStreaming(source)).instance
);
}
/**
* Add an instance to the linker's instance cache.
* Example:
* ```js
const { Linker } = require("@deislabs/wasm-linker-js");
const { parseText } = require("binaryen");
const assert = require("assert");
(async () => {
const usingAdd = `
(module
(import "calculator" "add" (func $calc_add (param i32 i32) (result i32)))
(export "add" (func $add))
(func $add (param i32) (param i32) (result i32)
(return
(call $calc_add
(local.get 0)
(local.get 1)
)
)
)
)
`;
const add = `
(module
(memory 1 1)
(export "memory" (memory 0))
(export "add" (func $add))
(func $add (param i32) (param i32) (result i32)
(return
(i32.add
(local.get 0)
(local.get 1)
)
)
)
)
`;
var linker = new Linker();
var depsInstance = await WebAssembly.instantiate(
new WebAssembly.Module(parseText(add).emitBinary())
);
linker.instance("calculator", depsInstance);
var calc = await linker.instantiate(parseText(usingAdd).emitBinary());
assert.equal(await calc.instance.exports.add(1, 41), 42);
})();
*```
*/
instance(name: string, instance: WebAssembly.Instance): void {
return this.store.addInstance(name, instance);
}
/**
* Alias all exports from one module as another.
* Example:
* ```js
const { Linker } = require("@deislabs/wasm-linker-js");
const { parseText } = require("binaryen");
const assert = require("assert");
(async () => {
const add = `
(module
(memory 1 1)
(export "memory" (memory 0))
(export "add" (func $add))
(func $add (param i32) (param i32) (result i32)
(return
(i32.add
(local.get 0)
(local.get 1)
)
)
)
)
`;
const usingAddWithAlias = `
(module
(import "calculator1" "add" (func $calc_add1 (param i32 i32) (result i32)))
(import "calculator2" "add" (func $calc_add2 (param i32 i32) (result i32)))
(memory 1 1)
(export "memory" (memory 0))
(export "add1" (func $add1))
(export "add2" (func $add2))
(func $add1 (param i32) (param i32) (result i32)
(return
(call $calc_add1
(local.get 0)
(local.get 1)
)
)
)
(func $add2 (param i32) (param i32) (result i32)
(return
(call $calc_add2
(local.get 0)
(local.get 1)
)
)
)
)
`;
var linker = new Linker();
// we first define the module that implements `add` as `calculator1`
await linker.module(
"calculator1",
new WebAssembly.Module(parseText(add).emitBinary())
);
// we alias `calculator1` as `calculator2`
linker.alias("calculator1", "calculator2");
var calc = await linker.instantiate(
parseText(usingAddWithAlias).emitBinary()
);
assert.equal(await calc.instance.exports.add1(1, 99), 100);
assert.equal(await calc.instance.exports.add2(2, 99), 101);
})();
*```
*/
alias(module: string, asModule: string): void {
return this.store.aliasModule(module, asModule);
}
/**
* Instantiate a WebAssembly module.
*
* This function iterates through the module's imports and performs
* name based resolution in trying to satisfy all module imports.
* First, it searches
*
* This function iterates through the module's imports and does a
* name based import resolution based on the exported items of the
* modules in the store's instance cache, and passes the store's
* imports cache when actually instantiates the module.
*/
async instantiate(module: WebAssembly.Module): Promise<WebAssembly.Instance> {
return this.useAsyncify
? await asyncify.instantiate(module, this.store.imports)
: await WebAssembly.instantiate(module, this.store.imports);
}
/**
* Compile and instantiate a WebAssembly module directly from a streamed
* underlying source.
* Not available in Safari and Node.js.
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming
*
* Example:
* ```js
var linker = new Linker();
var mod = await linker.instantiateStreaming(
fetch("calculator.wasm")
);
console.log(mod.instance.exports.multiply(3, 4));
```
*/
async instantiateStreaming(
source: Response
): Promise<WebAssembly.WebAssemblyInstantiatedSource> {
return this.useAsyncify
? await asyncify.instantiateStreaming(source, this.store.imports)
: await WebAssembly.instantiateStreaming(source, this.store.imports);
}
/**
* Add an imports object to the linker.
* Example:
* ```js
const { Linker } = require("@deislabs/wasm-linker-js");
const { parseText } = require("binaryen");
const assert = require("assert");
(async () => {
const usingAdd = `
(module
(import "calculator" "add" (func $calc_add (param i32 i32) (result i32))
(export "add" (func $add))
(func $add (param i32) (param i32) (result i32)
(return
(call $calc_add
(local.get 0)
(local.get 1)
)
)
)
)
`;
var linker = new Linker();
var importObject = {
calculator: {
add: (a: number, b: number) => a + b,
},
};
linker.imports(importObject);
var calc = await linker.instantiate(
parseText(usingAdd).emitBinary());
assert.equal(await calc.instance.exports.add(1, 2), 3)
* ```
*/
imports(importObject: any): void {
// This ensures that import objects defined using the
// current convention can be directly reused when
// using this linker.
//
// The signature is not ideal, and in the future we
// should explore making `importObject` a typed
// object.
return this.store.addImportObject(importObject);
}
// This is currently unused.
// If we were to use this type of resolution, we would always
// have to make an explicit choice between first adding imports
// defined by the user versus those coming from modules (imports
// not manually defined by a user, but automatically resolved by name).
//
// See the implementation of Store.addInstance, but in short,
// in the case of identical import names, the one defined last
// will be used, regardless of whether it was explicitly
// defined using `defined` or with `module`.
//
// Leaving this function here for completeness.
// @ts-ignore
private resolveImports(module: WebAssembly.Module): void {
let imports = WebAssembly.Module.imports(module);
imports.forEach((im) => {
if (
this.store.instances[im.module] !== undefined &&
this.store.instances[im.module].exports[im.name] !== undefined
) {
this.define(
im.module,
im.name,
this.store.instances[im.module].exports[im.name]
);
}
});
}
}
|
nurseiit/bifrost
|
src/elementHandler.ts
|
export default class MyElementHandler {
element(element: any) {
switch (element.tagName) {
case 'title':
element.setInnerContent('Bifrost');
break;
case 'h1':
element.setInnerContent('Welcome to Asgard!');
break;
case 'p':
element.setInnerContent(
'Asgard is not a place. It never was. This could be Asgard. Asgard is where our people stand.'
);
break;
case 'a':
element.setInnerContent('Check out my website!');
element.setAttribute('href', 'https://devnur.me');
break;
}
}
}
|
nurseiit/bifrost
|
src/index.ts
|
<gh_stars>0
import MyElementHandler from './elementHandler';
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
const getRandomVariantIndex = (): number => Math.floor(Math.random() * 2);
const fetchRewrite = async (url: string) => {
const res = await fetch(url);
return new HTMLRewriter().on('*', new MyElementHandler()).transform(res);
};
async function handleRequest(request: Request): Promise<Response> {
// fetch variants
const resp = await fetch(
'https://cfw-takehome.developers.workers.dev/api/variants'
);
const { variants } = await resp.json();
const cookie = request.headers.get('cookie');
if (cookie && cookie.includes('bifrost-AB=earth')) {
/* cookie matches for variant 0 (earth) */
return await fetchRewrite(variants[0]);
} else if (cookie && cookie.includes('bifrost-AB=asgard')) {
/* cookie matches for variant 1 (asgard) */
return await fetchRewrite(variants[1]);
} else {
/* no cookie matches */
// select one of two variants randomly (uniformly)
const index = getRandomVariantIndex();
// name cookie group value
const group = index === 0 ? 'earth' : 'asgard';
// fetch selected variant
const response = await fetchRewrite(variants[index]);
// clone response to modify later
const responseClone = new Response(response.body, response);
// add the cookie created
responseClone.headers.append('Set-Cookie', `bifrost-AB=${group}; path=/`);
return responseClone;
}
}
|
ymatzki/eslint-plugin
|
lib/configs/recommended.ts
|
export = {
extends: require.resolve("./base"),
rules: {
"@hrbrain/use-name-space-import": "warn",
"@hrbrain/no-use-function-component-type-without-children": "warn",
"@hrbrain/no-multiple-named-imports": "warn",
},
};
|
ymatzki/eslint-plugin
|
tools/update.ts
|
<reponame>ymatzki/eslint-plugin
import { updateRulesDocs } from "./update-rules-docs";
import { updateRulesList } from "./update-rules-list";
(async () => {
await updateRulesDocs();
await updateRulesList();
})();
|
ymatzki/eslint-plugin
|
lib/rules/no-use-function-component-type-without-children.ts
|
<filename>lib/rules/no-use-function-component-type-without-children.ts<gh_stars>1-10
// ------------------------------------------------------------------------------
// Imports
// ------------------------------------------------------------------------------
import { createRule, isFunctionComponentType } from "../util";
import {
AST_NODE_TYPES,
TSESTree,
} from "@typescript-eslint/experimental-utils";
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
const getFunctionComponentTypeName = (node: TSESTree.VariableDeclarator) => {
let typeName: string | undefined;
if (
node.id?.typeAnnotation?.typeAnnotation.type ===
AST_NODE_TYPES.TSTypeReference
) {
if (
node.id?.typeAnnotation?.typeAnnotation.typeName.type ===
AST_NODE_TYPES.TSQualifiedName &&
node.id?.typeAnnotation?.typeAnnotation.typeName.left.type ===
AST_NODE_TYPES.Identifier &&
node.id?.typeAnnotation?.typeAnnotation.typeName.right.type ===
AST_NODE_TYPES.Identifier
) {
/**
* Note: Expect:
* - LeftType.RightType
*/
typeName = `${node.id?.typeAnnotation?.typeAnnotation.typeName.left.name}.${node.id?.typeAnnotation?.typeAnnotation.typeName.right.name}`;
} else if (
node.id?.typeAnnotation?.typeAnnotation.typeName.type ===
AST_NODE_TYPES.Identifier
) {
/**
* Note: Expect:
* - TypeName
*/
typeName = node.id?.typeAnnotation?.typeAnnotation.typeName.name;
}
} else {
typeName = undefined;
}
return { typeName };
};
// ------------------------------------------------------------------------------
// Settings of createRule
// ------------------------------------------------------------------------------
const defaultOptions: [] = [];
type MessageIds = "noUseFunctionComponentTypeWithoutChildren";
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
export = createRule<[], MessageIds>({
name: "no-use-function-component-type-without-children",
meta: {
docs: {
description: "Don't use Function Component type without props.children",
category: "Best Practices",
recommended: false,
},
type: "suggestion",
messages: {
noUseFunctionComponentTypeWithoutChildren:
"Should not use '{{ typeName }}' when components doesn't use props.children",
},
schema: [],
},
defaultOptions,
create(context) {
return {
'VariableDeclarator:not(:has(Literal[value="children"])):not(:has(Identifier[name="children"]))'(
node: TSESTree.VariableDeclarator
) {
const { typeName } = getFunctionComponentTypeName(node);
if (
node.id?.typeAnnotation?.typeAnnotation.type ===
AST_NODE_TYPES.TSTypeReference &&
typeName &&
isFunctionComponentType(typeName)
) {
context.report({
node: node.id.typeAnnotation?.typeAnnotation.typeName,
loc: node.id.typeAnnotation?.typeAnnotation.typeName.loc,
messageId: "noUseFunctionComponentTypeWithoutChildren",
data: {
typeName,
},
});
}
},
};
},
});
|
ymatzki/eslint-plugin
|
tests/lib/rules/prefer-parameter-instance.spec.ts
|
<filename>tests/lib/rules/prefer-parameter-instance.spec.ts
import { RuleTester } from "../../util";
import rule from "../../../lib/rules/prefer-parameter-instance";
const tester = new RuleTester({
parser: "@typescript-eslint/parser",
parserOptions: {
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
});
tester.run("prefer-parameter-instance", rule, {
valid: [
{
code: `
const user: User<UserProps> = {
age: 'name',
info: {
age: 20
}
}
`,
options: [
{
onlyReference: true,
},
],
},
{
code: `
const user: User<{age: number}> = {
name: 'name',
info: {
age: 20
}
}
`,
options: [
{
onlyReference: false,
},
],
},
{
code: `
const user: User<string> = {
name: 'name',
info: {
age: 20
}
}
`,
options: [
{
onlyReference: true,
allowKeywords: true,
},
],
},
],
invalid: [
{
code: `
const user: User<{age: number}> = {
name: 'name',
info: {
age: 20
}
}
`,
options: [
{
onlyReference: true,
},
],
errors: [{ messageId: "onlyReference" }],
},
{
code: `
const user: User<{age: number}> = {
name: 'name',
info: {
age: 20
}
}
`,
options: [
{
onlyReference: true,
allowKeywords: true,
},
],
errors: [{ messageId: "onlyReference" }],
},
],
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.