robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
5.8 KiB187 linesraw
1local M = {}
2
3local http_methods = {
4  GET = true,
5  POST = true,
6  PUT = true,
7  PATCH = true,
8  HEAD = true,
9  DELETE = true,
10}
11
12---@alias vim.net.request.ResponseFunc fun(err: string?, response: vim.net.request.Response?)
13---@alias vim.net.HttpMethod string "GET" | "POST" | "PUT" | "PATCH" | "HEAD" | "DELETE"
14
15---@class vim.net.request.Opts
16---@inlinedoc
17---
18---Enables verbose output.
19---@field verbose? boolean
20---
21---Number of retries on transient failures (default: 3).
22---@field retry? integer
23---
24---Request body for POST/PUT/PATCH requests.
25---@field body? string
26---
27---File path to save the response body to.
28---@field outpath? string
29---
30---Buffer to save the response body to.
31---@field outbuf? integer
32---
33---Custom headers to send with the request. Supports basic key/value headers and empty headers as
34---supported by curl. Does not support "@filename" style, internal header deletion ("Header:").
35---@field headers? table<string, string>
36
37---@class vim.net.request.Response
38---
39---The HTTP body of the request
40---@field body string
41
42--- Makes an HTTP request to the given URL, asynchronously passing the result to the specified
43--- `on_response`, `outpath` or `outbuf`.
44---
45--- Examples:
46--- ```lua
47--- -- Write response body to file.
48--- vim.net.request('https://neovim.io/charter/', {
49---   outpath = 'vision.html',
50--- })
51---
52--- -- Process the response.
53--- vim.net.request(
54---   'https://api.github.com/repos/neovim/neovim',
55---   {},
56---   function (err, res)
57---     if err then return end
58---     local stars = vim.json.decode(res.body).stargazers_count
59---     vim.print(('Neovim currently has %d stars'):format(stars))
60---   end
61--- )
62---
63--- -- Write to both file and current buffer, but cancel it.
64--- local job = vim.net.request('https://neovim.io/charter/', {
65---   outpath = 'vision.html',
66---   outbuf = 0,
67--- })
68--- job:close()
69---
70--- -- Add custom headers in the request.
71--- vim.net.request('https://neovim.io/charter/', {
72---   headers = { Authorization = 'Bearer XYZ' },
73--- })
74---
75--- -- POST request with body.
76--- vim.net.request('POST', 'https://example.com/api', {
77---   body = '{"key": "value"}',
78---   headers = {['Content-Type'] = 'application/json' }
79--- })
80--- ```
81---
82--- @param method vim.net.HttpMethod (default: GET) The HTTP method (GET, POST, PUT, PATCH, HEAD, DELETE).
83--- @param url string The URL for the request.
84--- @param opts? vim.net.request.Opts
85--- @param on_response? vim.net.request.ResponseFunc Callback invoked on request completion.
86--- @overload fun(url: string, opts: vim.net.request.Opts, response: vim.net.request.ResponseFunc)
87--- @overload fun(method: vim.net.HttpMethod, url: string, opts: vim.net.request.Opts, response: vim.net.request.ResponseFunc)
88--- @return { close: fun() } # Object with `close()` method which cancels the request.
89function M.request(method, url, opts, on_response)
90  if type(url) ~= 'string' then
91    on_response = opts --[[@as vim.net.request.ResponseFunc?]]
92    opts = url --[[@as vim.net.request.Opts?]]
93    url = method
94    method = 'GET'
95  end
96  opts = opts or {}
97
98  vim.validate('method', method, function(m)
99    return http_methods[m] == true
100  end, 'method should be one of GET, POST, PUT, PATCH, HEAD, DELETE')
101  vim.validate('url', url, 'string')
102  vim.validate('opts', opts, 'table', true)
103  vim.validate('opts.headers', opts.headers, 'table', true)
104  vim.validate('opts.body', opts.body, function(b)
105    return (b == nil and true) or (type(b) == 'string' and not b:match('^@'))
106  end, true, 'body should be string and not start with @')
107  vim.validate('on_response', on_response, 'function', true)
108  ---@cast on_response vim.net.request.ResponseFunc?
109
110  local retry = opts.retry or 3
111
112  -- Build curl command
113  local args = { 'curl' }
114  if opts.verbose then
115    table.insert(args, '--verbose')
116  else
117    vim.list_extend(args, { '--silent', '--show-error', '--fail' })
118  end
119  vim.list_extend(args, { '--location', '--retry', tostring(retry) })
120
121  if opts.outpath then
122    vim.list_extend(args, { '--output', opts.outpath })
123  end
124
125  -- curl -X HEAD does not work and advises to use --head instead
126  vim.list_extend(args, method == 'HEAD' and { '--head' } or { '--request', method })
127
128  if vim.list_contains({ 'POST', 'PUT', 'PATCH' }, method) and opts.body then
129    vim.list_extend(args, { '--data-binary', '@-' })
130  end
131
132  if opts.headers then
133    for key, value in pairs(opts.headers) do
134      if type(key) ~= 'string' or type(value) ~= 'string' then
135        error('headers keys and values must be strings')
136      end
137
138      if key:match(':$') or key:match(';$') or key:match('^@') then
139        error('header keys must not start with @ or end with : and ;')
140      end
141
142      if value == '' then
143        vim.list_extend(args, { '--header', key .. ';' })
144      else
145        vim.list_extend(args, { '--header', key .. ': ' .. value })
146      end
147    end
148  end
149
150  table.insert(args, url)
151
152  local system_opts = opts.body and { stdin = opts.body } or {}
153  local job = vim.system(args, system_opts, function(res)
154    --- @cast res.stdout -?
155    ---@type string?, vim.net.request.Response?
156    local err, response = nil, nil
157    if res.signal ~= 0 then
158      err = ('Request killed with signal %d'):format(res.signal)
159    elseif res.code ~= 0 then
160      err = res.stderr ~= '' and res.stderr or ('Request failed with exit code %d'):format(res.code)
161    else
162      if on_response then
163        response = { body = res.stdout or '' }
164      end
165    end
166
167    -- nvim_buf_is_loaded and nvim_buf_set_lines are not allowed in fast context
168    vim.schedule(function()
169      if res.code == 0 and opts.outbuf and vim.api.nvim_buf_is_loaded(opts.outbuf) then
170        local lines = vim.split(res.stdout, '\n', { plain = true })
171        vim.api.nvim_buf_set_lines(opts.outbuf, 0, -1, true, lines)
172      end
173    end)
174
175    if on_response then
176      on_response(err, response)
177    end
178  end)
179
180  return {
181    close = function()
182      job:kill('sigint')
183    end,
184  }
185end
186
187return M