@@ -46,6 +46,8 @@ local config = require('opencode.config')
4646--- @field unsubscribe fun ( key : string | nil , cb : fun ( key : string , new_val : any , old_val : any ))
4747--- @field is_running fun (): boolean
4848
49+ local M = {}
50+
4951-- Internal raw state table
5052local _state = {
5153 -- ui
@@ -96,10 +98,10 @@ local _listeners = {}
9698--- @usage
9799--- state.subscribe('foo', function(key, new, old) ... end)
98100--- state.subscribe('*', function(key, new, old) ... end)
99- local function subscribe (key , cb )
101+ function M . subscribe (key , cb )
100102 if type (key ) == ' table' then
101103 for _ , k in ipairs (key ) do
102- subscribe (k , cb )
104+ M . subscribe (k , cb )
103105 end
104106 return
105107 end
113115--- Unsubscribe a callback for a key (or all keys)
114116--- @param key string | nil
115117--- @param cb fun ( key : string , new_val : any , old_val : any )
116- local function unsubscribe (key , cb )
118+ function M . unsubscribe (key , cb )
117119 key = key or ' *'
118120 local list = _listeners [key ]
119121 if not list then
@@ -148,7 +150,7 @@ local function _notify(key, new_val, old_val)
148150 end )
149151end
150152
151- local function append (key , value )
153+ function M . append (key , value )
152154 if type (value ) ~= ' table' then
153155 error (' Value must be a table to append' )
154156 end
@@ -164,7 +166,7 @@ local function append(key, value)
164166 _notify (key , _state [key ], old )
165167end
166168
167- local function remove (key , idx )
169+ function M . remove (key , idx )
168170 if not _state [key ] then
169171 return
170172 end
@@ -177,16 +179,21 @@ local function remove(key, idx)
177179 _notify (key , _state [key ], old )
178180end
179181
182+ ---
183+ --- Returns true if any job (run or server) is running
184+ ---
185+ function M .is_running ()
186+ return M .job_count > 0
187+ end
188+
180189--- Observable state proxy. All reads/writes go through this table.
181190--- Use `state.subscribe(key, cb)` to listen for changes.
182191--- Use `state.unsubscribe(key, cb)` to remove listeners.
183192---
184193--- Example:
185194--- state.subscribe('foo', function(key, new, old) print(key, new, old) end)
186195--- state.foo = 42 -- triggers callback
187- --- @type OpencodeState
188- local M = {}
189- setmetatable (M , {
196+ return setmetatable (M , {
190197 __index = function (_ , k )
191198 return _state [k ]
192199 end ,
@@ -203,18 +210,4 @@ setmetatable(M, {
203210 __ipairs = function ()
204211 return ipairs (_state )
205212 end ,
206- })
207-
208- M .append = append
209- M .remove = remove
210- M .subscribe = subscribe
211- M .unsubscribe = unsubscribe
212-
213- ---
214- --- Returns true if any job (run or server) is running
215- ---
216- function M .is_running ()
217- return M .job_count > 0
218- end
219-
220- return M
213+ }) --[[ @as OpencodeState]]
0 commit comments