@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
@@ -0,0 +1,127 @@
1
+ import type { AdminPatch, DataSpec, FileSpec } from "@aifivem/shared";
2
+ import { isRecord } from "../../shared";
3
+ import { clone } from "./patch";
4
+ import { ERR, validate } from "./validate";
5
+
6
+ type Data = Record<string, unknown>;
7
+ /** A patch that edits data (every kind but an action button's `run`). */
8
+ export type EditPatch = Exclude<AdminPatch, { action: "run" }>;
9
+ /** Cross-field check on the value about to be stored: a lang key refuses it. */
10
+ export type Rule = (key: string | undefined, next: Data) => string | null;
11
+
12
+ /** What the edit checks read of the panel: a file's content and its rule. */
13
+ export interface EditContext {
14
+ get(file: string): Data;
15
+ rule(file: string): Rule | undefined;
16
+ }
17
+
18
+ const DEFAULT_KEY = "^[a-z0-9_]{2,32}$";
19
+
20
+ /** An imported record: only the file's sections, a section it lacks taken from the new-record template. */
21
+ function imported(spec: FileSpec, value: Data): Data {
22
+ const base = clone(spec.newRecord ?? {});
23
+ const out: Data = {};
24
+ for (const name of Object.keys(spec.sections)) {
25
+ const v = name in value ? value[name] : base[name];
26
+ if (v !== undefined) out[name] = clone(v);
27
+ }
28
+ return out;
29
+ }
30
+
31
+ /** A text section with `records` must name a record of that file of this panel (or be empty). */
32
+ function linked(
33
+ spec: DataSpec,
34
+ value: unknown,
35
+ ctx: EditContext,
36
+ ): string | null {
37
+ return spec.type === "text" &&
38
+ spec.records &&
39
+ typeof value === "string" &&
40
+ value !== "" &&
41
+ !(value in ctx.get(spec.records))
42
+ ? "ADMIN_ERR_LOOKUP"
43
+ : null;
44
+ }
45
+
46
+ /** The refusal (a lang key) of a panel edit: key pattern, existence, lock, validation, links, the file's rule; null = ok. */
47
+ export function checkEdit(
48
+ patch: EditPatch,
49
+ spec: FileSpec,
50
+ ctx: EditContext,
51
+ ): string | null {
52
+ const data = ctx.get(patch.file);
53
+ if (patch.action === "create") {
54
+ if (
55
+ spec.kind !== "records" ||
56
+ !new RegExp(spec.keyPattern ?? DEFAULT_KEY).test(patch.key)
57
+ )
58
+ return ERR.pattern;
59
+ if (patch.key in data) return "ADMIN_ERR_EXISTS";
60
+ return null;
61
+ }
62
+ if (patch.action === "delete") {
63
+ if (spec.kind !== "records" || !(patch.key in data)) return ERR.type;
64
+ return spec.locked?.includes(patch.key) ? "ADMIN_ERR_LOCKED" : null;
65
+ }
66
+ if (patch.action === "import") {
67
+ if (spec.kind !== "records") return ERR.type;
68
+ const pattern = new RegExp(spec.keyPattern ?? DEFAULT_KEY);
69
+ for (const [key, value] of Object.entries(patch.records)) {
70
+ if (!pattern.test(key)) return ERR.pattern;
71
+ const record = imported(spec, value);
72
+ for (const [name, section] of Object.entries(spec.sections)) {
73
+ const refusal = validate(section, record[name], name);
74
+ if (refusal) return refusal.error;
75
+ const link = linked(section, record[name], ctx);
76
+ if (link) return link;
77
+ }
78
+ const ruled = ctx.rule(patch.file)?.(key, record);
79
+ if (ruled) return ruled;
80
+ }
81
+ return null;
82
+ }
83
+ const section = spec.sections[patch.section];
84
+ if (!section) return ERR.type;
85
+ if (spec.kind === "records" && (!patch.key || !(patch.key in data)))
86
+ return ERR.type;
87
+ const refusal = validate(section, patch.value, patch.section);
88
+ if (refusal) return refusal.error;
89
+ const link = linked(section, patch.value, ctx);
90
+ if (link) return link;
91
+ const current = spec.kind === "records" ? data[patch.key ?? ""] : data;
92
+ const next = {
93
+ ...(isRecord(current) ? current : {}),
94
+ [patch.section]: patch.value,
95
+ };
96
+ return ctx.rule(patch.file)?.(patch.key, next) ?? null;
97
+ }
98
+
99
+ /**
100
+ * Applies a checked edit to a file's data in place. Answers the changed keys (records) or `[undefined]` (settings);
101
+ * empty when nothing changed.
102
+ */
103
+ export function applyEdit(
104
+ data: Data,
105
+ patch: EditPatch,
106
+ spec: FileSpec,
107
+ ): Array<string | undefined> {
108
+ if (patch.action === "import") {
109
+ for (const [key, value] of Object.entries(patch.records))
110
+ data[key] = imported(spec, value);
111
+ return Object.keys(patch.records);
112
+ }
113
+ if (patch.action === "create") {
114
+ const record = clone(spec.newRecord ?? {});
115
+ if (spec.labelPath) record[spec.labelPath] = patch.label;
116
+ data[patch.key] = record;
117
+ } else if (patch.action === "delete") {
118
+ delete data[patch.key];
119
+ } else {
120
+ const target = spec.kind === "records" ? data[patch.key ?? ""] : data;
121
+ if (!isRecord(target)) return [];
122
+ if (patch.value === undefined || patch.value === null)
123
+ delete target[patch.section];
124
+ else target[patch.section] = clone(patch.value);
125
+ }
126
+ return [spec.kind === "records" ? patch.key : undefined];
127
+ }
@@ -0,0 +1,156 @@
1
+ import type { DataSpec, FileSpec, PanelSchema } from "@aifivem/shared";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import type { Logger } from "../../shared";
4
+ import { describe, texts, type Descriptions } from "./descriptions";
5
+
6
+ /**
7
+ * JSON Schemas of a script's panel files (draft-07), so an editor validates and explains `data/*.json` while someone
8
+ * edits it by hand: types, limits, enums and patterns from the panel's data specs, descriptions from the panel's
9
+ * labels and hints in the script's `locales/en.json`. Written to `data/schemas/<file>.schema.json`.
10
+ */
11
+
12
+ type Json = Record<string, unknown>;
13
+
14
+ const SCHEMA_KEY = {
15
+ type: "string",
16
+ description: "This file's JSON Schema (for editors).",
17
+ };
18
+
19
+ function toJson(spec: DataSpec, path: string, desc: Descriptions): Json {
20
+ const description = desc.get(path);
21
+ const base: Json = description ? { description } : {};
22
+ switch (spec.type) {
23
+ case "text":
24
+ return {
25
+ ...base,
26
+ type: "string",
27
+ minLength: spec.min,
28
+ maxLength: spec.max,
29
+ pattern: spec.pattern,
30
+ };
31
+ case "number":
32
+ return {
33
+ ...base,
34
+ type: spec.integer ? "integer" : "number",
35
+ minimum: spec.min,
36
+ maximum: spec.max,
37
+ };
38
+ case "bool":
39
+ return { ...base, type: "boolean" };
40
+ case "enum":
41
+ return { ...base, enum: spec.values };
42
+ case "names":
43
+ return {
44
+ ...base,
45
+ type: "array",
46
+ maxItems: spec.max,
47
+ uniqueItems: true,
48
+ items: {
49
+ type: "string",
50
+ maxLength: spec.itemMax,
51
+ pattern: spec.pattern,
52
+ },
53
+ };
54
+ case "vec3":
55
+ case "vec4": {
56
+ const keys =
57
+ spec.type === "vec3" ? ["x", "y", "z"] : ["x", "y", "z", "heading"];
58
+ return {
59
+ ...base,
60
+ type: "object",
61
+ required: keys,
62
+ properties: Object.fromEntries(
63
+ keys.map((k) => [k, { type: "number" }]),
64
+ ),
65
+ };
66
+ }
67
+ case "object":
68
+ return {
69
+ ...base,
70
+ ...objectOf(spec.fields, path ? `${path}.` : "", desc),
71
+ };
72
+ case "list":
73
+ return {
74
+ ...base,
75
+ type: "array",
76
+ minItems: spec.min,
77
+ maxItems: spec.max,
78
+ items: toJson(spec.of, `${path}[]`, desc),
79
+ };
80
+ default: {
81
+ const _exhaustive: never = spec;
82
+ return _exhaustive;
83
+ }
84
+ }
85
+ }
86
+
87
+ function objectOf(
88
+ fields: Record<string, DataSpec>,
89
+ prefix: string,
90
+ desc: Descriptions,
91
+ ): Json {
92
+ return {
93
+ type: "object",
94
+ properties: Object.fromEntries(
95
+ Object.entries(fields).map(([k, s]) => [k, toJson(s, prefix + k, desc)]),
96
+ ),
97
+ required: Object.entries(fields)
98
+ .filter(([, s]) => !s.optional)
99
+ .map(([k]) => k),
100
+ };
101
+ }
102
+
103
+ /** The schema of one panel file as JSON text (stable, so an unchanged schema is not written again). */
104
+ export function fileSchema(
105
+ resource: string,
106
+ schema: PanelSchema,
107
+ name: string,
108
+ spec: FileSpec,
109
+ ): string {
110
+ const desc = describe(schema, name, texts(resource));
111
+ const title = `${resource}/data/${name}.json`;
112
+ const body: Json =
113
+ spec.kind === "settings"
114
+ ? (() => {
115
+ const obj = objectOf(spec.sections, "", desc);
116
+ // Sections with defaults are filled at load: a hand-written file may leave them out.
117
+ const required = (obj.required as string[]).filter(
118
+ (k) => !(k in (spec.defaults ?? {})),
119
+ );
120
+ return {
121
+ ...obj,
122
+ properties: { $schema: SCHEMA_KEY, ...(obj.properties as Json) },
123
+ required,
124
+ };
125
+ })()
126
+ : {
127
+ type: "object",
128
+ properties: { $schema: SCHEMA_KEY },
129
+ patternProperties: {
130
+ [spec.keyPattern ?? "^[a-z0-9_]{2,32}$"]: objectOf(
131
+ spec.sections,
132
+ "",
133
+ desc,
134
+ ),
135
+ },
136
+ additionalProperties: false,
137
+ };
138
+ return `${JSON.stringify({ $schema: "http://json-schema.org/draft-07/schema#", title, ...body }, null, 2)}\n`;
139
+ }
140
+
141
+ /** Writes a schema file when its text changed (the server only writes inside its own resource). */
142
+ export function writeSchema(
143
+ resource: string,
144
+ name: string,
145
+ text: string,
146
+ log: Logger,
147
+ ): void {
148
+ const path = `data/schemas/${name}.schema.json`;
149
+ if (LoadResourceFile(resource, path) === text) return;
150
+ const dir = `${GetResourcePath(resource)}/data/schemas`;
151
+ void mkdir(dir, { recursive: true })
152
+ .then(() => writeFile(`${dir}/${name}.schema.json`, text, "utf8"))
153
+ .catch((error: unknown) =>
154
+ log.error(`writing ${resource}/${path} failed`, error),
155
+ );
156
+ }
@@ -0,0 +1,167 @@
1
+ import {
2
+ ADMIN,
3
+ CORE,
4
+ type AdminPanelSnapshot,
5
+ type AdminPatch,
6
+ type AdminResult,
7
+ type FileSpec,
8
+ type PanelSchema,
9
+ } from "@aifivem/shared";
10
+ import { isRecord, previewJson } from "../../shared";
11
+ import { registerExport, resourceExport } from "../../fivem/exports";
12
+ import { loadLocaleTexts } from "../../fivem/locale";
13
+ import { onClientCallback } from "../callback";
14
+ import { checkEdit, type Rule } from "./edit";
15
+ import { clone, toPatch } from "./patch";
16
+ import { PanelFiles, type Data } from "./panelFiles";
17
+ import { ERR } from "./validate";
18
+
19
+ const core = resourceExport(CORE.resource);
20
+
21
+ /** An `action` widget's handler: a lang key refuses (shown under the button), null succeeds. */
22
+ type ActionHandler = (
23
+ admin: number,
24
+ record: Data,
25
+ key: string | undefined,
26
+ ) => string | null;
27
+
28
+ /**
29
+ * A resource's panel content: loads `data/<file>.json` once, keeps it in memory, validates every panel edit against
30
+ * the schema, saves it (atomic, debounced), tells its own code, ai-core (open panels) and, for `sync: "all"` files,
31
+ * every client. One instance per resource, created at start.
32
+ */
33
+ export class AdminPanel extends PanelFiles {
34
+ private readonly rules = new Map<string, Rule>();
35
+ private readonly actions = new Map<string, ActionHandler>();
36
+ /**
37
+ * The admin whose panel edit or action is being applied, readable in `rule`, `onChange` and `onAction` handlers;
38
+ * 0 for the resource's own `commit`. Set by the lib only.
39
+ */
40
+ editor = 0;
41
+
42
+ constructor(schema: PanelSchema) {
43
+ super(schema);
44
+ registerExport("AdminPanelSnapshot", () => this.snapshot());
45
+ registerExport("AdminPanelData", () => this.dataSnapshot());
46
+ registerExport("AdminPanelSummary", () => this.summary());
47
+ registerExport("AdminPanelApply", (admin: number, patch: unknown) =>
48
+ this.apply(admin, patch),
49
+ );
50
+ // Each client mirror asks once at its start (a resource may hold a few mirrors): a hostile client cannot pull the
51
+ // whole change set over and over.
52
+ onClientCallback(
53
+ ADMIN.worldChangesCallback(this.resource),
54
+ () => Object.fromEntries(this.worldChanges),
55
+ { rate: { count: 4, windowMs: 10_000 } },
56
+ );
57
+ // After every resource's exports exist (ai-core registers its own panel too).
58
+ setImmediate(() => core.RegisterAdminPanel(this.resource));
59
+ }
60
+
61
+ rule(file: string, rule: Rule): void {
62
+ this.rules.set(file, rule);
63
+ }
64
+
65
+ /** Runs when an admin presses the `action` widget whose `path` is `id` (on a record, or the settings object). */
66
+ onAction(id: string, handler: ActionHandler): void {
67
+ this.actions.set(id, handler);
68
+ }
69
+
70
+ snapshot(): AdminPanelSnapshot {
71
+ return {
72
+ resource: this.resource,
73
+ schema: this.schema,
74
+ texts: loadLocaleTexts(),
75
+ data: this.dataSnapshot(),
76
+ };
77
+ }
78
+
79
+ /** Every file's content without schema and texts (the panel already has them from `summary()`). */
80
+ dataSnapshot(): Data {
81
+ return clone(Object.fromEntries(this.data));
82
+ }
83
+
84
+ /**
85
+ * What the panel needs at opening: schema, texts, the settings files and each records file's labels by key (for the
86
+ * global search). The records themselves come with `snapshot()` when the admin opens this script.
87
+ */
88
+ summary(): AdminPanelSnapshot {
89
+ const data: Data = {};
90
+ const index: Record<string, Record<string, string>> = {};
91
+ for (const [file, spec] of Object.entries(this.schema.files)) {
92
+ const content = this.data.get(file);
93
+ if (spec.kind !== "records") {
94
+ data[file] = clone(content ?? {});
95
+ continue;
96
+ }
97
+ const labels: Record<string, string> = {};
98
+ for (const [key, record] of Object.entries(content ?? {}))
99
+ labels[key] = labelOf(record, spec.labelPath) ?? key;
100
+ index[file] = labels;
101
+ }
102
+ return {
103
+ resource: this.resource,
104
+ schema: this.schema,
105
+ texts: loadLocaleTexts(),
106
+ data,
107
+ loaded: false,
108
+ index,
109
+ };
110
+ }
111
+
112
+ /** A panel edit (ai-core checked the admin and the rate): validate, store, save, announce. */
113
+ apply(admin: number, raw: unknown): AdminResult {
114
+ const patch = toPatch(raw);
115
+ const spec = patch ? this.schema.files[patch.file] : undefined;
116
+ if (!patch || !spec) return { ok: false, error: ERR.type };
117
+ this.editor = admin;
118
+ try {
119
+ if (patch.action === "run") return this.run(admin, patch, spec);
120
+ if (spec.memory) return { ok: false, error: ERR.type };
121
+ const error = checkEdit(patch, spec, {
122
+ get: (file) => this.get(file),
123
+ rule: (file) => this.rules.get(file),
124
+ });
125
+ if (error) {
126
+ this.log.warn(
127
+ `admin ${admin} edit refused (${error}): ${previewJson(patch, 300)}`,
128
+ );
129
+ return { ok: false, error };
130
+ }
131
+ this.store(patch, spec);
132
+ return { ok: true };
133
+ } finally {
134
+ this.editor = 0;
135
+ }
136
+ }
137
+
138
+ /** An `action` widget pressed: the script's handler decides; nothing is stored here. */
139
+ private run(
140
+ admin: number,
141
+ patch: Extract<AdminPatch, { action: "run" }>,
142
+ spec: FileSpec,
143
+ ): AdminResult {
144
+ const handler = this.actions.get(patch.id);
145
+ const data = this.get(patch.file);
146
+ const target = spec.kind === "records" ? data[patch.key ?? ""] : data;
147
+ if (!handler || !isRecord(target)) return { ok: false, error: ERR.type };
148
+ try {
149
+ const error = handler(admin, clone(target), patch.key);
150
+ return error ? { ok: false, error } : { ok: true };
151
+ } catch (error) {
152
+ this.log.error(`panel action ${patch.id} failed`, error);
153
+ return { ok: false, error: ERR.type };
154
+ }
155
+ }
156
+ }
157
+
158
+ /** A record's label at a dotted path (`labelPath`), when it is a text. */
159
+ function labelOf(record: unknown, path: string | undefined): string | null {
160
+ if (!path) return null;
161
+ let at: unknown = record;
162
+ for (const part of path.split(".")) {
163
+ if (typeof at !== "object" || at === null) return null;
164
+ at = (at as Record<string, unknown>)[part];
165
+ }
166
+ return typeof at === "string" && at !== "" ? at : null;
167
+ }
@@ -0,0 +1,128 @@
1
+ import {
2
+ ADMIN,
3
+ CORE,
4
+ type FileSpec,
5
+ type PanelSchema,
6
+ } from "@aifivem/shared";
7
+ import { createLogger, isRecord, type Logger } from "../../shared";
8
+ import { FileViews, type RecordReader } from "../../shared/records";
9
+ import { resourceExport } from "../../fivem/exports";
10
+ import { DataFile } from "../dataFile";
11
+ import { applyEdit, type EditPatch } from "./edit";
12
+ import { clone } from "./patch";
13
+ import { fileSchema, writeSchema } from "./jsonSchema";
14
+
15
+ const core = resourceExport(CORE.resource);
16
+
17
+ export type Data = Record<string, unknown>;
18
+ /** A record changed (records: its key; settings: no key); `null` = deleted. */
19
+ type ChangeHandler = (key: string | undefined, value: unknown) => void;
20
+
21
+ /** The files of a resource's panel: loaded once, kept in memory, saved on change, announced to code, panels and clients. */
22
+ export class PanelFiles {
23
+ protected readonly data = new Map<string, Data>();
24
+ private readonly dataFiles = new Map<string, DataFile>();
25
+ private readonly handlers = new Map<string, ChangeHandler[]>();
26
+ private readonly views = new FileViews((file) => this.get(file));
27
+ /** World files: records changed since start, for clients that read the file FiveM cached at start. */
28
+ protected readonly worldChanges = new Map<string, Data>();
29
+ protected readonly resource = GetCurrentResourceName();
30
+ protected readonly log: Logger = createLogger(this.resource);
31
+
32
+ constructor(protected readonly schema: PanelSchema) {
33
+ for (const [name, spec] of Object.entries(schema.files))
34
+ this.load(name, spec);
35
+ }
36
+
37
+ /** The current content of a file: the settings object, or `{ key: record }`. Read only. */
38
+ get<T = Data>(file: string): T {
39
+ return (this.data.get(file) ?? {}) as T;
40
+ }
41
+
42
+ onChange(file: string, handler: ChangeHandler): void {
43
+ this.handlers.set(file, [...(this.handlers.get(file) ?? []), handler]);
44
+ }
45
+
46
+ /** A file parsed by `read`, kept current on every change (settings files; parsed before `onChange` handlers run). */
47
+ view<T>(file: string, read: (raw: unknown) => T): { readonly value: T } {
48
+ return this.views.view(file, read);
49
+ }
50
+
51
+ /** A records file parsed per record through `readOne` (null leaves a record out); a change re-reads only that record. */
52
+ records<T>(file: string, readOne: RecordReader<T>): ReadonlyMap<string, T> {
53
+ return this.views.records(file, readOne);
54
+ }
55
+
56
+ /** A change made by the resource itself (game state the panel shows), stored without validation (a `memory` file only in memory). */
57
+ commit(file: string, key: string | undefined, value: unknown): void {
58
+ const data = this.data.get(file);
59
+ if (!data) return;
60
+ if (key === undefined) {
61
+ if (isRecord(value)) this.data.set(file, clone(value));
62
+ } else if (value === null) delete data[key];
63
+ else data[key] = clone(value);
64
+ this.changed(file, key);
65
+ }
66
+
67
+ /** `commit` after the current change has reached the panel (a form that resets itself after an admin sent it). */
68
+ commitAfter(file: string, key: string | undefined, value: unknown): void {
69
+ setImmediate(() => this.commit(file, key, value));
70
+ }
71
+
72
+ protected store(patch: EditPatch, spec: FileSpec): void {
73
+ const data = this.data.get(patch.file) ?? {};
74
+ const keys = applyEdit(data, patch, spec);
75
+ if (keys.length === 0) return;
76
+ this.data.set(patch.file, data);
77
+ for (const key of keys) this.changed(patch.file, key);
78
+ }
79
+
80
+ /** Save, then tell the resource's code, open panels and (world files) every client. */
81
+ private changed(file: string, key: string | undefined): void {
82
+ const spec = this.schema.files[file];
83
+ const data = this.get(file);
84
+ const value = key === undefined ? data : (data[key] ?? null);
85
+ this.dataFiles.get(file)?.write(data);
86
+ this.views.changed(file, key, value);
87
+ for (const handler of this.handlers.get(file) ?? []) handler(key, value);
88
+ core.AdminPanelChanged({
89
+ resource: this.resource,
90
+ file,
91
+ key,
92
+ value: clone(value),
93
+ });
94
+ if (spec?.sync !== "all") return;
95
+ const changes = this.worldChanges.get(file) ?? {};
96
+ changes[key ?? ""] = clone(value);
97
+ this.worldChanges.set(file, changes);
98
+ emitNet(ADMIN.worldEvent(this.resource), -1, file, key ?? null, value);
99
+ }
100
+
101
+ private load(name: string, spec: FileSpec): void {
102
+ if (spec.memory) {
103
+ this.data.set(name, {});
104
+ return;
105
+ }
106
+ const file = new DataFile(this.resource, name, this.log);
107
+ this.dataFiles.set(name, file);
108
+ file.schemaRef = `./schemas/${name}.schema.json`;
109
+ writeSchema(
110
+ this.resource,
111
+ name,
112
+ fileSchema(this.resource, this.schema, name, spec),
113
+ this.log,
114
+ );
115
+ const raw = file.read();
116
+ const data: Data = isRecord(raw) ? raw : {};
117
+ let filled = false;
118
+ if (spec.kind === "settings") {
119
+ for (const [section, value] of Object.entries(spec.defaults ?? {})) {
120
+ if (section in data) continue;
121
+ data[section] = clone(value);
122
+ filled = true;
123
+ }
124
+ }
125
+ this.data.set(name, data);
126
+ if (filled || raw === null || !file.hasSchemaRef()) file.write(data);
127
+ }
128
+ }
@@ -0,0 +1,46 @@
1
+ import type { AdminPatch } from "@aifivem/shared";
2
+ import { isRecord } from "../../shared";
3
+
4
+ /** A patch from a client: only the known shapes pass, extra fields drop. */
5
+ export function toPatch(value: unknown): AdminPatch | null {
6
+ if (!isRecord(value) || typeof value.file !== "string") return null;
7
+ const key = typeof value.key === "string" ? value.key : undefined;
8
+ switch (value.action) {
9
+ case "set":
10
+ return typeof value.section === "string"
11
+ ? {
12
+ file: value.file,
13
+ action: "set",
14
+ key,
15
+ section: value.section,
16
+ value: value.value,
17
+ }
18
+ : null;
19
+ case "create":
20
+ return key && typeof value.label === "string"
21
+ ? { file: value.file, action: "create", key, label: value.label }
22
+ : null;
23
+ case "delete":
24
+ return key ? { file: value.file, action: "delete", key } : null;
25
+ case "run":
26
+ return typeof value.id === "string" && value.id.length <= 64
27
+ ? { file: value.file, action: "run", key, id: value.id }
28
+ : null;
29
+ case "import": {
30
+ if (!isRecord(value.records)) return null;
31
+ const records: Record<string, Record<string, unknown>> = {};
32
+ for (const [k, v] of Object.entries(value.records))
33
+ if (isRecord(v)) records[k] = v;
34
+ return Object.keys(records).length > 0 &&
35
+ Object.keys(records).length <= 500
36
+ ? { file: value.file, action: "import", records }
37
+ : null;
38
+ }
39
+ default:
40
+ return null;
41
+ }
42
+ }
43
+
44
+ /** A deep copy through JSON: stored data never shares objects with a caller. */
45
+ export const clone = <T>(value: T): T =>
46
+ value === undefined ? value : (JSON.parse(JSON.stringify(value)) as T);