Skip to content

cc_lib — API and exports reference

Every public function cc_lib offers, by module. Lua resources load cc_lib with shared_script '@cc_lib/init.lua' and call CC..(...). Code that cannot load the init (JavaScript, C#, a vendor script you

Every public function cc_lib offers, by module. Lua resources load cc_lib with shared_script '@cc_lib/init.lua' and call CC..(...). Code that cannot load the init (JavaScript, C#, a vendor script you only want to touch once) uses the export surface at the end.

Side marks: server = server scripts only, client = client scripts only, unmarked = both. A server-only module called on the client raises a clear error instead of failing silently. Configuration is in CONFIG.md; which resources each module talks to is in COMPATIBILITY.md.

Contents: framework · inventory · money · security · callback · target · notify · progress · minigame · textui · menu · keys · fuel · vehicle · dispatch · phone · character · appearance · weather · garage · doorlock · logger · hooks · api · utilities · billing · boost · settings / locale · export surface · events

Lua API (CC.*)

CC is global inside any resource that loads @cc_lib/init.lua.

CC.framework

FunctionSideReturns
CC.framework.nameboth'esx' | 'qb' | 'qbox' | 'ox' | 'nd' | 'standalone'
CC.framework.getPlayer(src)servernormalised CCPlayer or nil
CC.framework.getIdentifier(src)serverstable per-character identifier
CC.framework.getJob(src) / getJob()server / client{ name, label, grade, gradeLabel, onDuty, isBoss }
CC.framework.hasJob(src, jobs, minGrade, requireDuty)serverboolean
CC.framework.hasGang(src, gangs, minGrade)serverboolean
CC.framework.getPlayers()serverCCPlayer[]
CC.framework.getPlayersByJob(job, onDutyOnly)serverCCPlayer[]
CC.framework.isDead(src)serverdead — not merely downed
CC.framework.isDowned(src)serverdead, or last stand / knocked out
CC.framework.isRestrained(src)servercuffed, ziptied, escorted or carried
CC.framework.getCharacterName(src)server'First Last', falling back to the account name; never nil
CC.framework.getPlayerByIdentifier(identifier)serverthe online CCPlayer with that character identifier, or nil (1.6.0)
CC.framework.getMetadata(src, key)servera value from the character's framework metadata (1.6.0)
CC.framework.setMetadata(src, key, value)serverboolean (1.6.0)
CC.framework.onPlayerLoaded(cb)server—
CC.framework.onJobChange(cb)both—
CC.framework.onReady(cb)clientfires once a character is loaded, and immediately on a live restart
CC.framework.getPlayerData()clientraw framework player data

Metadata (1.6.0) reads and writes the framework's own per-character store: qb/qbx PlayerData.metadata (GetMetaData / SetMetaData), ESX Legacy getMeta / setMeta, ox_core get / set, ND_Core getMetadata / setMetadata. With no framework it is a session-only table, dropped when the player leaves — persist it yourself if it must survive. A failure is logged and returns nil / false. Never write a key or value the client chose.

ND_Core (1.6.0) is the 2.x API: exports.ND_Core:getPlayer(src). The identifier is the character id; job/jobInfo.rank become job.name/job.grade; ND:characterLoaded drives onPlayerLoaded/onReady and a changed job in ND:updateCharacter drives onJobChange. ND has no gangs and no dirty-money account.

onReady (1.6.0) waits for a character for as long as it takes. 1.5 gave up after 60 s and fired every handler from the character-select screen.

A CCPlayer:

lua
{
    source     = 3,
    identifier = 'ABC12345',
    license    = 'license:110000112345678',
    name       = 'John Doe',
    firstname  = 'John',
    lastname   = 'Doe',
    job        = { name, label, grade, gradeLabel, onDuty, isBoss },
    gang       = { name, label, grade, isBoss },   -- nil on ESX/ox
    raw        = <the underlying framework object>
}

raw is deliberately exposed. The bridge covers 95% of cases; the escape hatch stops the last 5% from becoming a fork.

Always build world objects inside CC.framework.onReady, never at the top level of a client script. Top-level construction is why scripts "work until you restart them".

Dead, downed, restrained read everything the server can see:

Sourcedeaddowned (adds)restrained
Qbox / QBCore PlayerData.metadataisdeadinlaststandishandcuffed
Player state bags (ESX, ox_core, most death and cuff scripts)isDead, deadisDowned, downed, inLastStand, laststandisCuffed, cuffed, handcuffed, isHandcuffed, ziptied, isEscorted, escorted, isCarried, carried, beingCarried
The synced pedhealth ≤ 0—attached to another entity (escort and carry attach the ped)

Ped health alone is not enough: qb-ambulancejob and its forks resurrect the ped and play a "dead" animation, so a dead QB player has full health and only metadata.isdead says otherwise. esx_policejob keeps no server cuff state at all, so on ESX restraint comes from state bags only.

These are deny gates. A client that writes its own state bag can only refuse itself — except by clearing a flag a framework keeps only in a bag. Players can write their own player state bags unless the server sets setr sv_stateBagStrictMode true; recommend it.

CC.inventory — server unless noted

lua
CC.inventory.addItem(src, item, count, metadata, slot)   --> boolean
CC.inventory.removeItem(src, item, count, metadata, slot)--> boolean
CC.inventory.getItemCount(src, item, metadata)           --> number
CC.inventory.hasItem(src, item, count)                   --> boolean
CC.inventory.canCarry(src, item, count, metadata)        --> boolean
CC.inventory.getSlot(src, slot)                          --> { name, label, count, metadata, slot } | nil
CC.inventory.exchange(src, take, give)                   --> boolean  (atomic, rolls back)
CC.inventory.registerUsableItem(item, cb)

-- stashes
CC.inventory.secure                                      --> boolean
CC.inventory.registerStash(id, label, slots, weight, owner, opts) --> boolean
CC.inventory.openStash(src, id, label, slots, weight)    --> boolean
CC.inventory.guardStash(pattern, fn)                     --> boolean installed
CC.inventory.onStashMove(pattern, fn)                    --> boolean installed
CC.inventory.setStashSize(id, slots, weight)             --> boolean
CC.inventory.getStashItems(id)                           --> { { name, count, metadata, slot } } | nil
CC.inventory.clearStash(id)                              --> boolean
CC.inventory.moveStash(fromId, toId)                     --> moved, failed
CC.inventory.isStashOpen(id)                             --> boolean | nil  (nil = cannot tell)

-- client (UI hints only — never the basis of a decision)
CC.inventory.getItemCount(item)  /  hasItem(item, count)  /  isOpen()

exchange is the one to reach for in crafting and trades: it verifies everything up front, then rolls back every removal if any step fails, so an action can never consume without producing. From 1.6.0 every reward addItem is checked (a reward that does not land takes back the rewards already given and returns the inputs), capacity is checked after the inputs are removed so the weight they free counts, and an input line may carry its metadata as [3] so a rollback returns the same item. A rollback that itself fails is logged as an error naming every item.

Every server entry point (addItem, removeItem, canCarry, getItemCount, getSlot) returns its safe answer (false / 0 / nil) instead of raising when the inventory resource throws — during a restart, say — so the caller's rollback runs (1.6.0).

getSlot is how the server learns what is in a slot the client named — the client sends a slot number, never an item name. Metadata (serial, durability) is the inventory's own table, untouched. nil means empty or cannot tell: ESX and core_inventory have no numbered slots, and a fork with no GetItemBySlot export is not guessed at (both logged once).

Stashes: the inventory decides who opens what. CC.inventory.secure says whether it can. When it is false, a client can name any stash id (and often its size) itself, and the product must treat the stash id as the secret.

InventorysecureregisteropenguardStashresize / read / clear / move / isOpen
ox_inventoryyesRegisterStash (+ coords, groups)forceOpenInventoryopenInventory hookall
qb-inventory ≥ 2.2.3yesCreateInventoryOpenInventory(src, id, data)AddHook('InventoryOpened')all
qb-inventory 2.0–2.2.2no — moves were not checked against the open inventory; warned onceas aboveas aboveas above (2.1.0+)all
qs-inventorynoremembered; the server RegisterStash(src, id, slots, weight) runs on every openthen the client open—resize only (community-tested)
ps-inventoryno—its OpenInventory(src, id, data) export (QB-compat branch, since f6516c3)——
qb-inventory 1.x, lj, ps without the exportno—the client asks: inventory:server:OpenInventory + SetCurrentStash—resize only
codem, core, ak47, tgiann, origenno—their OpenInventory export where one exists (community-tested)——
  • owner is not access control. On ox, owner = true lets a client open other players' copies. registerStash accepts only an identifier string; true logs a warning and registers the stash shared. Gate access with guardStash.
  • opts = { coords = vec3 | vec3[], groups = { job = grade }, maxDistance = n } is passed to ox (maxDistance is not something ox's API can take; others ignore what they cannot express).
  • guardStash(pattern, fn) — fn(src, stashId, 'open') must return exactly true to allow. false, nil and an error refuse: ox and qb both pcall their hooks and let the action through when a hook errors, so the wrapper fails closed. A malformed Lua pattern is refused up front (ox would throw on every stash open). Returns false where nothing can be installed — do not rely on it there.
  • onStashMove(pattern, fn) — fn(src, { from, to, item, count, metadata, action }) for raid and theft logs. On ox it fires as the move is about to apply; on qb-inventory after it succeeded. It never blocks a move.
  • moveStash moves stack by stack through the inventory's own API, adding to the target first. A stack the target will not take stays where it was and comes back in failed with reason = 'add_failed'; one the source will not release is taken back out of the target ('remove_failed'). Nothing is ever deleted. Both ids must be registered.
  • setStashSize refuses to shrink a stash below its highest occupied slot.
  • Restarts: every registered stash, guard and move log is re-applied when the inventory resource restarts. A guard that silently vanished would leave every guarded stash open.
  • ox inventory:clearstashes defaults to '6 MONTH': every stash not changed in that long is deleted at each ox start — a holiday home emptied silently. cc_lib warns once when a product first uses stashes; set inventory:clearstashes "" keeps them.
  • ps-inventory infers the inventory type from the id text: a stash id containing trunk, glovebox, shop, traphouse, crafting or otherplayer is not opened as a stash.

CC.money — server unless noted

Accounts are 'cash', 'bank', 'black'.

lua
CC.money.get(src, account)                       --> number
CC.money.canAfford(src, account, amount)         --> boolean
CC.money.add(src, account, amount, reason)       --> boolean
CC.money.remove(src, account, amount, reason)    --> boolean
CC.money.charge(src, amount, reason)             --> boolean, 'cash'|'bank'   (cash first, then bank)

CC.money.getSociety(job)                         --> number
CC.money.addSociety(job, amount, reason)         --> boolean
CC.money.removeSociety(job, amount, reason)      --> boolean  (read-compare-write; cannot go negative)
CC.money.paySalary(src, job, amount, reason, fallbackToServer) --> boolean  (refunds the society if the credit fails, 1.6.0)

CC.money.addByIdentifier(identifier, account, amount, reason) --> boolean  (1.6.0)

CC.money.get(account)                            -- client, read-only for UI

addByIdentifier pays a character who may have logged off — a sale that completes later, a refund, a salary. Online it is add. Offline it works on qb-core and Qbox (their offline player object, saved afterwards) and returns false with a log line everywhere else, so hold the payout and retry when they are back.

Without accounts (1.6.0). ND_Core uses the character's cash and bank and has no black. With no framework, cash and black money are inventory items — cc:cash_item (default money) and cc:black_item (default black_money) through CC.inventory — which is what ox_inventory does on a bare server. There is no standalone bank: it reads 0 and refuses, with one warning.

Society providers, in order: Renewed-Banking, qs-banking, qb-banking, qb-management, fd_banking (1.6.0), acc_business, okokBanking, esx_addonaccount.

Job names are always bare ('police'). The bridge adds society_ for ESX and strips it for QB.

CC.security — server only

The centrepiece. See docs/08-cartel-engineering-standards.md.

lua
CC.security.event(name, opts, handler)

opts:

FieldDefaultEffect
cooldown—ms between calls per player
exclusivefalsereject re-entry while the handler is running
args—argument schema (see below)
job / jobGrade / requireDuty—job gate
gang / gangGrade—gang gate
distance—{ coords = vec3 or fun(src), max = n }
alivetruerefuse a dead player: ped health ≤ 0, or CC.framework.isDead
downedfalsetrue = refuse a downed player (last stand, knocked out, dead)
restrainedfalsetrue = refuse a cuffed, ziptied, escorted or carried player
onFootfalsetrue = refuse a player in a vehicle
combatCooldown—true (30 s) or ms: refuse a player who dealt or took weapon damage that recently

Every gate is a switch: set it to true to turn the refusal on. alive is the one that is on unless you write alive = false.

The checks run in this order: rate limit → argument schema → framework player loaded → liveness (alive, downed, restrained, onFoot, combatCooldown) → job / gang → distance. Schema, unloaded-player, job, gang and distance failures are CC.security.flagged; cooldown and liveness refusals are silent — a downed player pressing E is not an attacker.

The server's liveness test is GetEntityHealth(ped) <= 0 plus the framework's own dead state. Never IsEntityDead on the server — it is a client-only native, and calling it there threw "attempt to call a nil value" inside every handler.

An arg spec: { name, type, optional?, min?, max?, integer?, maxLen?, oneOf?, maxDepth?, maxNodes? } with type one of number, string, boolean, table, vector3.

Tighter by default from 1.6.0:

  • A number with no min/max is still bounded to ±2,147,483,647.
  • A table is walked: at most maxDepth levels (default 8) and maxNodes entries in total (default 512, never below maxLen). 1.5 counted only the top level.
  • An unknown type (a typo) refuses the argument and logs an error. It used to accept anything, which silently turned validation off.
  • A distance gate whose coords resolve to nil (or whose check errors) refuses, without flagging the player. It used to skip the check and pass. Return false from coords to skip the check on purpose (a keybind with no fixed point).
lua
CC.security.gate(src, name, opts, args?)    --> ok, reason?, cleaned?
CC.security.cooldown(src, key, ms)          --> boolean allowed
CC.security.acquire(src, key) / release(src, key)
CC.security.exclusive(src, key, fn)         --> boolean ran, any result
CC.security.mutex(key, fn)                  --> boolean ran, any result
CC.security.validate(specs, args)           --> ok, reason, cleaned
CC.security.near(src, coords, max)          --> boolean
CC.security.nearAny(src, points, max)       --> index?
CC.security.entityFromNetId(src, netId, maxDistance) --> entity?
CC.security.inCombat(src, ms?)              --> boolean   (default 30000)
CC.security.markCombat(src)
CC.security.trackCombat()                   -- events/callbacks with combatCooldown call it for you
CC.security.flag(src, reason, detail)       -- detail: a string
CC.security.onFlag(cb)
CC.security.isAdmin(src, ace)               --> boolean  (ACE, never a job check)
CC.security.command(name, ace, handler)

flag records and forwards; it never kicks, bans or punishes. Ship the signal, let the server owner wire the consequence.

gate is the pipeline event and callback.register share, for checks you run yourself — "may this player be invited?", "may they enter?". reason is one of 'source', 'cooldown', 'args', 'unloaded', 'dead', 'downed', 'restrained', 'vehicle', 'combat', 'job', 'gang', 'distance'. Pass args (a table.pack of the raw arguments) when opts.args is set.

Combat is tracked from the engine's weaponDamageEvent — the shooter and every player ped hit — and only once something asks for it. It is heard with AddEventHandler; never RegisterNetEvent an engine event, which makes it callable by any client with a forged victim.

mutex(key, fn) locks an object, not a player: two different players racing for 'unit:12' serialise, and the second is refused at once (it does not queue). fn may yield (MySQL.await); the lock is released on every path, including an error. Global within one resource.

Tickets — single use, bound to one player and one purpose:

lua
CC.security.ticket(src, kind, data, ttlMs, key?)  --> id
CC.security.redeem(src, kind, id)                 --> data | nil   (consumes it)
CC.security.peek(src, kind, id)                   --> data | nil   (does not)
CC.security.revokeTickets(src, kind?)             --> revoked count

A consent ("accept the raid"), a spawn, a stash open: something the server granted a moment ago that the client now asks to use. redeem returns nil for the wrong player, the wrong kind, an expired or an already used ticket — and a wrong-player or wrong-kind attempt does not burn the owner's ticket. Ids are 128 bits from math.random seeded with the clock and an ASLR address: not cryptographic, but not enumerable. With key, the id is the key, for server-internal tickets ("this player may open stash X for the next 5 s"); two players can hold the same key. A ticket issued with nil data redeems as true. Expiry is a timestamp compared at redeem time, never a timer, and a dropped player loses every ticket.

CC.callback

Dependency-free request/response in both directions, behind the same gate as CC.security.event.

lua
-- server
CC.callback.register('name', opts, function(src, ...) return value end)
CC.callback.await(src, 'name', ...)          -- server -> client
-- client
CC.callback.register('name', function(...) return value end)
CC.callback.await('name', ...)               -- client -> server
CC.callback.awaitTimeout(name, ms, ...)

Callbacks are for reads; mutations are events. A callback's answer travels back to a client that can drop it, replay the request, or ask twice in one frame. Anything that moves money or items, or changes state, is a CC.security.event with exclusive and a server-side apply.

On the server, register honours every event option — cooldown, args, job, gang, distance, alive (on by default), downed, restrained, onFoot, combatCooldown — and exclusive, keyed per player and callback. A refused request is answered with nil at once, so the client is never left waiting out the timeout. (1.0 silently ignored exclusive, alive and gang on callbacks.)

await must run inside a thread (CreateThread, an event handler or SetTimeout). It waits on a promise with Citizen.Await; requests time out at 10 s by default and answer nil exactly once. (1.0 parked on a bare coroutine.yield(), which FiveM's scheduler treats as Wait(0): every await returned nil one tick later on a live server.)

CC.target — client only

lua
local id = CC.target.addSphereZone({ coords = vec3, radius = 2.0, options = {...} })
local id = CC.target.addBoxZone({ coords = vec3, size = vec3, rotation = 0.0, options = {...} })
local id = CC.target.addModel(models, options)
local id = CC.target.addLocalEntity(entities, options)
local id = CC.target.addGlobalVehicle(options)
CC.target.remove(id)
CC.target.removeAll()

An option:

lua
{
    name        = 'cc_shop_open',       -- unique, namespaced
    label       = 'Open shop',
    icon        = 'fa-solid fa-basket-shopping',
    distance    = 2.0,
    groups      = { police = 0 },       -- job gate, enforced on every adapter
    items       = { 'lockpick' },       -- item gate
    canInteract = function(entity, distance, coords, name, bone) return true end,
    onSelect    = function(data) end,   -- data.entity, data.coords
}

Falls back to a native proximity system — one adaptive thread for all zones, with an [E] prompt — when no targeting resource is installed. addModel and addGlobalVehicle require a real target resource.

Adapters: ox_target, qb-target (and qtarget / bt-target), darktrace interact (1.6.0: in-world prompts; a call it rejects falls back to the native prompt), and the native fallback (also used for sleepless_interact).

Always CC.target.remove(id) in onResourceStop. Leaked zones survive the restart and are visible to every player instantly.

CC.notify

lua
CC.notify.send(src, opts)                 -- server
CC.notify.broadcast(opts)                 -- server
CC.notify.job(jobName, opts, onDutyOnly)  -- server
CC.notify.send(opts)                      -- client
CC.notify.success/error/info/warn(description, title)  -- client

opts: { title?, description, type = 'success'|'error'|'inform'|'warning', duration?, icon? }. Falls back through the framework's own notify, then the GTA feed — it is never silent.

CC.progress — client only

lua
local completed = CC.progress.run({
    label     = 'Picking the lock',
    duration  = 8000,
    canCancel = true,
    disable   = { move = true, car = true, mouse = false, combat = true },
    anim      = { dict = '...', clip = '...', flag = 49 },
    prop      = { model = ..., bone = ..., pos = ..., rot = ... },
})

Returns true when it completed. (ox_lib and qb-progressbar disagree on the polarity of this — cc_lib normalises it. Getting it backwards is the most common bridge bug in the wild.)

A progress bar is a client-side courtesy. The server must enforce the time cost independently — a cheater simply never runs the bar.

CC.minigame — client only

lua
CC.minigame.provider      --> 'ox_lib' | 'native' | 'none'
local ok, score = CC.minigame.run({
    provider   = nil,                    -- nil = the detected provider
    difficulty = { 'easy', 'medium' },   -- or one entry; ox_lib's { areaSize, speedMultiplier } works too
    inputs     = { 'e' },                -- e, w, a, s, d, space
    attempts   = 1,
})                         --> ok, score 0..1
ProviderWhat runs
ox_liblib.skillCheck(difficulty, inputs)
nativea drawn timed-key bar per difficulty entry; the prompt is GTA's own ~INPUT_~ glyph, so it shows the right button on keyboard or controller
nonenothing: true, 1.0 at once

'none' is always valid — some communities do not want reaction tests at all. The result is a client claim: trust it only where losing costs time or a cheap item, and roll on the server where the outcome matters (handbook/16). The native check runs a per-frame loop only while it is on screen.

CC.textui — client only

lua
CC.textui.show('[E] Open shop', 'right-center')
CC.textui.hide()
CC.textui.isShown()

show is idempotent: calling it every frame with the same text costs nothing after the first call.

CC.menu — client only

lua
CC.menu.open({ id, title, options = { { label, description?, icon?, disabled?, onSelect } } })
CC.menu.close()
local values = CC.menu.input(title, rows)   --> array or nil if cancelled
local ok     = CC.menu.confirm(title, message)

Includes a native keyboard-driven fallback so menus work with zero menu resources installed.

CC.keys

lua
-- server
CC.keys.give(src, plate, netId)   /  remove(src, plate, netId)  /  has(src, plate, netId)
CC.keys.setLock(netId, locked)
-- client
CC.keys.give(plate, vehicle)  /  remove(plate, vehicle)  /  has(plate, vehicle)
CC.keys.hasForVehicle(vehicle)  /  setLock(vehicle, locked)

Carries all three identities (source, plate, netId) because the ecosystem has four incompatible API shapes and you cannot cheaply derive one from another on the right side of the network boundary.

CC.fuel

lua
CC.fuel.get(vehicle)              --> 0..100   (server: nil when nothing server-readable exists)
CC.fuel.set(vehicle, level)
CC.fuel.setFor(src, netId, level) -- server; required for client-only providers
CC.fuel.getType(vehicle)  /  isElectric(vehicle)

GetVehicleFuelLevel is a client-only native, so on the server get reads the provider and the fuel state bag, and answers nil ("cannot tell") rather than a guess — a 0 would bill a full tank.

Providers: Renewed-Fuel, ox_fuel (state bag), and the LegacyFuel export shape — LegacyFuel, ps-fuel, cdn-fuel, lj-fuel, hyon_gas_station, BigDaddy-Fuel, qs-fuelstations, lc_fuel (client only), okokGasStation, qb-fuel (1.6.0). On the client a legacy-shaped resource must actually publish GetFuel to be picked (1.6.0); on the server a set with no server SetFuel returns false — use setFor.

CC.vehicle

lua
-- client
CC.vehicle.getProperties(vehicle)  /  setProperties(vehicle, props)
CC.vehicle.current()  /  nearest(radius)
-- server
CC.vehicle.spawn({ model, coords, heading, plate, owner, props, warp, type })  --> entity, netId
CC.vehicle.delete(entity)
CC.vehicle.generatePlate(prefix)
-- both (1.6.0)
CC.vehicle.getLabel(model)  --> 'Pegassi Zentorno'; never nil

getLabel reads qb/qbx shared vehicles (brand + name), then the game label on the client, then the model name itself.

Server-side spawning means the client never chooses the model, which closes the "spawn a Rhino from the garage menu" exploit outright. Pass type ('boat', 'heli', 'plane', 'bike', …) for anything that is not a car: the server cannot read a model's type, and a helicopter created as an 'automobile' is a broken entity.

CC.dispatch

lua
CC.dispatch.send(alert)              -- client
CC.dispatch.send(alert, fromSource)  -- server
CC.dispatch.fallback(alert)          -- server: blip + notify on-duty players

One table argument, deliberately. Falls back to blips and notifications when no dispatch resource is installed. send returns true when a dispatch resource took the alert, false when the built-in fallback delivered it.

ProviderPath
ps-dispatchclient CustomAlert; server SendTargetedAlert when targets is given
cd_dispatch, qs-dispatch, linden_outlawalertclient event
rcore_dispatch (1.6.0)rcore_dispatch:server:sendAlert, from either side
core_dispatch (1.6.0)client export addCall, one per job
lb-tablet (1.6.0)server export AddDispatch, one per job
origen_police, emergencydispatchdetected; alerts use the fallback
noneblip + notification to on-duty players in jobs

A provider call that throws falls back to the built-in alert.

Client-raised alerts are bounded (1.6.0). When a client alert has to go through the server (no client adapter, or a server-only provider) it is a gated event: 5 s cooldown, coords taken from the sender's own ped, jobs filtered to cc:dispatch_jobs (default police,sheriff,ambulance,fire, at most 4, police if none survive), and every blip field clamped. A player cannot push text to a gang or a business, or alert a place they are not standing in. Server-side CC.dispatch.send is not filtered.

CC.phone (1.6.0)

lua
-- server
CC.phone.sendMail(src, { sender, subject, message })                 --> boolean deliveredByPhone
CC.phone.notify(src, { title, description, app?, icon?, duration? }) --> boolean shownByPhone
CC.phone.getNumber(src)                                              --> string | nil
-- client
CC.phone.notify({ title, description })                              --> boolean

Phones are an optional integration: nothing may depend on one. With no phone, or a phone call that throws, the player gets a CC.notify toast instead and the function returns false — the player still saw it.

PhoneMailNotify
lb-phoneSendMail to the player's addressSendNotification
yseriesSendMail(data, 'source', src)SendNotification
gksphoneSendNewMailtoast
qs-smartphone-prosendNewMailtoast
qs-smartphone, qb-phonesendNewMailToOffline (citizenid)toast
npwdtoast (npwd has no mail)client createNotification

The provider shapes were written from each vendor's documentation and have not been run against every phone in-game; each is export-probed and pcall-guarded. Pass L() text, never a string a client sent.

CC.character

lua
-- server
CC.character.onCreated(function(src, identifier) end)
CC.character.hasCreatedSignal()             --> boolean
CC.character.onDeleted(function(identifier) end)
CC.character.setSavePosition(src, coords)   --> boolean honoured  (nil clears it)
-- client
CC.character.onSpawned(function(isNew) end)

Only the framework, on the server, says a character is new or gone. A client that says "I am new" gets a free starter flat on every relog. Every signal here is a server-local framework event, heard with AddEventHandler.

ESXox_coreQboxQBCore / standalone
onCreatedesx:playerLoaded with isNewox:createdCharacter——
hasCreatedSignal()truetruefalsefalse
onDeleted— (esx_multicharacter deletes through a client net event)ox:deletedCharacterqbx_core:server:characterDeleted—
onSpawned (client)the first esx:onPlayerSpawn after a loadox:playerLoaded(_, isNew)——
setSavePositionnot honourednot honouredinProperty bag + the positionnot honoured

Identifiers match CC.framework.getIdentifier ('char7' on ox_core). Register onSpawned at resource start: a spawn that already happened is not replayed. The QB family hands new characters to apartments:client:setupSpawnUI instead of announcing them.

setSavePosition(src, coords) saves coords — the door outside — as the player's position instead of wherever they stand inside an instanced interior; nil puts normal saving back. On Qbox, qbx_core's Save() keeps PlayerData.position while the inProperty state bag is set, so cc_lib sets both, and clears its own override when the character logs out. QBCore, ESX and ox_core save the live position: move the player out before they log off.

CC.appearance — client only

lua
CC.appearance.resource                        --> string | nil  (also readable on the server)
CC.appearance.supports('outfits' | 'shop')    --> boolean
CC.appearance.openWardrobe('outfits' | 'shop')--> boolean
CC.appearance.createFirstCharacter(function(finished) end, { timeoutMs = 600000 })
CC.appearance.isCreatorOpen()                 --> boolean

A wardrobe never opens a free editor. Several common "open the wardrobe" calls open a full editor — ped model, face, tattoos — for free, which turns a home closet into a free clothing shop. openWardrobe only ever calls these:

Provider'outfits''shop' (paid)
illenium-appearanceillenium-appearance:client:openOutfitMenu…:openClothingShopMenu(false)
bl_appearanceOpenMenu('outfits')—
fivem-appearanceopenWardrobe()—
rcore_clothing (community-tested)rcore_clothing:openChangingRoom—
ak47 (community-tested)ak47_clothing:openOutfit / ak47_qb_clothing:openOutfit—
tgiann-clothing (community-tested)OpenWardobeMenu('clothing')—
17mov_CharacterSystem (community-tested)17mov_CharacterSystem:OpenOutfitsMenu—
qs-appearance (community-tested)clothing:openOutfitMenu—
qb-clothingqb-clothing:client:openOutfitMenu—
esx_skin— (no outfit-only menu exists)—

Never openClothingShop(true) / isPedMenu = true, qb-clothing:client:openMenu, esx_skin:openSaveableMenu or startPlayerCustomization for a wardrobe; tests/sim.lua records every event and export each provider's wardrobe fires and fails if one appears. Other providers' shops need a shop id from their own config, or (in fivem-appearance:clothingShop) take the price from the client, so 'shop' is illenium-only.

createFirstCharacter(cb, opts) runs the first-character creator and calls cb(finished) exactly once: true when the creator closed, false on the timeout (default 10 minutes) or when nothing could start.

ProviderCreatorSaved by
illenium-appearancestartPlayerCustomization(cb, cfg)illenium-appearance:server:saveAppearance
fivem-appearancestartPlayerCustomization(cb, cfg)fivem-appearance:save (the wasabi fork; the original saves nothing)
bl_appearanceInitialCreation(cb)bl itself
esx_skinesx_skin:openSaveableMenu(submit, cancel); cancel counts as finishedesx_skin
qb-clothingqb-clothes:client:CreateFirstCharacter, finished on qb-clothing:client:onMenuCloseqb-clothing
anything elsethe same qb event, finished when NUI focus was taken and returned with the screen faded inthe provider

Run the creator before placing the player: illenium and bl_appearance move the player to a private routing bucket while the creator is open and reset it to 0 when it closes.

CC.weather — client only

lua
CC.weather.resource    --> string | nil
CC.weather.pause()     -- this player only: inside a shell it would rain in the living room
CC.weather.resume()
CC.weather.isPaused()  --> boolean
Resourcepause / resume
Renewed-WeathersyncLocalPlayer.state.syncWeather = false / true
qb-weathersyncqb-weathersync:client:DisableSync / EnableSync
cd_easytimecd_easytime:PauseSync(true / false)
vSync (community-tested)vSync:toggle(false / true)
noneone loop, every 2.5 s, while paused: clear sky, rain off, ped dried

Never two weather writers at once — two loops writing weather flicker. With a weather resource, cc_lib only flips its switch; the fallback loop runs only on a server with none. resume also runs when your resource stops.

CC.garage

lua
-- server
CC.garage.register({
    id     = 'tcch_12',
    label  = 'Grove St. 12',
    coords = vec4(...),
    spawns = { vec4(...) },          -- optional; defaults to coords
    type   = 'car',
    access = function(src) return Houses.canUseGarage(src, 12) end,
    interactions = false,            -- optional; true lets jg v4 draw its own prompts
})                                   --> boolean registered, string garageId
CC.garage.garageId(id)               --> string: the id to send the client
CC.garage.refreshAccess(id)          --> boolean (jg v4: refresh prompts after a key change)
CC.garage.unregister(id)             --> boolean
CC.garage.isClientDriven()           --> boolean
-- client: the server's garageId(id), never the raw id
CC.garage.open(garageId, coords)     --> boolean
CC.garage.store(garageId)            --> boolean

jg v4 renames the garage. registerGarage returns an id prefixed with the calling resource's name, and that is the id jg opens, stores and keeps cars under (player_vehicles.garage_id). Send the client CC.garage.garageId(id). It is the raw id on every other garage resource, and on jg until a registration succeeds.

Access is a live callback, asked at the moment of use — never a copied list. qbx_properties captured owner and keyholders in a closure, and a revoked keyholder kept pulling cars until a restart. Only an exact true from access allows; an error refuses. Registrations live in the garage resource's memory, so cc_lib re-applies them when it restarts.

Resourceregisterunregisterclient
jg-advancedgarages v4registerGarage{ id, name, coords (vec3), spawnPoints, vehicleType, access, manageInteractions } → prefixed idunregisterGarage(prefixedId) (keeps stored cars)openGarage / storeVehicle (client exports)
qbx_garagesRegisterGarage(id, { label, vehicleType, accessPoints, canAccess })none upstream: re-registered with canAccess falseits own access point
cd_garage (community-tested)cd_garage:PropertyGarage:Create(data) — no access callback: anyone at the marker reaches their own cars—PropertyGarage:Open(vec4) / :StoreVehicle
vms_garagesv2 (community-tested)registerHousingGarage(id, label, housingId, coords)—enterHouseGarage()
jg v3, okokGarage, qb-garages (community-tested)client-driven: nothing to register—their open / store events

isClientDriven() is true for jg v3, okokGarage, qb-garages and cd_garage: the product checks access itself and calls CC.garage.open / store from the client. qb-garages deposits call exports['qb-houses']:hasKey; a housing product that replaces qb-houses answers it from its own resource with AddEventHandler('__cfx_export_qb-houses_hasKey', function(setCB) setCB(fn) end) — the pattern qbx_core uses for qb-core.

CC.doorlock — server only

lua
CC.doorlock.resource                        --> 'ox_doorlock' | 'qb-doorlock' | nil
CC.doorlock.bind({ name = 'tcch_12_front', authorize = function(src) return true end }) --> boolean
CC.doorlock.setState(name, locked)          --> boolean
CC.doorlock.unbind(name)
CC.doorlock.exists(name)                    --> boolean

A real door (a walk-in MLO property) authorised by a live callback through ox_doorlock's doorAuthorization hook — never by copying keyholders into the door's own data (ps-housing did, and revoked keyholders kept unlocking). Read from ox_doorlock's source, and why the wrapper looks the way it does:

  • The hook can only grant: the door's own rules decide first.
  • ox keeps any non-nil hook result — including the error message of a hook that threw, which is truthy, so an erroring hook would grant. cc_lib's hook never lets an error out.
  • The last non-nil result wins, so a false would overwrite another resource's grant. cc_lib answers true or nil, never false.
  • nameFilter is skipped for a door with no name, so cc_lib checks the exact bound name.
  • The lockpick path returns before hooks run, and upstream checks only that the player holds a lockpick item — not the door's lockpick flag, the skill check or the distance. That gap is ox_doorlock's to fix, not ours.

The door must exist first: create it in ox_doorlock's own editor (createDoor is an export only on ox_doorlock main since 4e56b7e). bind returns false for a door ox does not know. setState from the server applies without ox's own authorisation check, so decide first. qb-doorlock has no server authorisation hook upstream; bind returns false there. Never bind a door of an instanced interior: ox_doorlock broadcasts door state to every player in every routing bucket.

CC.logger — server only

lua
CC.logger.setup({ default = url, channels = { economy = url, security = url } })
CC.logger.log('economy', { title, description?, player?, fields?, colour?, footer? })
CC.logger.captureSecurityFlags('security')

-- 1.6.0
local econ = CC.logger.channel('economy')   --> { log = fun(data) }
econ.log({ title = 'Sold', player = src })
CC.logger.info(msg, ...)  /  CC.logger.warn(msg, ...)  /  CC.logger.error(msg, ...)

Every log goes somewhere (1.6.0). Whether or not a webhook is set, log() writes:

  • one console line (set cc:log_console "false" to stop);
  • the local server event cc_lib:log with the raw entry { resource, channel, level, title, description, player, identifier, fields, time } — feed your own stack with AddEventHandler('cc_lib:log', fn) (never RegisterNetEvent);
  • Fivemanage (fmsdk LogMessage) and the ox_lib logger (lib.logger, in a resource that loads @ox_lib/init.lua) when detected — set cc:log_mirror "auto" | "none" | "fivemanage,ox_lib".

So an empty webhook means no Discord posts, never no log. info/warn/error are plain one-line logs on the channel of that name: console and mirrors always, Discord only if a webhook is set for that exact channel (never the default one). Webhook branding: set cc:log_username, cc:log_avatar, cc:log_footer_icon, or setup{ username, avatar, footerIcon }.

Batched with rate-limit backoff — Discord throttles webhooks at roughly 5 requests per 2 seconds, and PerformHttpRequest failures are silent by default, so a busy script that posts per event loses exactly the logs you need during an incident.

Player text is handled for you (1.3.0). Every request carries allowed_mentions = { parse = {} }, and every string log() puts in an embed — title, description, field names and values, footer, player name — is sanitised: invisible and bidi characters stripped, @everyone / @here / <@ broken, markdown escaped (idempotently, so pre-escaped text is not escaped twice). Every embed is cut to Discord's limits on UTF-8 boundaries (title 256, description 4096, 25 fields, 256 / 1024 per field, footer 2048, 6000 per embed and per message) and invalid UTF-8 is replaced, because one over-limit embed is a 400 that loses the whole batch. Pass the raw values; do not pre-sanitise.

Webhook URLs are secrets. Server-only file, or a set (never setr) convar.

CC.hooks — extensibility without source

The answer to "deeply customizable, but escrowed". A customer changes what your script does from their own resource; your source stays sealed.

lua
-- in your product
CC.hooks.define('beforePurchase', {
    cancellable = true,
    mutable     = true,
    description = 'Before money is taken. Return false to block.',
    payload     = 'source, item, count, price',
})
CC.hooks.expose()          -- publishes registerHook / removeHook / getHooks

local price = 250
if CC.hooks.count('beforePurchase') > 0 then    -- skip building a payload nobody reads
    local payload = { source = src, item = 'lockpick', price = price }
    if not CC.hooks.run('beforePurchase', payload) then return end
    price = payload.price      -- read it BACK; a hook may have changed it
end
lua
-- in the customer's own resource, no Cartel source required
exports.cc_shop:registerHook('beforePurchase', function(payload)
    if isVip(payload.source) then payload.price = payload.price * 0.9 end
end, { priority = 10 })
FunctionNotes
define(name, opts)Declares a hook. opts: cancellable, mutable, description, payload
expose()Publishes the registration exports on this resource
run(name, payload)Returns false if any handler cancelled. payload mutates in place
filter(name, value, ctx)Chain form — each handler returns a replacement value
count(name)Handlers registered right now; 0 for an unknown name. Guard an expensive payload with it: the argument is built before run can decide anything
register/remove/removeResourceDirect control; list()/names() for introspection

A handler can be a function or the string 'resource.exportName':

lua
exports.cc_shop:registerHook('beforePurchase', 'my_perks.applyDiscount')

A function passed from another resource arrives as a function reference (a callable table), not a Lua function; 1.1 accepts it — 1.0 rejected it, so cross-resource registration only worked through the string form.

The string form is serialisable, so it can live in a config or JSON data file — neither of which can carry a closure. It resolves lazily on each call, so the target resource may start after the one registering. This is the same shape ox_inventory item definitions and ox_target options use.

Handlers run inside pcall (a customer's broken hook can't break your product), in descending priority, and are auto-removed when their resource stops — tracked via GetInvokingResource(). Slow handlers are logged by owning resource. Handler ids are strings (cc_shop:beforePurchase:3) rather than array indices — self-describing in a log line, and still valid after the list is compacted.

Hooks narrow authority, never widen it. A hook can block or adjust something the code was already willing to do. Never treat a hook's return as permission, and always re-validate a mutated value before acting on it.

CC.api — versioned public surface

lua
CC.api.publish({
    version = '1.2.0',
    hooks   = true,
    exports = { isOnRun = function(src) return active[src] ~= nil end },
})

Every Cartel resource then answers getVersion, getApi and getHooks, so tooling and support can enumerate a product without docs.

FunctionPurpose
publish(opts)Publishes exports, the three standard ones, and fires <resource>:ready
registry(name, opts)A registration point third parties add to — see below
require(resource, minVersion)Soft dependency check; warns, never throws
deprecate(old, new, fn)Keeps an old export alive, warns once per session
compareVersions(a, b)-1 / 0 / 1, semver-aware

Registries solve start-order. Exports only exist once a resource has started, so a customer registering into you may run too early:

lua
local Shops = CC.api.registry('shop', {
    validate = function(def)
        if type(def.coords) ~= 'vector3' then return false, 'coords must be a vec3' end
        return true
    end,
})
Shops.onAdd(function(def) buildTargetFor(def) end)

That publishes registerShop / unregisterShop / getShops. From 1.6.0 only the owning resource (or the host) can unregister an entry, the owner may re-register its own key to replace it, and getShops returns a copy. onAdd replays entries already registered, so a late listener still sees the full set, and entries are dropped automatically when their owning resource stops. Consumers can either call immediately or wait for AddEventHandler('cc_shops:ready', ...) — both work.

Utilities

lua
CC.log(level, msg, ...)          -- 'error'|'warn'|'info'|'debug'
CC.started(resourceName)         --> boolean
CC.pick({ 'a', 'b' })            --> first started, or nil
CC.plate(plate)                  --> trimmed, uppercased
CC.number(v, min, max, integer)  --> number or nil  (rejects NaN and inf)
CC.string(v, maxLen)             --> string or nil
CC.readonly(t)                   --> read-only proxy
CC.hasExport(res, fn)            --> boolean: started AND publishes that export (1.6.0)
CC.pickExport(list, fn)          --> first in list that publishes fn, or nil (1.6.0)
CC.eventName(suffix)             --> 'cc_lib:<this resource>:<suffix>' (1.6.0)

Scoped events (1.6.0). cc_lib's own server→client events (notify, keys, fuel, vehicle props, dispatch, phone) are named CC.eventName(...) and have one handler, in init.lua, which loads the module on first use. Before 1.6.0 they were global: every resource using cc_lib answered every other resource's event (one toast became one per product), and a resource whose client had never touched the module dropped its own.

CC.billing — server only (1.13.0)

Send an invoice through the billing resource the server runs.

lua
local ok, err = CC.billing.send(targetSrc, {
    amount  = 250,                 -- integer, 1 .. 1,000,000,000
    reason  = 'Speeding',          -- 1..128 characters
    society = 'police',            -- optional: job whose account is paid
    sender  = officerSrc,          -- optional: issuing player
})
CC.billing.provider()  --> 'okokBilling' | 'esx_billing' | 'fallback' | nil

err is one of bad_target, bad_amount, bad_reason, no_provider, provider_failed, funds, society_failed. With no billing resource, Config.Billing.fallback = 'charge' takes the amount from the target's bank at once (refunded if the society cannot be paid); the default 'none' returns false, 'no_provider'. Decide the amount and target on the server — never pass values a client sent.

CC.boost (1.12.0; off by default since 1.13.0)

A timed pay/XP multiplier ("double XP weekend"), configured in Config.Boost.

lua
CC.boost.active()      --> boolean
CC.boost.pay(amount)   --> amount x pay rate, whole dollars (non-numbers and <= 0 unchanged)
CC.boost.xp(amount)    --> amount x XP rate, whole points
CC.boost.payRate()     --> number (1 outside the window)
CC.boost.xpRate()      --> number
CC.boost.state()       --> { active, start, finish, pay, xp }

Call it once, where a job credits earned pay, after the job's own cap. Never boost refunds, buy-backs, society wages or anything a shop also sells. The server is the authority; the client answer is for display.

Settings and locale (1.13.0)

lua
CC.setting(convar, path, default)   --> convar > config.lua (or server/config.lua for 'server:' paths) > default
CC.setting('cc:cash_item', 'Money.cashItem', 'money')
CC.setting('cc:webhook_default', 'server:Webhooks.default', '')   -- server only
CC.cfg                              --> config.lua's Config (read it, do not write it)
CC.locale(key, ...)                 --> cc_lib string from locales/, formatted; unknown key -> key
CC.settings.validate()              --> { { level, path, msg }, ... } problems in the config files

Products keep their own config and locales; these are for cc_lib's own settings.


Export surface (exports.cc_lib)

For JavaScript/C# resources and one-line integrations. Lua resources should prefer the init (faster, and its events are scoped to your resource).

ExportSideReturns
call(module, fn, ...)server, clientwhatever CC.<module>.<fn>(...) returns; on error nil, message (never throws)
getVersion()server, client'1.13.0'
getConfig()server, clienta plain copy of config.lua (never server/config.lua)
modules()server, clientthe module names call accepts on that side
boostPay(amount), boostXp(amount), boostState()serversee CC.boost
GetProfile(src)server{ name, job, avatar? } for the homebar card (display only)

call refuses unknown modules and any function whose name starts with _ (internal). Server modules: framework, money, inventory, notify, progress, target, textui, menu, minigame, keys, fuel, vehicle, appearance, garage, doorlock, weather, phone, dispatch, character, billing, boost, logger, hooks, security, callback, api. Client: the same minus billing, logger, security and api.

js
// JavaScript, server side
const ok = exports.cc_lib.call('money', 'add', source, 'bank', 500, 'myjob:payout');
exports.cc_lib.call('notify', 'send', source, { description: 'Paid $500', type: 'success' });
lua
-- Lua without the init
exports.cc_lib:call('billing', 'send', target, { amount = 120, reason = 'Tow', society = 'mechanic' })

Events

EventSideWhenPayload
cc_lib:logserver, local onlyevery CC.logger.logentry table: channel, resource, level, title, description, player, identifier, fields, time
cc_lib:<resource>:<suffix>netcc_lib's own scoped routes (notify, keys, fuel, dispatch, phone)internal — do not trigger

Listen with AddEventHandler('cc_lib:log', function(entry) ... end). It is server-local: never RegisterNetEvent it. Hook points for products are declared with CC.hooks (above) and listed by each product's getHooks export.