-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDmLib.ts
More file actions
3787 lines (3393 loc) · 121 KB
/
DmLib.ts
File metadata and controls
3787 lines (3393 loc) · 121 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Actor,
Ammo,
Armor,
Book,
Cell,
Form,
FormType,
Game,
hooks,
Ingredient,
Input,
Key,
Keyword,
Location,
MiscObject,
ObjectReference,
once,
Outfit,
Potion,
printConsole,
settings,
SlotMask,
SoulGem,
storage,
TESModPlatform,
Utility,
Weapon,
WorldSpace,
writeLogs,
} from "skyrimPlatform"
/** Actor helpers */
export namespace ActorLib {
/** Player FormId. */
export const playerId = 0x14
/** Gets the player as an `Actor`.
*
* @remarks
* This function is intended to be used as a callback when you are defining functions that
* need the player, but
* {@link https://github.com/skyrim-multiplayer/skymp/blob/main/docs/skyrim_platform/native.md#native-functions game functions are not available}
* when defining them.
*
* @privateRemarks
* `Game.getPlayer()` is guaranteed to get an `Actor` in Skyrim Platform, so it's
* ok to do `Game.getPlayer() as Actor`.
*/
export const Player = () => Game.getPlayer() as Actor
/** Is an object the player?
* @param a Object to be tested.
* @returns Wether the object is the player.
*/
export function isPlayer(a: Actor | ObjectReference | null) {
if (!a) return false
return a.getFormID() === playerId
}
/**
* Returns the name of the base of an `Actor`.
* @param a Actor to get name from.
* @returns Actor name.
*/
export function getBaseName(a: Actor | null) {
const u = "unknown"
if (!a) return u
return a.getLeveledActorBase()?.getName() || u
}
/** Returns wether an `Actor` `Race` has the `ActorTypeNPC` `Keyword`.
*
* @remarks
* This function is useful to check if an `Actor` is a _humanoid_ type of
* character. Most of these character types are sentient, playable, use the
* installed body modifier (CBBE, UNP, etc), are not creatures...
*
* @param a `Actor` to check.
* @returns Wether the `Actor` has the `Keyword`.
*/
export function isActorTypeNPC(a: Actor | null) {
if (!a) return false
const ActorTypeNPC = Keyword.from(
Game.getFormFromFile(0x13794, "Skyrim.esm")
)
return a.getRace()?.hasKeyword(ActorTypeNPC) || false
}
/** Does something to an `Actor` after some time has passed.
*
* @remarks
* This was made to hide the tediousness of having to retrieve and check
* for an `Actor` each time the `Utility.wait` function is used.
*
* The Actor `a` is guaranteed to exist at the time `DoSomething` is
* executed. If the function is not executed it means `a` is no longer
* available.
*
* @param a `Actor` to work on.
* @param time Time to wait (seconds).
* @param DoSomething What to do when the time has passed.
*/
export function waitActor(
a: Actor,
time: number,
DoSomething: (act: Actor) => void
) {
const actor = FormLib.preserveActor(a)
const f = async () => {
await Utility.wait(time)
const act = actor()
if (!act) return
DoSomething(act)
}
f()
}
// ;> ======================
// ;> ALTERNATE DECLARATIONS
// ;> ======================
/** Player FormId. */
export const PlayerId = playerId
/** Gets the player as an `Actor`.
*
* @remarks
* This function is intended to be used as a callback when you are defining functions that
* need the player, but
* {@link https://github.com/skyrim-multiplayer/skymp/blob/main/docs/skyrim_platform/native.md#native-functions game functions are not available}
* when defining them.
*
* @privateRemarks
* `Game.getPlayer()` is guaranteed to get an `Actor` in Skyrim Platform, so it's
* ok to do `Game.getPlayer() as Actor`.
*/
export const player = Player
/** Is an object the player?
* @param a Object to be tested.
* @returns Wether the object is the player.
*/
export const IsPlayer = isPlayer
/** Returns the name of the base of an `Actor`.
* @param a Actor to get name from.
* @returns Actor name.
*/
export const GetBaseName = getBaseName
/** Returns wether an `Actor` `Race` has the `ActorTypeNPC` `Keyword`.
*
* @remarks
* This function is useful to check if an `Actor` is a _humanoid_ type of
* character. Most of these character types are sentient, playable, use the
* installed body modifier (CBBE, UNP, etc), are not creatures...
*
* @param a `Actor` to check.
* @returns Wether the `Actor` has the `Keyword`.
*/
export const IsActorTypeNPC = isActorTypeNPC
/** Does something to an `Actor` after some time has passed.
*
* @remarks
* This was made to hide the tediousness of having to retrieve and check
* for an `Actor` each time the `Utility.wait` function is used.
*
* The Actor `a` is guaranteed to exist at the time `DoSomething` is
* executed. If the function is not executed it means `a` is no longer
* available.
*
* @param a `Actor` to work on.
* @param time Time to wait (seconds).
* @param DoSomething What to do when the time has passed.
*/
export const WaitActor = waitActor
}
/** Animation helpers */
export namespace AnimLib {
export const enum Animations {
AttackPowerStartBackLeftHand = "attackPowerStartBackLeftHand",
AttackPowerStartBackward = "attackPowerStartBackward",
AttackPowerStartDualWield = "attackPowerStartDualWield",
AttackPowerStartForward = "attackPowerStartForward",
AttackPowerStartForwardH2HLeftHand = "attackPowerStartForwardH2HLeftHand",
AttackPowerStartForwardH2HRightHand = "attackPowerStartForwardH2HRightHand",
AttackPowerStartForwardLeftHand = "attackPowerStartForwardLeftHand",
AttackPowerStartH2HCombo = "attackPowerStartH2HCombo",
AttackPowerStartInPlace = "attackPowerStartInPlace",
AttackPowerStartInPlaceLeftHand = "attackPowerStartInPlaceLeftHand",
AttackPowerStartLeft = "attackPowerStartLeft",
AttackPowerStartLeftLeftHand = "attackPowerStartLeftLeftHand",
AttackPowerStartRight = "attackPowerStartRight",
AttackPowerStartRightLeftHand = "attackPowerStartRightLeftHand",
AttackStart = "attackStart",
AttackStartDualWield = "attackStartDualWield",
AttackStartH2HLeft = "AttackStartH2HLeft",
AttackStartH2HRight = "AttackStartH2HRight",
AttackStartLeftHand = "attackStartLeftHand",
BashRelease = "bashRelease",
BashStart = "bashStart",
BlockStart = "blockStart",
BlockStop = "blockStop",
BowAttackStart = "bowAttackStart",
ChairDrinkingStart = "ChairDrinkingStart",
CrossbowAttackStart = "crossbowAttackStart",
CrossbowDwarvenAttackStart = "crossbowDwarvenAttackStart",
HorseEnter = "HorseEnter",
HorseExit = "HorseExit",
IdleAlchemyEnter = "IdleAlchemyEnter",
IdleBedExitStart = "IdleBedExitStart",
IdleBedLeftEnterStart = "IdleBedLeftEnterStart",
IdleBlacksmithForgeEnter = "IdleBlacksmithForgeEnter",
IdleBlackSmithingEnterStart = "IdleBlackSmithingEnterStart",
IdleCarryBucketPourEnter = "IdleCarryBucketPourEnter",
IdleChairExitStart = "IdleChairExitStart",
IdleChairFrontEnter = "IdleChairFrontEnter",
IdleChairShoulderFlex = "idleChairShoulderFlex",
IdleCounterStart = "IdleCounterStart",
IdleEnchantingEnter = "IdleEnchantingEnter",
IdleExamine = "IdleExamine",
IdleFeedChicken = "IdleFeedChicken",
IdleFurnitureExitSlow = "IdleFurnitureExitSlow",
IdleHammerCarpenterTableEnter = "IdleHammerCarpenterTableEnter",
IdleLeanTableEnter = "IdleLeanTableEnter",
IdleLooseSweepingStart = "idleLooseSweepingStart",
IdleSharpeningWheelStart = "IdleSharpeningWheelStart",
IdleSmelterEnter = "IdleSmelterEnter",
IdleStop = "IdleStop",
IdleStopInstant = "IdleStopInstant",
IdleTanningEnter = "IdleTanningEnter",
IdleTelvanniTowerFloatDown = "IdleTelvanniTowerFloatDown",
IdleTelvanniTowerFloatUp = "IdleTelvanniTowerFloatUp",
IdleWallLeanStart = "IdleWallLeanStart",
JumpDirectionalStart = "JumpDirectionalStart",
JumpLand = "JumpLand",
JumpLandDirectional = "JumpLandDirectional",
JumpStandingStart = "JumpStandingStart",
RitualSpellStart = "RitualSpellStart",
SneakSprintStartRoll = "SneakSprintStartRoll",
SneakStart = "SneakStart",
SneakStop = "SneakStop",
SpellReadyLeftHand = "MLh_SpellReady_event",
SpellReadyRightHand = "MRh_SpellReady_Event",
SpellReleaseLeftHand = "MLH_SpellRelease_event",
SpellReleaseRightHand = "MRh_SpellRelease_Event",
SprintStart = "SprintStart",
SprintStop = "SprintStop",
SwimStart = "SwimStart",
SwimStop = "SwimStop",
Unequip = "Unequip",
}
/** Adds a hook to react to some animation event.
* @param {string} animName Name of the animation to react to.
* @param {()=>void} callback Function to call when animation is played.
* @param {number | undefined} minFormId Minimum FormId of actors to react to.
* @param {number | undefined} maxFormId Maximum FormId of actors to react to.
*/
export function HookAnim(
animName: string,
callback: () => void,
minFormId: number | undefined,
maxFormId: number | undefined
) {
hooks.sendAnimationEvent.add(
{
enter(_) {},
leave(c) {
if (c.animationSucceeded) once("update", () => callback())
},
},
minFormId,
maxFormId,
animName
)
}
// ;> ======================
// ;> ALTERNATE DECLARATIONS
// ;> ======================
/** Adds a hook to react to some animation event.
* @param {string} animName Name of the animation to react to.
* @param {()=>void} callback Function to call when animation is played.
* @param {number | undefined} minFormId Minimum FormId of actors to react to.
* @param {number | undefined} maxFormId Maximum FormId of actors to react to.
*/
export const hookAnim = HookAnim
}
/** Functions related to arrays. */
export namespace ArrayLib {
/** Returns a random element from some array.
*
* @param arr Array to get the element from.
* @returns A random element.
*/
export function randomElement<T>(arr: T[]) {
return arr[Math.floor(Math.random() * arr.length)]
}
// ;> ======================
// ;> ALTERNATE DECLARATIONS
// ;> ======================
/** Returns a random element from some array.
*
* @param arr Array to get the element from.
* @returns A random element.
*/
export const RandomElement = randomElement
}
/** Functional programming combinators.
*
* @remarks
* Many of these may be arcane, but they are quite useful nonetheless.
*
* Some of them are used in this library and you aren't required to use any
* of these, ever.\
* But if you know when to use them, your code will be shorter and your intentions
* clearer.
*
* Highly recommended reading:
*
* - https://tgdwyer.github.io/
* - https://leanpub.com/javascriptallongesix/read#leanpub-auto-making-data-out-of-functions
*/
export namespace Combinators {
/** Returns whatever it's passed to it.
*
* @param x
* @returns x
*
* @remarks
* **This is NOT STUPID**. It's useful, for example, for feeding it to
* functions that may transform values, but we don't want to transform
* something in particular.
*
* It's not much useful by itself, but you will soon see its value
* when you start composing functions.
*
* @see {@link K} for other uses.
*
* @example
* const lower = (x: string) => x.toLowerCase()
* const upper = (x: string) => x.toUpperCase()
* const f = (x: string, g: (x: string) => string) => g(x)
*
* const x = f("LOWER", lower)
* const y = f("upper", upper)
* const z = f("sAmE", I)
*/
export const I = <T>(x: T) => x
/** Returns a function that accepts one parameter, but ignores it and returns whatever
* you originally defined it with.
*
* @param x
* @returns `function (y: any) => x`
*
* @remarks
* This can be used to make a function constant; that is, no matter what you
* pass to it, it will always returns the value you first defined it with.
* This is useful to plug constants into places that are expecting functions.
*
* If combined with {@link I} it can do useful things. `K(I)` will always
* return the second parameter you pass to it.
*
* Combined with {@link O} can be used to make one liners that ensure a calculated value
* is always returned.
*
* @see {@link O} for more uses.
*
* @example
* const first = K
* const second = k(I)
* first("primero")("segundo") // => "primero"
* second("primero")("segundo") // => "segundo"
*
* const msg = K("You are a moron")
* const validate = (x: number) => (typeof x !== "number" ? null : x.toString())
* const intToStr = O(validate, msg)
* intToStr(null) // => "You are a moron"
* intToStr(32) // => 32
*
* const guaranteedActorBase = O((a: Actor) => a.getLeveledActorBase(), K(Game.getPlayer()?.getBaseObject()))
* guaranteedActorBase(null) // => player
* guaranteedActorBase(whiterunGuard) // => Whiterun Guard
*/
export const K =
<T>(x: T) =>
(y: any): T =>
x
/** Creates a function that accepts one parameter `x`. Returns `f1(x)` if not `null`, else `f2(x)`.
*
* @param f1 First function to apply.
* @param f2 Second function to apply.
* @returns `f1(x)` if not `null`, else `f2(x)`.
*/
export const O =
<U>(f1: (...args: any[]) => U | null, f2: (...args: any[]) => U) =>
(...args: any[]): U =>
f1(...args) || f2(...args)
/** Applies function `f` to `x` and returns `x`. Useful for chaining functions that return nothing.
*
* @param x
* @param f
* @returns x
*/
export function Tap<K>(x: K, f: (x: K) => void) {
f(x)
return x
}
/** Returns a value while executing a function.
*
* @see {@link DebugLib.Log.R} for a sample usage.
*
* @param f Function to execute.
* @param x Value to return.
* @returns `x`
*/
export const Return = <T>(f: void, x: T) => Tap(x, K(f))
// ;> ======================
// ;> ALTERNATE DECLARATIONS
// ;> ======================
/** Returns whatever it's passed to it.
*
* @param x
* @returns x
*
* @remarks
* **This is NOT STUPID**. It's useful, for example, for feeding it to
* functions that may transform values, but we don't want to transform
* something in particular.
*
* It's not much useful by itself, but you will soon see its value
* when you start composing functions.
*
* @see {@link K} for other uses.
*
* @example
* const lower = (x: string) => x.toLowerCase()
* const upper = (x: string) => x.toUpperCase()
* const f = (x: string, g: (x: string) => string) => g(x)
*
* const x = f("LOWER", lower)
* const y = f("upper", upper)
* const z = f("sAmE", I)
*/
export const i = I
/** Returns a function that accepts one parameter, but ignores it and returns whatever
* you originally defined it with.
*
* @param x
* @returns `function (y: any) => x`
*
* @remarks
* This can be used to make a function constant; that is, no matter what you
* pass to it, it will always returns the value you first defined it with.
* This is useful to plug constants into places that are expecting functions.
*
* If combined with {@link I} it can do useful things. `K(I)` will always
* return the second parameter you pass to it.
*
* Combined with {@link O} can be used to make one liners that ensure a calculated value
* is always returned.
*
* @see {@link O} for more uses.
*
* @example
* const first = K
* const second = k(I)
* first("primero")("segundo") // => "primero"
* second("primero")("segundo") // => "segundo"
*
* const msg = K("You are a moron")
* const validate = (x: number) => (typeof x !== "number" ? null : x.toString())
* const intToStr = O(validate, msg)
* intToStr(null) // => "You are a moron"
* intToStr(32) // => 32
*
* const guaranteedActorBase = O((a: Actor) => a.getLeveledActorBase(), K(Game.getPlayer()?.getBaseObject()))
* guaranteedActorBase(null) // => player
* guaranteedActorBase(whiterunGuard) // => Whiterun Guard
*/
export const k = K
/** Creates a function that accepts one parameter `x`. Returns `f1(x)` if not `null`, else `f2(x)`.
*
* @param f1 First function to apply.
* @param f2 Second function to apply.
* @returns `f1(x)` if not `null`, else `f2(x)`.
*/
export const o = O
/** Applies function `f` to `x` and returns `x`. Useful for chaining functions that return nothing.
*
* @param x
* @param f
* @returns x
*/
export const tap = Tap
}
/** Useful functions for debugging. */
export namespace DebugLib {
export namespace Log {
/** How much will the console be spammed.
* - optimization Meant to only output the times functions take to execute. Used for bottleneck solving.
* - none No spam.
* - error Just errors and stuff like that.
* - info Detailed info so players can know if things are going as expected, but not enough for actual debugging.
* - verbose Info meant for developers. Use it for reporting errors or unexpected behavior.
*/
export enum Level {
optimization = -1,
none,
error,
info,
verbose,
}
/** Gets the logging level from some configuration file.
*
* @param pluginName Name of the plugin to get the value from.
* @param optionName Name of the variable that carries the value.
* @returns The logging level from file. `verbose` if value was invalid.
*/
export function LevelFromSettings(
pluginName: string,
optionName: string
): Level {
return LevelFromValue(settings[pluginName][optionName])
}
/** Gets a logging {@link Level} from either a string or a number.
*
* @param v The string or number to convert to a Level.
* @returns A logging Level. `Level.verbose` if `v` can not be converted.
*/
export function LevelFromValue(v: any): Level {
const l =
typeof v === "string"
? v.toLowerCase()
: typeof v === "number"
? v
: "verbose"
let t = (<any>Level)[l]
if (typeof l === "number") t = Level[t]
return t === undefined ? Level.verbose : t
}
/** A function that accepts a message. Returns nothing. */
export type LoggingFunction = (msg: string) => void
/** Signature of a function used for giving format to logging. */
export type LogFormat = (
currLogLvl: Level,
maxLogLvl: Level,
modName: string,
date: Date,
msg: string
) => string
/** Returns a string in the form `"[Mod name]: Message"`.
* @see {@link FileFmt}.
*
* @remarks
* You can use this function as a guide on how a {@link LogFormat} function
* used for {@link CreateFunction} can be made.
*
* @example
* const LogI = CreateFunction(userLevel, Level.info, "my-mod", ConsoleFmt, FileFmt)
* const LogV = CreateFunction(userLevel, Level.verbose, "my-mod", ConsoleFmt, FileFmt)
*
* // Console output: "[my-mod]: This is important for the player."
* // File output: "[info] 4/5/2021 12:32:15 p.m.: This is important for the player."
* LogI("This is important for the player.")
*
* // Console output: "[my-mod]: This is useful for debugging."
* // File output: "[verbose] 4/5/2021 12:32:15 p.m.: This is useful for debugging."
* LogV("This is useful for debugging.")
*/
export const ConsoleFmt: LogFormat = (_, __, n, ___, msg) =>
`[${n}]: ${msg}`
/** Returns a string in the form `"[logging level] date-time: Message"`.
* @see {@link ConsoleFmt}.
*
* @remarks
* You can use this function as a guide on how a {@link LogFormat} function
* used for {@link CreateFunction} can be made.
*
* Format for https://github.com/Scarfsail/AdvancedLogViewer :\
* `[{Type}] {Date} {Time}: {Message}`
*
* @example
* const LogI = CreateFunction(userLevel, Level.info, "my-mod", ConsoleFmt, FileFmt)
* const LogV = CreateFunction(userLevel, Level.verbose, "my-mod", ConsoleFmt, FileFmt)
*
* // Console output: "[my-mod]: This is important for the player."
* // File output: "[info] 4/5/2021 12:32:15 p.m.: This is important for the player."
* LogI("This is important for the player.")
*
* // Console output: "[my-mod]: This is useful for debugging."
* // File output: "[verbose] 4/5/2021 12:32:15 p.m.: This is useful for debugging."
* LogV("This is useful for debugging.")
*/
export const FileFmt: LogFormat = (_, m, __, t, msg) =>
`[${Level[m]}] ${t.toLocaleString()}: ${msg}`
/** A function that accepts a message, a variable and an optional function.
*
* Returns the variable after logging the message.
* If a function was passed, it will be applied to the variable before logging.
*
* Function `f` must be a function that transforms variables of the same type
* of `x` to string.
*/
export type TappedFunction = <T>(
msg: string,
x: T,
f?: (x: T) => string
) => T
/** Creates a logging function that appends some message before logging.
*
* @param f Function to wrap.
* @param append Message to append each time the result is called.
* @returns A {@link LoggingFunction}.
*
* @example
* const CMLL = Append(printConsole, "Kemonito: ")
* CMLL("Kicks") // => "Kemonito: Kicks"
* CMLL("Flies!") // => "Kemonito: Flies!"
* CMLL("Is love") // => "Kemonito: Is love"
* CMLL("Is life") // => "Kemonito: Is life"
*/
export function Append(f: LoggingFunction, append: any): LoggingFunction {
return (msg: any) => f(append + msg)
}
/** Creates a logging function that appends some message before logging.
*
* @see {@link Append}
*
* @param f Function to wrap.
* @param append Message to append each time the result is called.
* @returns A {@link TappedFunction}.
*/
export function AppendT(f: TappedFunction, append: any): TappedFunction {
return <T>(msg: string, x: T, fmt?: (x: T) => string) =>
f(append + msg, x, fmt)
}
/** Creates a function used for logging. Said function can log to either console or to some file.
*
* @see {@link FileFmt}, {@link ConsoleFmt}.
*
* @param currLogLvl The log level the user has selected. I.e. how much info they want to get.
* @param logAt At which level this function will log.
* @param modName Name of the mod. Will be used to output messages and to name the output file.
* Output file will be named `"Data\Platform\Plugins\modName-logs.txt"`.
* @param ConsoleFmt A function of type {@link LogFormat}. If `undefined`, nothing will be output to console.
* @param FileFmt A function of type {@link LogFormat}. If `undefined`, nothing will be output to file.
* @returns A function that logs a message as a string.
*
* @example
* // LogI will only log to file
* const LogI = CreateFunction(Level.info, Level.info, "my-mod", undefined, FileFmt)
*
* // LogV won't log anything because player only wants to log at most Level.info type messages
* const LogV = CreateFunction(Level.info, Level.verbose, "my-mod", ConsoleFmt, FileFmt)
*/
export function CreateFunction(
currLogLvl: Level,
logAt: Level,
modName: string,
ConsoleFmt?: LogFormat,
FileFmt?: LogFormat
): LoggingFunction {
return function (msg: any) {
const canLog =
currLogLvl >= logAt || (currLogLvl < 0 && currLogLvl === logAt)
if (!canLog) return
const t = new Date()
if (ConsoleFmt)
printConsole(ConsoleFmt(currLogLvl, logAt, modName, t, msg))
if (FileFmt)
writeLogs(modName, FileFmt(currLogLvl, logAt, modName, t, msg))
}
}
/** Creates all functions at all logging levels with their corresponding Tapped counterparts.
*
* @param mod Mod name. This will be saved for each line.
* @param logLvl Current logging level for the mod.
* @param Console Console format.
* @param File File format.
* @returns An object with all functions.
*/
export function CreateAll(
mod: string,
logLvl: Level,
Console?: LogFormat,
File?: LogFormat
) {
const CLF = (logAt: Level) =>
CreateFunction(logLvl, logAt, mod, Console, File)
const O = CLF(Level.optimization)
const N = CLF(Level.none)
const E = CLF(Level.error)
const I = CLF(Level.info)
const V = CLF(Level.verbose)
return {
/** Log at special mode: optimization. */
Optimization: O,
/** Log at none level. Basically, ignore logging settings, except when using special modes. */
None: N,
/** Log at error level. */
Error: E,
/** Log at info level. */
Info: I,
/** Log at verbose level. */
Verbose: V,
/** Log at special mode: optimization. Return value. */
TapO: Tap(O),
/** Log at none level and return value. */
TapN: Tap(N),
/** Log at error level and return value. */
TapE: Tap(E),
/** Log at info level and return value. */
TapI: Tap(I),
/** Log at verbose level and return value. */
TapV: Tap(V),
}
}
/** Makes a logging function to log a value, then returns that value.
*
* @param f - The logging function.
* @returns A {@link TappedFunction}.
*
* @remarks
* This function is intended to be used to initialize variables while logging them,
* so logging looks cleaner and variables become self documenting in code and
* "debuggeable" at the same time.
*
* @example
* const IntToHex = (x: number) => x.toString(16)
* const LogAndInit = Tap(printConsole)
*
* // "Value for x: 3". Meanwhile: x === 3.
* const x = LogAndInit("Value for x", 3)
*
* // "Hex: ff". Meanwhile: ff === 255
* const ff = LogAndInit("Hex", 255, IntToHex)
*
* // Don't know what the next call will yield, but we can log it to console to see it!
* const form = LogAndInit("Found form", Game.getFormFromFile(0x3bba, "Skyrim.esm"))
*/
export function Tap(f: LoggingFunction): TappedFunction {
return function <T>(msg: string, x: T, g?: (x: T) => string): T {
if (g) {
if (msg) f(`${msg}: ${g(x)}`)
else f(g(x))
} else {
if (msg) f(`${msg}: ${x}`)
else f(`${x}`)
}
return x
}
}
/** Returns `x` while executing a logging function. `R` means _[R]eturn_.
*
* @remarks
* This is useful for uncluttering logging calls when returning values from functions,
* but can be used to log variable assignments as well.
*
* At first this may look like it's doing the same as {@link Tap}, but this function provides much
* more flexibility at the cost of doing more writing.\
* Both functions are useful and can be used together for great flexibilty.
*
* @param f A function that takes any number of arguments and returns `void`.
* @param x The value to be returned.
* @returns `x`
*
* @example
* const Msg = (s: string) => { printConsole(`This is a ${s}`) }
* const x = R(Msg("number"), 2) // => "This is a number"; x === 2
* const s = R(Msg("string"), "noob") // => "This is a string"; s === "noob"
*/
export const R = Combinators.Return
/** Converts an integer to hexadecimal notation.
*
* @remarks
* This function has apparently absurd safeguards because it's intended to be used for logging.\
* If you want a straight forward conversion, just use `x.toString(16)`.
*
* @param x
* @returns string
*/
export function IntToHex(x: number) {
return !x || typeof x !== "number"
? "IntToHex: Undefined value"
: x.toString(16)
}
// ;> ======================
// ;> ALTERNATE DECLARATIONS
// ;> ======================
/** Gets the logging level from some configuration file.
*
* @param pluginName Name of the plugin to get the value from.
* @param optionName Name of the variable that carries the value.
* @returns The logging level from file. `verbose` if value was invalid.
*/
export const levelFromSettings = LevelFromSettings
/** Gets a logging {@link Level} from either a string or a number.
*
* @param v The string or number to convert to a Level.
* @returns A logging Level. `Level.verbose` if `v` can not be converted.
*/
export const levelFromValue = LevelFromValue
/** Returns a string in the form `"[Mod name]: Message"`.
* @see {@link FileFmt}.
*
* @remarks
* You can use this function as a guide on how a {@link LogFormat} function
* used for {@link CreateFunction} can be made.
*
* @example
* const LogI = CreateFunction(userLevel, Level.info, "my-mod", ConsoleFmt, FileFmt)
* const LogV = CreateFunction(userLevel, Level.verbose, "my-mod", ConsoleFmt, FileFmt)
*
* // Console output: "[my-mod]: This is important for the player."
* // File output: "[info] 4/5/2021 12:32:15 p.m.: This is important for the player."
* LogI("This is important for the player.")
*
* // Console output: "[my-mod]: This is useful for debugging."
* // File output: "[verbose] 4/5/2021 12:32:15 p.m.: This is useful for debugging."
* LogV("This is useful for debugging.")
*/
export const consoleFmt = ConsoleFmt
/** Returns a string in the form `"[logging level] date-time: Message"`.
* @see {@link ConsoleFmt}.
*
* @remarks
* You can use this function as a guide on how a {@link LogFormat} function
* used for {@link CreateFunction} can be made.
*
* Format for https://github.com/Scarfsail/AdvancedLogViewer :\
* `[{Type}] {Date} {Time}: {Message}`
*
* @example
* const LogI = CreateFunction(userLevel, Level.info, "my-mod", ConsoleFmt, FileFmt)
* const LogV = CreateFunction(userLevel, Level.verbose, "my-mod", ConsoleFmt, FileFmt)
*
* // Console output: "[my-mod]: This is important for the player."
* // File output: "[info] 4/5/2021 12:32:15 p.m.: This is important for the player."
* LogI("This is important for the player.")
*
* // Console output: "[my-mod]: This is useful for debugging."
* // File output: "[verbose] 4/5/2021 12:32:15 p.m.: This is useful for debugging."
* LogV("This is useful for debugging.")
*/
export const fileFmt = FileFmt
/** Creates a logging function that appends some message before logging.
*
* @param f Function to wrap.
* @param append Message to append each time the result is called.
* @returns A {@link LoggingFunction}.
*
* @example
* const CMLL = Append(printConsole, "Kemonito: ")
* CMLL("Kicks") // => "Kemonito: Kicks"
* CMLL("Flies!") // => "Kemonito: Flies!"
* CMLL("Is love") // => "Kemonito: Is love"
* CMLL("Is life") // => "Kemonito: Is life"
*/
export const append = Append
/** Creates a logging function that appends some message before logging.
*
* @see {@link Append}
*
* @param f Function to wrap.
* @param append Message to append each time the result is called.
* @returns A {@link TappedFunction}.
*/
export const appendT = AppendT
/** Creates a function used for logging. Said function can log to either console or to some file.
*
* @see {@link FileFmt}, {@link ConsoleFmt}.
*
* @param currLogLvl The log level the user has selected. I.e. how much info they want to get.
* @param logAt At which level this function will log.
* @param modName Name of the mod. Will be used to output messages and to name the output file.
* Output file will be named `"Data\Platform\Plugins\modName-logs.txt"`.
* @param ConsoleFmt A function of type {@link LogFormat}. If `undefined`, nothing will be output to console.
* @param FileFmt A function of type {@link LogFormat}. If `undefined`, nothing will be output to file.
* @returns A function that logs a message as a string.
*
* @example
* // LogI will only log to file
* const LogI = CreateFunction(Level.info, Level.info, "my-mod", undefined, FileFmt)
*
* // LogV won't log anything because player only wants to log at most Level.info type messages
* const LogV = CreateFunction(Level.info, Level.verbose, "my-mod", ConsoleFmt, FileFmt)
*/
export const createFunction = CreateFunction
/** Creates all functions at all logging levels with their corresponding Tapped counterparts.
*
* @param mod Mod name. This will be saved for each line.
* @param logLvl Current logging level for the mod.
* @param Console Console format.
* @param File File format.
* @returns An object with all functions.
*/
export const createAll = CreateAll
/** Makes a logging function to log a value, then returns that value.
*
* @param f - The logging function.
* @returns A {@link TappedFunction}.
*
* @remarks
* This function is intended to be used to initialize variables while logging them,
* so logging looks cleaner and variables become self documenting in code and
* "debuggeable" at the same time.
*
* @example
* const IntToHex = (x: number) => x.toString(16)
* const LogAndInit = Tap(printConsole)
*
* // "Value for x: 3". Meanwhile: x === 3.
* const x = LogAndInit("Value for x", 3)
*
* // "Hex: ff". Meanwhile: ff === 255
* const ff = LogAndInit("Hex", 255, IntToHex)
*
* // Don't know what the next call will yield, but we can log it to console to see it!
* const form = LogAndInit("Found form", Game.getFormFromFile(0x3bba, "Skyrim.esm"))
*/
export const tap = Tap
/** Returns `x` while executing a logging function. `R` means _[R]eturn_.
*
* @remarks
* This is useful for uncluttering logging calls when returning values from functions,
* but can be used to log variable assignments as well.
*
* At first this may look like it's doing the same as {@link Tap}, but this function provides much
* more flexibility at the cost of doing more writing.\
* Both functions are useful and can be used together for great flexibilty.
*
* @param f A function that takes any number of arguments and returns `void`.
* @param x The value to be returned.
* @returns `x`
*
* @example
* const Msg = (s: string) => { printConsole(`This is a ${s}`) }
* const x = R(Msg("number"), 2) // => "This is a number"; x === 2
* const s = R(Msg("string"), "noob") // => "This is a string"; s === "noob"
*/
export const r = R
/** Converts an integer to hexadecimal notation.
*
* @remarks
* This function has apparently absurd safeguards because it's intended to be used for logging.\
* If you want a straight forward conversion, just use `x.toString(16)`.
*
* @param x
* @returns string
*/
export const intToHex = IntToHex
}