@aifivem/lib 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/package.json +34 -4
  2. package/src/client/action.ts +38 -0
  3. package/src/client/adminWorld.ts +95 -0
  4. package/src/client/appearance.ts +29 -0
  5. package/src/client/areaFollower.ts +41 -0
  6. package/src/client/blip.ts +79 -0
  7. package/src/client/cache.ts +66 -0
  8. package/src/client/callback.ts +70 -0
  9. package/src/client/controls.ts +73 -0
  10. package/src/client/entities.ts +83 -0
  11. package/src/client/entity.ts +26 -0
  12. package/src/client/fuel.ts +18 -0
  13. package/src/client/gestures.ts +18 -0
  14. package/src/client/headshot.ts +26 -0
  15. package/src/client/hud.ts +24 -0
  16. package/src/client/index.ts +131 -0
  17. package/src/client/inventory.ts +117 -0
  18. package/src/client/keyHints.ts +13 -0
  19. package/src/client/keybind.ts +163 -0
  20. package/src/client/localPed.ts +169 -0
  21. package/src/client/location.ts +54 -0
  22. package/src/client/mdt.ts +10 -0
  23. package/src/client/medical.ts +28 -0
  24. package/src/client/membership.ts +41 -0
  25. package/src/client/menu/dialogs.ts +77 -0
  26. package/src/client/menu/minigames.ts +79 -0
  27. package/src/client/menu/requests.ts +65 -0
  28. package/src/client/modelScan/def.ts +29 -0
  29. package/src/client/modelScan/objectIndex.ts +41 -0
  30. package/src/client/modelScan/scan.ts +69 -0
  31. package/src/client/modelScan/scanner.ts +164 -0
  32. package/src/client/netEvent.ts +40 -0
  33. package/src/client/notify.ts +14 -0
  34. package/src/client/nuiScreen.ts +87 -0
  35. package/src/client/player/anim.ts +98 -0
  36. package/src/client/player/fade.ts +17 -0
  37. package/src/client/player/player.ts +80 -0
  38. package/src/client/player/teleport.ts +87 -0
  39. package/src/client/playerData.ts +83 -0
  40. package/src/client/players.ts +44 -0
  41. package/src/client/points/interact.ts +144 -0
  42. package/src/client/points/modelHost.ts +117 -0
  43. package/src/client/points/modelPoint.ts +181 -0
  44. package/src/client/points/point.ts +159 -0
  45. package/src/client/points/points.ts +170 -0
  46. package/src/client/points/targets/adapter.ts +40 -0
  47. package/src/client/points/targets/interactTarget.ts +45 -0
  48. package/src/client/points/targets/optionShape.ts +22 -0
  49. package/src/client/points/targets/oxTarget.ts +42 -0
  50. package/src/client/points/targets/qbTarget.ts +71 -0
  51. package/src/client/points/targets/targets.ts +20 -0
  52. package/src/client/preview.ts +51 -0
  53. package/src/client/progress.ts +132 -0
  54. package/src/client/prompt.ts +26 -0
  55. package/src/client/prop.ts +79 -0
  56. package/src/client/radial.ts +16 -0
  57. package/src/client/raycast.ts +48 -0
  58. package/src/client/scriptCamera.ts +167 -0
  59. package/src/client/seatbelt.ts +18 -0
  60. package/src/client/shot.ts +29 -0
  61. package/src/client/streaming.ts +91 -0
  62. package/src/client/tickLoop.ts +18 -0
  63. package/src/client/vehicleKeys.ts +14 -0
  64. package/src/client/vehicleProps.ts +107 -0
  65. package/src/client/vehicles.ts +46 -0
  66. package/src/client/waypoint.ts +10 -0
  67. package/src/client/world.ts +10 -0
  68. package/src/client/zoneEngine.ts +174 -0
  69. package/src/client/zones.ts +161 -0
  70. package/src/fivem/byResource.ts +146 -0
  71. package/src/fivem/callbackNames.ts +12 -0
  72. package/src/fivem/exports.ts +70 -0
  73. package/src/fivem/index.ts +13 -0
  74. package/src/fivem/locale.ts +57 -0
  75. package/src/fivem/playerData.ts +13 -0
  76. package/src/fivem/scheduler/every.ts +101 -0
  77. package/src/fivem/scheduler/group.ts +97 -0
  78. package/src/fivem/scheduler/scheduler.ts +77 -0
  79. package/src/fivem/state/entityState.ts +75 -0
  80. package/src/fivem/state/globalState.ts +80 -0
  81. package/src/fivem/state/mirror.ts +47 -0
  82. package/src/fivem/state/playerState.ts +60 -0
  83. package/src/server/admin/descriptions.ts +57 -0
  84. package/src/server/admin/edit.ts +127 -0
  85. package/src/server/admin/jsonSchema.ts +156 -0
  86. package/src/server/admin/panel.ts +167 -0
  87. package/src/server/admin/panelFiles.ts +128 -0
  88. package/src/server/admin/patch.ts +46 -0
  89. package/src/server/admin/validate.ts +147 -0
  90. package/src/server/appearance.ts +28 -0
  91. package/src/server/areaStream/areaStream.ts +141 -0
  92. package/src/server/areaStream/followers.ts +154 -0
  93. package/src/server/areaStream/grid.ts +74 -0
  94. package/src/server/areaStream/options.ts +16 -0
  95. package/src/server/banking.ts +15 -0
  96. package/src/server/bans.ts +47 -0
  97. package/src/server/billing.ts +20 -0
  98. package/src/server/buckets.ts +12 -0
  99. package/src/server/callback.ts +112 -0
  100. package/src/server/characters.ts +129 -0
  101. package/src/server/command/addCommand.ts +83 -0
  102. package/src/server/command/command.ts +116 -0
  103. package/src/server/command/commandSet.ts +74 -0
  104. package/src/server/dataFile.ts +81 -0
  105. package/src/server/database.ts +117 -0
  106. package/src/server/definitions.ts +65 -0
  107. package/src/server/dispatch.ts +13 -0
  108. package/src/server/doors.ts +15 -0
  109. package/src/server/ems.ts +15 -0
  110. package/src/server/fuel.ts +15 -0
  111. package/src/server/garages.ts +34 -0
  112. package/src/server/gate.ts +148 -0
  113. package/src/server/index.ts +165 -0
  114. package/src/server/inventory.ts +106 -0
  115. package/src/server/jobs.ts +42 -0
  116. package/src/server/log.ts +21 -0
  117. package/src/server/mdt.ts +12 -0
  118. package/src/server/medical.ts +16 -0
  119. package/src/server/minigameFor.ts +65 -0
  120. package/src/server/money.ts +70 -0
  121. package/src/server/netEntity.ts +19 -0
  122. package/src/server/netEvent.ts +58 -0
  123. package/src/server/notify.ts +17 -0
  124. package/src/server/online/mirror.ts +176 -0
  125. package/src/server/online/online.ts +190 -0
  126. package/src/server/pending.ts +70 -0
  127. package/src/server/phone.ts +22 -0
  128. package/src/server/players.ts +197 -0
  129. package/src/server/position.ts +31 -0
  130. package/src/server/primeTime.ts +7 -0
  131. package/src/server/prison.ts +15 -0
  132. package/src/server/progressFor.ts +62 -0
  133. package/src/server/proximity.ts +98 -0
  134. package/src/server/rateLimit.ts +53 -0
  135. package/src/server/state.ts +45 -0
  136. package/src/server/stress.ts +25 -0
  137. package/src/server/vehicle/nearby.ts +66 -0
  138. package/src/server/vehicle/plate.ts +14 -0
  139. package/src/server/vehicle/spawn.ts +125 -0
  140. package/src/server/vehicle/vehicleType.ts +50 -0
  141. package/src/server/vehicleKeys.ts +23 -0
  142. package/src/server/watchers.ts +46 -0
  143. package/src/server/world.ts +16 -0
  144. package/src/shared/access.ts +94 -0
  145. package/src/shared/action.ts +28 -0
  146. package/src/shared/blipStyle.ts +26 -0
  147. package/src/shared/clock.ts +22 -0
  148. package/src/shared/format.ts +36 -0
  149. package/src/shared/grid.ts +20 -0
  150. package/src/shared/index.ts +179 -0
  151. package/src/shared/lang.ts +39 -0
  152. package/src/shared/placePed.ts +96 -0
  153. package/src/shared/random.ts +11 -0
  154. package/src/shared/read.ts +60 -0
  155. package/src/shared/records.ts +148 -0
  156. package/src/shared/spec.ts +20 -0
  157. package/src/shared/strict.ts +70 -0
  158. package/src/shared/vec.ts +48 -0
  159. package/src/shared/vehicleProps.ts +138 -0
  160. package/src/shared/wait.ts +27 -0
  161. package/src/shared/zone.ts +144 -0
  162. package/README.md +0 -3
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@aifivem/lib",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
4
+ "description": "Helpers every ai-core resource uses: logging, exports, rate limits, database tables.",
5
+ "license": "GPL-3.0-only",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/aifivem/aicore-packages.git",
9
+ "directory": "lib"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ "./shared": "./src/shared/index.ts",
14
+ "./fivem": "./src/fivem/index.ts",
15
+ "./server": "./src/server/index.ts",
16
+ "./client": "./src/client/index.ts"
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "dependencies": {
25
+ "@aifivem/shared": "^0.6.0",
26
+ "@aifivem/mysql": "^0.2.0"
27
+ },
28
+ "devDependencies": {
29
+ "@citizenfx/client": "latest",
30
+ "@citizenfx/server": "latest",
31
+ "@types/node": "^22"
32
+ },
33
+ "scripts": {
34
+ "bench": "bun bench/scheduler.bench.ts && bun bench/zones.bench.ts && bun bench/modelScan.bench.ts && bun bench/command.bench.ts && bun bench/state.bench.ts && bun bench/online.bench.ts && bun bench/players.bench.ts && bun bench/area.bench.ts && bun bench/records.bench.ts && bun bench/watchers.bench.ts && bun bench/entities.bench.ts"
35
+ }
36
+ }
@@ -0,0 +1,38 @@
1
+ import { loadLocaleTexts } from "../fivem/locale";
2
+ import { isActionOk, replyError } from "../shared/action";
3
+ import { triggerServerCallback } from "./callback";
4
+ import { notify } from "./notify";
5
+
6
+ /** This resource's lang table, read on the first refusal. */
7
+ let texts: Record<string, string> | null = null;
8
+
9
+ export interface CallActionOptions {
10
+ /** Lang key shown when the reply is missing, malformed, timed out or the call was refused by the gate. */
11
+ fallback: string;
12
+ /** ms before the call counts as failed (default the callback timeout). */
13
+ timeout?: number;
14
+ /** No notification on a refusal (the caller shows the error itself). */
15
+ silent?: boolean;
16
+ }
17
+
18
+ /**
19
+ * Runs an action on the server (`onClientCallback` answering an `ActionResult`). A refusal, a timeout or a gate
20
+ * refusal shows the error's text from this resource's lang file as an error notification. Resolves with the ok
21
+ * reply (extra fields unchecked: parse the ones you read), null otherwise.
22
+ */
23
+ export async function callAction(
24
+ name: string,
25
+ args: unknown[] = [],
26
+ options: CallActionOptions,
27
+ ): Promise<({ ok: true } & Record<string, unknown>) | null> {
28
+ const reply = await triggerServerCallback(name, args, options.timeout).catch(
29
+ () => null,
30
+ );
31
+ if (isActionOk(reply)) return reply;
32
+ if (!options.silent) {
33
+ const key = replyError(reply, options.fallback) ?? options.fallback;
34
+ texts ??= loadLocaleTexts();
35
+ notify(texts[key] ?? key, "error");
36
+ }
37
+ return null;
38
+ }
@@ -0,0 +1,95 @@
1
+ import { ADMIN } from "@aifivem/shared";
2
+ import { createLogger, isRecord, withoutSchemaKey } from "../shared";
3
+ import { FileViews, type RecordReader } from "../shared/records";
4
+ import { triggerServerCallback } from "./callback";
5
+ import { onServerEvent } from "./netEvent";
6
+
7
+ type Data = Record<string, unknown>;
8
+ /** A record changed (records: its key; settings: no key, the whole object); `null` = deleted. */
9
+ type ChangeHandler = (key: string | undefined, value: unknown) => void;
10
+
11
+ /**
12
+ * The client copy of a resource's world panel files (`sync: "all"`): the file FiveM cached at start, then the
13
+ * records changed since start (asked once), then live changes. Never polls.
14
+ */
15
+ export class AdminWorld {
16
+ private readonly data = new Map<string, Data>();
17
+ private readonly handlers = new Map<string, ChangeHandler[]>();
18
+ private readonly resource = GetCurrentResourceName();
19
+ private readonly views = new FileViews((file) => this.get(file));
20
+ /** Resolves once the changes since start are applied (or could not be loaded): the data is current from then on. */
21
+ readonly ready: Promise<void>;
22
+
23
+ /** `files`: the world files this client mirrors (each must be in the resource's `files`). */
24
+ constructor(files: string[]) {
25
+ const log = createLogger(this.resource);
26
+ for (const file of files) {
27
+ const raw = LoadResourceFile(this.resource, `data/${file}.json`);
28
+ try {
29
+ const parsed: unknown = raw ? withoutSchemaKey(JSON.parse(raw)) : {};
30
+ this.data.set(file, isRecord(parsed) ? parsed : {});
31
+ } catch (error) {
32
+ log.error(`data/${file}.json is not valid JSON`, error);
33
+ this.data.set(file, {});
34
+ }
35
+ }
36
+ onServerEvent(
37
+ ADMIN.worldEvent(this.resource),
38
+ {
39
+ args: ([file, key, value]) =>
40
+ typeof file === "string"
41
+ ? [
42
+ file,
43
+ typeof key === "string" && key !== "" ? key : undefined,
44
+ value,
45
+ ]
46
+ : null,
47
+ },
48
+ (file, key, value) => this.put(file, key, value),
49
+ );
50
+ this.ready = triggerServerCallback(
51
+ ADMIN.worldChangesCallback(this.resource),
52
+ ).then(
53
+ (changes) => {
54
+ if (!isRecord(changes)) return;
55
+ for (const [file, records] of Object.entries(changes)) {
56
+ if (!isRecord(records)) continue;
57
+ for (const [key, value] of Object.entries(records))
58
+ this.put(file, key === "" ? undefined : key, value);
59
+ }
60
+ },
61
+ (error: unknown) =>
62
+ log.error("loading the panel changes since start failed", error),
63
+ );
64
+ }
65
+
66
+ /** The current content of a file: the settings object, or `{ key: record }`. Read only; parse what you use. */
67
+ get(file: string): Data {
68
+ return this.data.get(file) ?? {};
69
+ }
70
+
71
+ onChange(file: string, handler: ChangeHandler): void {
72
+ this.handlers.set(file, [...(this.handlers.get(file) ?? []), handler]);
73
+ }
74
+
75
+ /** A file parsed by `read`, kept current on every change (settings files; parsed before `onChange` handlers run). */
76
+ view<T>(file: string, read: (raw: unknown) => T): { readonly value: T } {
77
+ return this.views.view(file, read);
78
+ }
79
+
80
+ /** A records file parsed per record through `readOne` (null leaves a record out); a change re-reads only that record. */
81
+ records<T>(file: string, readOne: RecordReader<T>): ReadonlyMap<string, T> {
82
+ return this.views.records(file, readOne);
83
+ }
84
+
85
+ private put(file: string, key: string | undefined, value: unknown): void {
86
+ const data = this.data.get(file);
87
+ if (!data) return;
88
+ if (key === undefined) {
89
+ if (isRecord(value)) this.data.set(file, value);
90
+ } else if (value === null) delete data[key];
91
+ else data[key] = value;
92
+ this.views.changed(file, key, value);
93
+ for (const handler of this.handlers.get(file) ?? []) handler(key, value);
94
+ }
95
+ }
@@ -0,0 +1,29 @@
1
+ import {
2
+ CORE,
3
+ toCharacterAppearance,
4
+ type CharacterAppearance,
5
+ type ClothingMenu,
6
+ type JobOutfit,
7
+ } from "@aifivem/shared";
8
+ import { resourceExport } from "../fivem/exports";
9
+
10
+ const core = resourceExport(CORE.resource);
11
+
12
+ /** Looks on peds through ai-core's appearance layer, whatever clothing script runs (ai-appearance, tgiann-clothing). */
13
+ export const appearance = {
14
+ /**
15
+ * Puts a look (server `appearance.get`) on a ped of the look's model (create the ped with `look.model`); false when
16
+ * the ped is gone, the model differs or no clothing script runs. On the player's own ped it changes their clothes.
17
+ */
18
+ apply: (ped: number, look: CharacterAppearance): boolean =>
19
+ core.ApplyAppearance(ped, look),
20
+ /** The look a ped wears now, null when the clothing script cannot tell. */
21
+ read: (ped: number): CharacterAppearance | null =>
22
+ toCharacterAppearance(core.GetPedAppearance(ped)),
23
+ /** Opens the clothing script's clothing shop, barber or saved outfits for the player; false when it has none. */
24
+ openMenu: (menu: ClothingMenu): boolean => core.OpenClothingMenu(menu),
25
+ /** Puts a job outfit (collection pieces) on the player until `reloadSkin`, not saved; false when it cannot. */
26
+ wearOutfit: (outfit: JobOutfit): boolean => core.WearOutfit(outfit),
27
+ /** Puts the player's saved look back on (takes a job outfit off); false without a clothing script. */
28
+ reloadSkin: (): boolean => core.ReloadSkin(),
29
+ };
@@ -0,0 +1,41 @@
1
+ import { every } from "../fivem/scheduler/every";
2
+ import { gridCell } from "../shared/grid";
3
+ import { cache } from "./cache";
4
+
5
+ /**
6
+ * Tells the server this player's grid cell whenever it changes (one `every` job, 2 s, while started), for a server
7
+ * `AreaStream` that follows reported cells (`followReported`). Create once at module level.
8
+ */
9
+ export class AreaFollower {
10
+ private cell = "";
11
+ private readonly job = every(2000, () => this.check(), {
12
+ active: false,
13
+ name: "areaFollower",
14
+ });
15
+
16
+ /** `event` gets `(cx, cy)`; `cellSize` must match the server stream's. */
17
+ constructor(
18
+ private readonly event: string,
19
+ private readonly cellSize = 64,
20
+ ) {}
21
+
22
+ /** Sends the cell now and on every change. */
23
+ start(): void {
24
+ this.cell = "";
25
+ this.check();
26
+ this.job.set(true);
27
+ }
28
+
29
+ stop(): void {
30
+ this.job.set(false);
31
+ }
32
+
33
+ private check(): void {
34
+ const [x = 0, y = 0] = GetEntityCoords(cache.ped, false);
35
+ const { cx, cy } = gridCell(x, y, this.cellSize);
36
+ const key = `${cx}:${cy}`;
37
+ if (key === this.cell) return;
38
+ this.cell = key;
39
+ emitNet(this.event, cx, cy);
40
+ }
41
+ }
@@ -0,0 +1,79 @@
1
+ /** Map blips with a name, kept per id so a script can rebuild them when its panel data changes. */
2
+
3
+ interface Vec3 {
4
+ x: number;
5
+ y: number;
6
+ z: number;
7
+ }
8
+
9
+ export interface BlipOptions {
10
+ coords: Vec3;
11
+ /** Shown in the map legend (already translated); without it the game's default name for the sprite. */
12
+ label?: string;
13
+ sprite: number;
14
+ color: number;
15
+ /** Default 0.8. */
16
+ scale?: number;
17
+ /** Only on the minimap when close (default true). */
18
+ shortRange?: boolean;
19
+ /** `SetBlipDisplay` (default 4: map and minimap). */
20
+ display?: number;
21
+ /** A GPS route to the blip: true in the game's route colour, a number for that route colour. */
22
+ route?: boolean | number;
23
+ }
24
+
25
+ import type { BlipStyle } from "../shared/blipStyle";
26
+
27
+ export type { BlipStyle };
28
+
29
+ const LABEL = `AI_BLIP_${GetCurrentResourceName()}`;
30
+ AddTextEntry(LABEL, "~a~");
31
+
32
+ /** Creates a named blip at a point and returns its handle (`RemoveBlip` it, or use `Blips`). */
33
+ export function createBlip(options: BlipOptions): number {
34
+ const { x, y, z } = options.coords;
35
+ const blip = AddBlipForCoord(x, y, z);
36
+ SetBlipSprite(blip, options.sprite);
37
+ SetBlipColour(blip, options.color);
38
+ SetBlipScale(blip, options.scale ?? 0.8);
39
+ SetBlipDisplay(blip, options.display ?? 4);
40
+ SetBlipAsShortRange(blip, options.shortRange ?? true);
41
+ if (options.label !== undefined) {
42
+ BeginTextCommandSetBlipName(LABEL);
43
+ AddTextComponentSubstringPlayerName(options.label);
44
+ EndTextCommandSetBlipName(blip);
45
+ }
46
+ if (options.route !== undefined && options.route !== false) {
47
+ SetBlipRoute(blip, true);
48
+ if (options.route !== true) SetBlipRouteColour(blip, options.route);
49
+ }
50
+ return blip;
51
+ }
52
+
53
+ /** A script's blips by id: `add` replaces a blip with the same id, `clear` removes them all (a panel rebuild). */
54
+ export class Blips {
55
+ private readonly blips = new Map<string, number>();
56
+
57
+ add(id: string, options: BlipOptions): number {
58
+ this.remove(id);
59
+ const blip = createBlip(options);
60
+ this.blips.set(id, blip);
61
+ return blip;
62
+ }
63
+
64
+ get(id: string): number | undefined {
65
+ return this.blips.get(id);
66
+ }
67
+
68
+ remove(id: string): void {
69
+ const blip = this.blips.get(id);
70
+ if (blip === undefined) return;
71
+ RemoveBlip(blip);
72
+ this.blips.delete(id);
73
+ }
74
+
75
+ clear(): void {
76
+ for (const blip of this.blips.values()) RemoveBlip(blip);
77
+ this.blips.clear();
78
+ }
79
+ }
@@ -0,0 +1,66 @@
1
+ import { CORE, type PlayerCache } from "@aifivem/shared";
2
+
3
+ /** The unarmed "weapon" hash: cached as `false`. */
4
+ const UNARMED = GetHashKey("WEAPON_UNARMED") | 0;
5
+
6
+ /** The weapon in a ped's hand, `false` when unarmed. */
7
+ export function readWeapon(ped: number): number | false {
8
+ const weapon = GetSelectedPedWeapon(ped) | 0;
9
+ return weapon === UNARMED ? false : weapon;
10
+ }
11
+
12
+ /** The vehicle, seat and weapon of a ped right now (also ai-core's watcher). */
13
+ export function readPlayerState(
14
+ ped: number,
15
+ ): Pick<PlayerCache, "vehicle" | "seat" | "weapon"> {
16
+ const vehicle = GetVehiclePedIsIn(ped, false);
17
+ let seat: number | false = false;
18
+ if (vehicle) {
19
+ for (let i = -1; i < GetVehicleMaxNumberOfPassengers(vehicle); i++) {
20
+ if (GetPedInVehicleSeat(vehicle, i) !== ped) continue;
21
+ seat = i;
22
+ break;
23
+ }
24
+ }
25
+ return { vehicle: vehicle || false, seat, weapon: readWeapon(ped) };
26
+ }
27
+
28
+ /**
29
+ * The local player's often read values (ped, player id, server id, vehicle, seat, weapon), like ox_lib's `cache`:
30
+ * read `cache.ped` instead of calling PlayerPedId() in loops. One watcher in ai-core updates every resource through
31
+ * a local event, so no resource polls for these itself. Read only.
32
+ */
33
+ const ped = PlayerPedId();
34
+ export const cache: PlayerCache = {
35
+ ped,
36
+ playerId: PlayerId(),
37
+ serverId: GetPlayerServerId(PlayerId()),
38
+ ...readPlayerState(ped),
39
+ };
40
+
41
+ type Handler = (value: unknown, old: unknown) => void;
42
+ const handlers = new Map<string, Set<Handler>>();
43
+
44
+ const valid = (key: keyof PlayerCache, value: unknown): boolean =>
45
+ key === "ped" || key === "playerId" || key === "serverId"
46
+ ? typeof value === "number"
47
+ : typeof value === "number" || value === false;
48
+
49
+ on(CORE.clientCacheEvent, (key: unknown, value: unknown) => {
50
+ if (typeof key !== "string" || !(key in cache)) return;
51
+ const name = key as keyof PlayerCache;
52
+ if (!valid(name, value) || cache[name] === value) return;
53
+ const old = cache[name];
54
+ (cache as unknown as Record<string, unknown>)[name] = value;
55
+ for (const handler of handlers.get(name) ?? []) handler(value, old);
56
+ });
57
+
58
+ /** Runs `handler(value, old)` whenever a cached value changes (entering a vehicle, a new ped after a model swap...). */
59
+ export function onCache<K extends keyof PlayerCache>(
60
+ key: K,
61
+ handler: (value: PlayerCache[K], old: PlayerCache[K]) => void,
62
+ ): void {
63
+ let set = handlers.get(key);
64
+ if (!set) handlers.set(key, (set = new Set()));
65
+ set.add(handler as Handler);
66
+ }
@@ -0,0 +1,70 @@
1
+ import {
2
+ DEFAULT_CALLBACK_TIMEOUT,
3
+ requestEvent,
4
+ responseEvent,
5
+ } from "../fivem/callbackNames";
6
+ import { createLogger } from "../shared";
7
+ import { fromServer } from "./netEvent";
8
+
9
+ const resource = GetCurrentResourceName();
10
+ const log = createLogger(resource);
11
+
12
+ interface Pending {
13
+ resolve: (value: unknown) => void;
14
+ reject: (error: Error) => void;
15
+ timer: ReturnType<typeof setTimeout>;
16
+ }
17
+
18
+ const pending = new Map<number, Pending>();
19
+ let nextId = 0;
20
+
21
+ onNet(responseEvent(resource), (id: unknown, ok: unknown, result: unknown) => {
22
+ if (!fromServer()) return;
23
+ const entry = typeof id === "number" ? pending.get(id) : undefined;
24
+ if (!entry) return;
25
+ pending.delete(id as number);
26
+ clearTimeout(entry.timer);
27
+ if (ok === true) entry.resolve(result);
28
+ else entry.reject(new Error("server callback failed"));
29
+ });
30
+
31
+ /**
32
+ * Asks the server (`onClientCallback(name, ...)` there) and resolves with its answer. The answer is unknown:
33
+ * parse it. Rejects when the server reports an error or does not answer within `timeoutMs`.
34
+ */
35
+ export function triggerServerCallback(
36
+ name: string,
37
+ args: unknown[] = [],
38
+ timeoutMs = DEFAULT_CALLBACK_TIMEOUT,
39
+ ): Promise<unknown> {
40
+ const id = ++nextId;
41
+ return new Promise((resolve, reject) => {
42
+ const timer = setTimeout(() => {
43
+ pending.delete(id);
44
+ reject(new Error(`server callback ${name} timed out`));
45
+ }, timeoutMs);
46
+ pending.set(id, { resolve, reject, timer });
47
+ emitNet(requestEvent(name), resource, id, ...args);
48
+ });
49
+ }
50
+
51
+ /** Answers the server's `triggerClientCallback(name, source, ...)`. Arguments are unknown: parse before use. */
52
+ export function onServerCallback(
53
+ name: string,
54
+ handler: (...args: unknown[]) => unknown,
55
+ ): void {
56
+ onNet(
57
+ requestEvent(name),
58
+ async (caller: unknown, id: unknown, ...args: unknown[]) => {
59
+ if (!fromServer() || typeof caller !== "string" || typeof id !== "number")
60
+ return;
61
+ try {
62
+ const result = await handler(...args);
63
+ emitNet(responseEvent(caller), id, true, result ?? null);
64
+ } catch (error) {
65
+ log.error(`callback ${name} failed`, error);
66
+ emitNet(responseEvent(caller), id, false, null);
67
+ }
68
+ },
69
+ );
70
+ }
@@ -0,0 +1,73 @@
1
+ import { TickLoop } from "./tickLoop";
2
+
3
+ /**
4
+ * Disabled controls of this resource, one per-frame job for all of them: each reason (`cuffed`, `seatbelt`, `menu`)
5
+ * adds its controls and removes them when it ends; the job runs only while any reason is active.
6
+ */
7
+ class Controls {
8
+ private readonly sets = new Map<
9
+ string,
10
+ { group: number; controls: readonly number[] }
11
+ >();
12
+ /** Reasons that disable every control, each with the controls it keeps. */
13
+ private readonly all = new Map<string, readonly number[]>();
14
+ /** Flat [group, control, group, control...] of every active reason, rebuilt on change (nothing allocated per frame). */
15
+ private flat: number[] = [];
16
+ /** Controls every `disableAll` reason keeps (and no `disable` reason takes). */
17
+ private kept: number[] = [];
18
+ private readonly tick = new TickLoop(() => {
19
+ if (this.all.size > 0) {
20
+ DisableAllControlActions(0);
21
+ DisableAllControlActions(1);
22
+ DisableAllControlActions(2);
23
+ const kept = this.kept;
24
+ for (let i = 0; i < kept.length; i++)
25
+ EnableControlAction(0, kept[i] ?? 0, true);
26
+ }
27
+ const flat = this.flat;
28
+ for (let i = 0; i < flat.length; i += 2)
29
+ DisableControlAction(flat[i] ?? 0, flat[i + 1] ?? 0, true);
30
+ });
31
+
32
+ /** Disables `controls` (in input group `group`, default 0) every frame until `enable(reason)`. */
33
+ disable(reason: string, controls: readonly number[], group = 0): void {
34
+ this.sets.set(reason, { group, controls });
35
+ this.rebuild();
36
+ }
37
+
38
+ /**
39
+ * Disables every control (input groups 0-2) every frame until `enable(reason)`, except `except` (group 0: camera
40
+ * look, push to talk...). Read the disabled ones with `IsDisabledControlPressed` (noclip, free camera).
41
+ */
42
+ disableAll(reason: string, except: readonly number[] = []): void {
43
+ this.all.set(reason, except);
44
+ this.rebuild();
45
+ }
46
+
47
+ enable(reason: string): void {
48
+ const a = this.sets.delete(reason);
49
+ const b = this.all.delete(reason);
50
+ if (a || b) this.rebuild();
51
+ }
52
+
53
+ isDisabled(reason: string): boolean {
54
+ return this.sets.has(reason) || this.all.has(reason);
55
+ }
56
+
57
+ private rebuild(): void {
58
+ this.flat = [];
59
+ const taken = new Set<number>();
60
+ for (const { group, controls } of this.sets.values())
61
+ for (const c of controls) {
62
+ this.flat.push(group, c);
63
+ if (group === 0) taken.add(c);
64
+ }
65
+ const lists = [...this.all.values()];
66
+ this.kept = (lists[0] ?? []).filter(
67
+ (c) => !taken.has(c) && lists.every((list) => list.includes(c)),
68
+ );
69
+ this.tick.set(this.flat.length > 0 || this.all.size > 0);
70
+ }
71
+ }
72
+
73
+ export const controls = new Controls();
@@ -0,0 +1,83 @@
1
+ import type { Vec3 } from "../shared/vec";
2
+ import { cache } from "./cache";
3
+
4
+ /** A game entity pool (`GetGamePool`). */
5
+ export type EntityKind = "ped" | "object" | "vehicle";
6
+
7
+ const POOLS: Record<EntityKind, string> = {
8
+ ped: "CPed",
9
+ object: "CObject",
10
+ vehicle: "CVehicle",
11
+ };
12
+
13
+ /** The closest entity and its distance in metres. */
14
+ export interface NearestEntity {
15
+ entity: number;
16
+ distance: number;
17
+ }
18
+
19
+ /**
20
+ * The closest ped / object / vehicle to `from` (default the local ped) within `maxDistance` (default no limit) that
21
+ * passes `filter`, with its distance; null when none. Peds skip the local ped unless `ignoreLocal: false`. Every
22
+ * entity of the pool, local ones included; one `GetGamePool` walk per call (for actions, not ticks).
23
+ */
24
+ export function nearestEntity(
25
+ kind: EntityKind,
26
+ from?: Vec3,
27
+ maxDistance = Infinity,
28
+ options: { filter?: (entity: number) => boolean; ignoreLocal?: boolean } = {},
29
+ ): NearestEntity | null {
30
+ let x: number;
31
+ let y: number;
32
+ let z: number;
33
+ if (from) ({ x, y, z } = from);
34
+ else [x = 0, y = 0, z = 0] = GetEntityCoords(cache.ped, false);
35
+ const skip = kind === "ped" && options.ignoreLocal !== false ? cache.ped : 0;
36
+ const { filter } = options;
37
+ let best = 0;
38
+ let bestSq = maxDistance * maxDistance;
39
+ for (const entity of GetGamePool(POOLS[kind]) as number[]) {
40
+ if (entity === skip) continue;
41
+ const [ex = 0, ey = 0, ez = 0] = GetEntityCoords(entity, false);
42
+ const dx = ex - x;
43
+ const dy = ey - y;
44
+ const dz = ez - z;
45
+ const sq = dx * dx + dy * dy + dz * dz;
46
+ if (sq < bestSq && (!filter || filter(entity))) {
47
+ best = entity;
48
+ bestSq = sq;
49
+ }
50
+ }
51
+ return best ? { entity: best, distance: Math.sqrt(bestSq) } : null;
52
+ }
53
+
54
+ /** Every ped / object / vehicle within `radius` metres of `coords` (the local ped included); one pool walk. */
55
+ export function entitiesInArea(
56
+ kind: EntityKind,
57
+ coords: Vec3,
58
+ radius: number,
59
+ ): number[] {
60
+ const out: number[] = [];
61
+ const max = radius * radius;
62
+ for (const entity of GetGamePool(POOLS[kind]) as number[]) {
63
+ const [ex = 0, ey = 0, ez = 0] = GetEntityCoords(entity, false);
64
+ const dx = ex - coords.x;
65
+ const dy = ey - coords.y;
66
+ const dz = ez - coords.z;
67
+ if (dx * dx + dy * dy + dz * dz <= max) out.push(entity);
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /** No vehicle stands within `radius` metres of `coords` (a spawn spot is free); stops at the first one found. */
73
+ export function isSpawnClear(coords: Vec3, radius: number): boolean {
74
+ const max = radius * radius;
75
+ for (const vehicle of GetGamePool("CVehicle") as number[]) {
76
+ const [vx = 0, vy = 0, vz = 0] = GetEntityCoords(vehicle, false);
77
+ const dx = vx - coords.x;
78
+ const dy = vy - coords.y;
79
+ const dz = vz - coords.z;
80
+ if (dx * dx + dy * dy + dz * dz <= max) return false;
81
+ }
82
+ return true;
83
+ }
@@ -0,0 +1,26 @@
1
+ import { waitFor } from "../shared/wait";
2
+
3
+ /** The local entity of a network id once it exists on this client, or 0 after `timeoutMs` (default 5 s). */
4
+ export async function waitForEntity(
5
+ netId: number,
6
+ timeoutMs = 5000,
7
+ ): Promise<number> {
8
+ return waitFor(
9
+ () =>
10
+ NetworkDoesEntityExistWithNetworkId(netId)
11
+ ? NetToEnt(netId) || undefined
12
+ : undefined,
13
+ timeoutMs,
14
+ ).catch(() => 0);
15
+ }
16
+
17
+ /**
18
+ * The local entity of a network id right now, or 0 (not on this client, or not of `type`: 1 ped, 2 vehicle, 3 object;
19
+ * any type when omitted).
20
+ */
21
+ export function entityFromNetId(netId: number, type?: 1 | 2 | 3): number {
22
+ if (!NetworkDoesEntityExistWithNetworkId(netId)) return 0;
23
+ const entity = NetToEnt(netId);
24
+ if (!entity) return 0;
25
+ return type === undefined || GetEntityType(entity) === type ? entity : 0;
26
+ }
@@ -0,0 +1,18 @@
1
+ import { VEHICLE_BAGS } from "@aifivem/shared";
2
+ import { EntityState } from "../fivem/state/entityState";
3
+ import { stateNumber } from "../fivem/state/mirror";
4
+
5
+ /** The `fuel` bag mirror, made on first use: a resource that never reads fuel adds no state bag handler. */
6
+ let bag: EntityState<number> | null = null;
7
+
8
+ /**
9
+ * A vehicle's fuel on the client through ai-core's fuel layer: the server keeps the `fuel` bag for every fuel script
10
+ * (a mirror for scripts that live on clients), so this is a memory read; the game's tank level without one.
11
+ */
12
+ export const fuel = {
13
+ /** 0-100 for a vehicle this client knows. */
14
+ get(vehicle: number): number {
15
+ bag ??= new EntityState(VEHICLE_BAGS.fuel, stateNumber);
16
+ return bag.get(vehicle) ?? GetVehicleFuelLevel(vehicle);
17
+ },
18
+ };