@tilua-types/sunc 11.1.5 → 11.2.1

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.
package/runtime/sunc.luau CHANGED
@@ -267,11 +267,953 @@ local function built(options)
267
267
  return copy
268
268
  end
269
269
 
270
+ -- Some executors (Solara) fail with "Can't parse JSON" when `Headers` is an
271
+ -- empty table, as they send it on as JSON `[]`: one with no headers is sent
272
+ -- without the field.
273
+ local function withoutEmptyHeaders(options)
274
+ if type(options) ~= "table" or type(options.Headers) ~= "table" or next(options.Headers) ~= nil then
275
+ return options
276
+ end
277
+ local copy = {}
278
+ for key, value in pairs(options) do
279
+ copy[key] = value
280
+ end
281
+ copy.Headers = nil
282
+ return copy
283
+ end
284
+
270
285
  __NAME__.http = {
271
286
  request = send and function(options)
272
287
  if type(options) == "function" then
273
- return send(built(options(types)))
288
+ return send(withoutEmptyHeaders(built(options(types))))
274
289
  end
275
- return send(options)
290
+ return send(withoutEmptyHeaders(options))
276
291
  end or nil,
277
292
  }
293
+
294
+ -- ============================================================
295
+ -- What this project keeps: executor.fingerprint, env.getmain
296
+ -- ============================================================
297
+ --
298
+ -- A table every script of this project shares — what `env.getmain()` answers,
299
+ -- and the HTTP cache beside it — kept in the first of `getgenv()`, `shared`
300
+ -- and `_G` there is. It is kept under a name nothing else can look up, as the
301
+ -- bridge names its remotes: the HMAC of this machine's fingerprint under the
302
+ -- project's secret, which the compiler writes in. Another
303
+ -- script sees one more key of random hex; only this project's scripts, on this
304
+ -- machine, know which.
305
+ --
306
+ -- The SHA-256, HMAC and AES-GCM are @tilua-types/crypto's runtime, put here
307
+ -- by the compiler and set up the first time it is needed.
308
+
309
+ local SECRET = __SECRET__
310
+
311
+ local freeze = table.freeze or function(t)
312
+ return t
313
+ end
314
+
315
+ local loadCrypto = __CRYPTO__
316
+ local cryptoLib
317
+
318
+ local function lib()
319
+ if cryptoLib == nil then
320
+ cryptoLib = loadCrypto()
321
+ end
322
+ return cryptoLib
323
+ end
324
+
325
+ local function hmacHex(key, text)
326
+ return lib().hmacSha256(key, text).hex
327
+ end
328
+
329
+ -- The fingerprint, as FingerprintJS makes a browser's: many components, each
330
+ -- something this machine and executor answer the same way on every run, put
331
+ -- together and hashed. A component that cannot be read is left out, as one
332
+ -- the browser does not have. Nothing timed (a benchmark of the CPU is
333
+ -- different on every run), nothing a player changes as they play (the
334
+ -- window's size, the client's settings), and nothing that changes every week
335
+ -- (Roblox's version, the executor's version), or what is kept under the
336
+ -- fingerprint would be lost with it:
337
+ --
338
+ -- - `hwid`: the executor's `gethwid`;
339
+ -- - `clientid`: Roblox's id for the client install;
340
+ -- - `executor`: the executor's name;
341
+ -- - `capabilities`: which of the library's functions the executor has;
342
+ -- - `genv`: how many of the names sUNC and UNC define (`hookfunction`,
343
+ -- `getrawmetatable`, ...) are a function in `getgenv()`. Only those
344
+ -- names: whatever else a script put there does not count;
345
+ -- - `math`: what the CPU and the C library make of awkward floating-point
346
+ -- arguments, as FingerprintJS's `math` component;
347
+ -- - `quirks`: what the executor's own functions answer for a fixed input —
348
+ -- its base64 of edge bytes, its LZ4, its SHA-256 — where executors differ;
349
+ -- - `locale`: the system's locale;
350
+ -- - `timezone`: the offset from UTC in January and in July, which is the
351
+ -- timezone and its daylight saving, the same all year;
352
+ -- - `platform`: touch, keyboard, mouse, the platform and a ten-foot
353
+ -- interface.
354
+
355
+ local components
356
+
357
+ -- Every global of the executor's this library reads, written in by the
358
+ -- compiler from the names the runtime hands to `pick`
359
+ local SUNC_NAMES = __SUNC_NAMES__
360
+
361
+ local function shortHash(text)
362
+ return string.sub(lib().sha256(text).hex, 1, 16)
363
+ end
364
+
365
+ local function sortedNames(names)
366
+ table.sort(names)
367
+ return #names .. ":" .. shortHash(table.concat(names, ","))
368
+ end
369
+
370
+ local function utcOffset(t)
371
+ local here, utc = os.date("*t", t), os.date("!*t", t)
372
+ here.isdst, utc.isdst = false, false
373
+ return os.time(here) - os.time(utc)
374
+ end
375
+
376
+ local COMPONENTS = {
377
+ hwid = function()
378
+ return __NAME__.executor.hwid()
379
+ end,
380
+ clientid = function()
381
+ return game:GetService("RbxAnalyticsService"):GetClientId()
382
+ end,
383
+ executor = function()
384
+ return __NAME__.executor.identify()[1]
385
+ end,
386
+ capabilities = function()
387
+ local names = {}
388
+ for space, members in pairs(__NAME__) do
389
+ if type(members) == "table" then
390
+ for member, value in pairs(members) do
391
+ if type(value) == "function" then
392
+ names[#names + 1] = space .. "." .. member
393
+ end
394
+ end
395
+ end
396
+ end
397
+ return sortedNames(names)
398
+ end,
399
+ genv = function()
400
+ local genv = __NAME__.env.getgenv()
401
+ local count = 0
402
+ for _, name in SUNC_NAMES do
403
+ local ok, value = pcall(function()
404
+ return genv[name]
405
+ end)
406
+ if ok and type(value) == "function" then
407
+ count = count + 1
408
+ end
409
+ end
410
+ return count
411
+ end,
412
+ math = function()
413
+ local values = {
414
+ math.acos(0.123124234234234242), math.asin(0.123124234234234242), math.atan(0.5),
415
+ math.atan2(-0.1, -1e-300), math.cos(21 * math.pi), math.sin(-1e300), math.tan(-1e300),
416
+ math.exp(1), math.log(1e300), math.log10(7), math.sinh(1), math.cosh(1), math.tanh(1),
417
+ math.pow(math.pi, -100), math.sqrt(2), math.fmod(1e300, 0.1),
418
+ }
419
+ local ok, noise = pcall(function()
420
+ return math.noise(0.4, 1.7, 2.3)
421
+ end)
422
+ if ok then
423
+ values[#values + 1] = noise
424
+ end
425
+ for i, value in values do
426
+ values[i] = string.format("%.17g", value)
427
+ end
428
+ return shortHash(table.concat(values, ","))
429
+ end,
430
+ quirks = function()
431
+ local parts = {}
432
+ local function add(f)
433
+ local ok, value = pcall(f)
434
+ parts[#parts + 1] = ok and tostring(value) or "-"
435
+ end
436
+ add(function()
437
+ return __NAME__.encoding.base64encode("\0\1\127\128\255tilua")
438
+ end)
439
+ add(function()
440
+ return shortHash(__NAME__.encoding.lz4compress(string.rep("tilua-sunc ", 16)))
441
+ end)
442
+ add(function()
443
+ return __NAME__.crypt.hash("tilua", "sha256")
444
+ end)
445
+ return shortHash(table.concat(parts, "|"))
446
+ end,
447
+ locale = function()
448
+ return game:GetService("LocalizationService").SystemLocaleId
449
+ end,
450
+ timezone = function()
451
+ return utcOffset(1577836800) .. "/" .. utcOffset(1593561600)
452
+ end,
453
+ platform = function()
454
+ local input = game:GetService("UserInputService")
455
+ local parts = { tostring(input.TouchEnabled), tostring(input.KeyboardEnabled), tostring(input.MouseEnabled) }
456
+ local ok, platform = pcall(function()
457
+ return input:GetPlatform()
458
+ end)
459
+ parts[#parts + 1] = ok and tostring(platform) or "-"
460
+ local tenFoot
461
+ ok, tenFoot = pcall(function()
462
+ return game:GetService("GuiService"):IsTenFootInterface()
463
+ end)
464
+ parts[#parts + 1] = ok and tostring(tenFoot) or "-"
465
+ return table.concat(parts, ",")
466
+ end,
467
+ }
468
+
469
+ local function collect()
470
+ if components == nil then
471
+ components = {}
472
+ for name, read in pairs(COMPONENTS) do
473
+ local ok, value = pcall(read)
474
+ if ok and value ~= nil then
475
+ components[name] = tostring(value)
476
+ end
477
+ end
478
+ freeze(components)
479
+ end
480
+ return components
481
+ end
482
+
483
+ local machineText
484
+
485
+ local function machine()
486
+ if machineText == nil then
487
+ local lines = {}
488
+ for name, value in pairs(collect()) do
489
+ lines[#lines + 1] = name .. "=" .. value
490
+ end
491
+ table.sort(lines)
492
+ machineText = table.concat(lines, "\n")
493
+ end
494
+ return machineText
495
+ end
496
+
497
+ __NAME__.executor.fingerprint = function(salt)
498
+ return hmacHex(type(salt) == "string" and salt or "tilua-sunc", machine())
499
+ end
500
+
501
+ __NAME__.executor.components = function()
502
+ local copy = {}
503
+ for name, value in pairs(collect()) do
504
+ copy[name] = value
505
+ end
506
+ return copy
507
+ end
508
+
509
+ local ROOT_VERSION = 1
510
+ local rootKey
511
+
512
+ local function holder()
513
+ local getgenv = __NAME__.env.getgenv
514
+ if getgenv then
515
+ local ok, genv = pcall(getgenv)
516
+ if ok and type(genv) == "table" then
517
+ return genv
518
+ end
519
+ end
520
+ if type(shared) == "table" then
521
+ return shared
522
+ end
523
+ return _G
524
+ end
525
+
526
+ local function root()
527
+ if rootKey == nil then
528
+ rootKey = string.sub(hmacHex(SECRET, "main\n" .. machine()), 1, 24)
529
+ end
530
+ local where = holder()
531
+ local found = rawget(where, rootKey)
532
+ if type(found) ~= "table" or found.version ~= ROOT_VERSION then
533
+ local globals = type(found) == "table" and type(found.globals) == "table" and found.globals or {}
534
+ found = { version = ROOT_VERSION, globals = globals, http = { entries = {}, count = 0, clock = 0 } }
535
+ rawset(where, rootKey, found)
536
+ end
537
+ return found
538
+ end
539
+
540
+ __NAME__.env.getmain = function()
541
+ return root().globals
542
+ end
543
+
544
+ -- ============================================================
545
+ -- http.to(url): an immutable request builder, cached as a browser does
546
+ -- ============================================================
547
+ --
548
+ -- Every method answers a new builder and leaves the one it was called on as it
549
+ -- was, so one with a base URL and headers can be kept and built on. What a
550
+ -- builder holds is in `states`, out of the builder itself: the builder is an
551
+ -- empty frozen table.
552
+ --
553
+ -- A GET is cached the way a browser's private cache does (RFC 9111): the
554
+ -- response's `Cache-Control` (`max-age`, `no-store`, `no-cache`,
555
+ -- `must-revalidate`), `Expires` and `Date`, `Age`, a guess from
556
+ -- `Last-Modified` when nothing says how long, `Vary`, and revalidation with
557
+ -- `If-None-Match` / `If-Modified-Since`, a 304 refreshing what was kept. The
558
+ -- request's own `Cache-Control` (`no-store`, `no-cache`, `max-age`,
559
+ -- `max-stale`, `min-fresh`, `only-if-cached`) and `Pragma: no-cache` are
560
+ -- honoured, and `:cache(mode)` takes fetch's modes. A POST, PUT, PATCH or
561
+ -- DELETE that succeeds forgets what was kept for its URL.
562
+ --
563
+ -- What is kept is in memory, in the table `env.getmain()` sits beside, and on
564
+ -- disk when the executor has a filesystem: one file a URL, in a folder, both
565
+ -- named by HMACs, each sealed with AES-GCM under a key from the project's
566
+ -- secret and this machine.
567
+
568
+ local CACHEABLE = {
569
+ [200] = true, [203] = true, [204] = true, [300] = true, [301] = true, [308] = true,
570
+ [404] = true, [405] = true, [410] = true, [414] = true, [501] = true,
571
+ }
572
+ local UNSAFE = { POST = true, PUT = true, PATCH = true, DELETE = true }
573
+ -- The longest a response is guessed fresh for from its Last-Modified
574
+ local HEURISTIC_LIMIT = 86400
575
+ -- Entries kept in memory; past it the least recently used goes (its file stays)
576
+ local MEMORY_LIMIT = 128
577
+ -- Varied on whether the response says so or not: one URL asked with two
578
+ -- tokens is two answers
579
+ local ALWAYS_VARY = { "authorization" }
580
+
581
+ local function lowerHeaders(headers)
582
+ local out = {}
583
+ if type(headers) == "table" then
584
+ for key, value in pairs(headers) do
585
+ if type(key) == "string" then
586
+ out[string.lower(key)] = tostring(value)
587
+ end
588
+ end
589
+ end
590
+ return out
591
+ end
592
+
593
+ local function copyOf(t)
594
+ local out = {}
595
+ for key, value in pairs(t) do
596
+ out[key] = value
597
+ end
598
+ return out
599
+ end
600
+
601
+ -- `Cache-Control` as `{ ["max-age"] = "60", ["no-cache"] = true }`
602
+ local function directives(value)
603
+ local out = {}
604
+ if type(value) ~= "string" then
605
+ return out
606
+ end
607
+ for part in string.gmatch(value, "[^,]+") do
608
+ local name, argument = string.match(part, "^%s*([^=%s]+)%s*=%s*\"?([^\"]*)\"?%s*$")
609
+ if name then
610
+ out[string.lower(name)] = argument
611
+ else
612
+ name = string.match(part, "^%s*(.-)%s*$")
613
+ if name ~= "" then
614
+ out[string.lower(name)] = true
615
+ end
616
+ end
617
+ end
618
+ return out
619
+ end
620
+
621
+ local function seconds(value)
622
+ if type(value) ~= "string" then
623
+ return nil
624
+ end
625
+ return tonumber(string.match(value, "^%s*(%d+)%s*$"))
626
+ end
627
+
628
+ local MONTHS = {
629
+ jan = 1, feb = 2, mar = 3, apr = 4, may = 5, jun = 6,
630
+ jul = 7, aug = 8, sep = 9, oct = 10, nov = 11, dec = 12,
631
+ }
632
+
633
+ -- Days from 1970-01-01 to a date of the proleptic Gregorian calendar
634
+ local function daysFromCivil(y, m, d)
635
+ if m <= 2 then
636
+ y = y - 1
637
+ end
638
+ local era = math.floor(y / 400)
639
+ local yearOfEra = y - era * 400
640
+ local dayOfYear = math.floor((153 * ((m + 9) % 12) + 2) / 5) + d - 1
641
+ local dayOfEra = yearOfEra * 365 + math.floor(yearOfEra / 4) - math.floor(yearOfEra / 100) + dayOfYear
642
+ return era * 146097 + dayOfEra - 719468
643
+ end
644
+
645
+ -- An HTTP date as Unix seconds: `Sun, 06 Nov 1994 08:49:37 GMT`, the RFC 850
646
+ -- form and asctime's. Nil for anything else.
647
+ local function httpDate(value)
648
+ if type(value) ~= "string" then
649
+ return nil
650
+ end
651
+ local d, mon, y, h, mi, s = string.match(value, "(%d%d?)[ %-](%a%a%a)[ %-](%d+) (%d%d):(%d%d):(%d%d)")
652
+ if not d then
653
+ mon, d, h, mi, s, y = string.match(value, "(%a%a%a) +(%d%d?) (%d%d):(%d%d):(%d%d) (%d%d%d%d)")
654
+ end
655
+ local month = mon and MONTHS[string.lower(mon)]
656
+ if not month then
657
+ return nil
658
+ end
659
+ local year = tonumber(y)
660
+ if year < 100 then
661
+ year = year + (year < 70 and 2000 or 1900)
662
+ end
663
+ return daysFromCivil(year, month, tonumber(d)) * 86400 + tonumber(h) * 3600 + tonumber(mi) * 60 + tonumber(s)
664
+ end
665
+
666
+ -- What a response is kept as, or nil when it is not to be kept
667
+ local function makeEntry(url, requestHeaders, status, statusText, headers, body, requestTime, responseTime)
668
+ local control = directives(headers["cache-control"])
669
+ if control["no-store"] then
670
+ return nil
671
+ end
672
+ local vary = {}
673
+ for _, name in ALWAYS_VARY do
674
+ vary[name] = requestHeaders[name] or ""
675
+ end
676
+ if headers["vary"] then
677
+ for name in string.gmatch(headers["vary"], "[^,%s]+") do
678
+ if name == "*" then
679
+ return nil
680
+ end
681
+ name = string.lower(name)
682
+ vary[name] = requestHeaders[name] or ""
683
+ end
684
+ end
685
+ local date = httpDate(headers["date"]) or responseTime
686
+ local initialAge = math.max(responseTime - date, seconds(headers["age"]) or 0) + (responseTime - requestTime)
687
+ local lifetime = 0
688
+ local maxAge = seconds(control["max-age"])
689
+ if maxAge then
690
+ lifetime = maxAge
691
+ elseif headers["expires"] then
692
+ local expires = httpDate(headers["expires"])
693
+ lifetime = expires and math.max(0, expires - date) or 0
694
+ elseif headers["last-modified"] then
695
+ local modified = httpDate(headers["last-modified"])
696
+ lifetime = modified and math.min(HEURISTIC_LIMIT, math.max(0, math.floor((date - modified) / 10))) or 0
697
+ end
698
+ local etag, lastModified = headers["etag"], headers["last-modified"]
699
+ -- Never to be fresh again and unable to be revalidated: no use keeping
700
+ if etag == nil and lastModified == nil and math.max(0, initialAge) >= lifetime then
701
+ return nil
702
+ end
703
+ return {
704
+ url = url,
705
+ status = status,
706
+ statusText = statusText,
707
+ headers = headers,
708
+ body = body,
709
+ responseTime = responseTime,
710
+ initialAge = math.max(0, initialAge),
711
+ lifetime = lifetime,
712
+ vary = vary,
713
+ etag = etag,
714
+ lastModified = lastModified,
715
+ noCache = control["no-cache"] ~= nil,
716
+ mustRevalidate = control["must-revalidate"] ~= nil,
717
+ }
718
+ end
719
+
720
+ local function currentAge(entry)
721
+ return entry.initialAge + math.max(0, os.time() - entry.responseTime)
722
+ end
723
+
724
+ local function varyMatches(entry, requestHeaders)
725
+ for name, value in pairs(entry.vary) do
726
+ if (requestHeaders[name] or "") ~= value then
727
+ return false
728
+ end
729
+ end
730
+ return true
731
+ end
732
+
733
+ -- "use" what was kept, "validate" it with the server, or "fetch" anew
734
+ local function decide(entry, control, mode)
735
+ if mode == "force-cache" then
736
+ return "use"
737
+ end
738
+ local canValidate = entry.etag ~= nil or entry.lastModified ~= nil
739
+ local otherwise = canValidate and "validate" or "fetch"
740
+ if mode == "no-cache" or control["no-cache"] or entry.noCache then
741
+ return otherwise
742
+ end
743
+ local age = currentAge(entry)
744
+ local maxAge = seconds(control["max-age"])
745
+ local minFresh = seconds(control["min-fresh"]) or 0
746
+ if age + minFresh < entry.lifetime and (maxAge == nil or age <= maxAge) then
747
+ return "use"
748
+ end
749
+ local maxStale = control["max-stale"]
750
+ if maxStale ~= nil and not entry.mustRevalidate and (maxAge == nil or age <= maxAge) then
751
+ local allowed = seconds(maxStale)
752
+ if maxStale == true or (allowed and age - entry.lifetime <= allowed) then
753
+ return "use"
754
+ end
755
+ end
756
+ return otherwise
757
+ end
758
+
759
+ --------------------------------------------------------------------------------
760
+ -- Where entries are kept
761
+ --------------------------------------------------------------------------------
762
+
763
+ local fs = __NAME__.fs
764
+ local hasDisk = fs.read ~= nil and fs.write ~= nil and fs.isfile ~= nil and fs.isfolder ~= nil
765
+ and fs.makefolder ~= nil and fs.delete ~= nil
766
+ local disk
767
+
768
+ local function diskState()
769
+ if disk == nil then
770
+ local fingerprint = machine()
771
+ local key = lib().hmacSha256(SECRET, "disk\n" .. fingerprint).bytes
772
+ disk = {
773
+ folder = string.sub(hmacHex(SECRET, "folder\n" .. fingerprint), 1, 24),
774
+ fingerprint = fingerprint,
775
+ sealer = lib().aesGcm.context(key),
776
+ }
777
+ end
778
+ return disk
779
+ end
780
+
781
+ local function pathOf(url)
782
+ local state = diskState()
783
+ return state.folder .. "/" .. string.sub(hmacHex(SECRET, "file\n" .. state.fingerprint .. "\n" .. url), 1, 32)
784
+ end
785
+
786
+ local KEPT = {
787
+ "url", "status", "statusText", "headers", "responseTime", "initialAge", "lifetime",
788
+ "vary", "etag", "lastModified", "noCache", "mustRevalidate",
789
+ }
790
+
791
+ -- The entry's fields as JSON, a newline, then the body as it is: JSON writes
792
+ -- control characters escaped, so the first newline is the end of the fields
793
+ local function writeDisk(url, entry)
794
+ if not hasDisk then
795
+ return
796
+ end
797
+ pcall(function()
798
+ local state = diskState()
799
+ local fields = {}
800
+ for _, name in KEPT do
801
+ fields[name] = entry[name]
802
+ end
803
+ local path = pathOf(url)
804
+ local sealed = state.sealer.encrypt(__JSON__.encode(fields) .. "\n" .. entry.body, { aad = path })
805
+ if not fs.isfolder(state.folder) then
806
+ fs.makefolder(state.folder)
807
+ end
808
+ fs.write(path, lib().base64.encode(sealed.iv .. sealed.tag .. sealed.ciphertext))
809
+ end)
810
+ end
811
+
812
+ local function deleteDisk(url)
813
+ if not hasDisk then
814
+ return
815
+ end
816
+ pcall(function()
817
+ local path = pathOf(url)
818
+ if fs.isfile(path) then
819
+ fs.delete(path)
820
+ end
821
+ end)
822
+ end
823
+
824
+ local function readDisk(url)
825
+ if not hasDisk then
826
+ return nil
827
+ end
828
+ local ok, entry = pcall(function()
829
+ local path = pathOf(url)
830
+ if not fs.isfile(path) then
831
+ return nil
832
+ end
833
+ local raw = lib().base64.decode(fs.read(path))
834
+ local text = diskState().sealer.decrypt({
835
+ iv = string.sub(raw, 1, 12),
836
+ tag = string.sub(raw, 13, 28),
837
+ ciphertext = string.sub(raw, 29),
838
+ }, path)
839
+ local split = text and string.find(text, "\n", 1, true)
840
+ if not split then
841
+ -- Not sealed by this project on this machine, or damaged
842
+ fs.delete(path)
843
+ return nil
844
+ end
845
+ local fields = __JSON__.decode(string.sub(text, 1, split - 1))
846
+ if type(fields) ~= "table" or fields.url ~= url then
847
+ return nil
848
+ end
849
+ fields.body = string.sub(text, split + 1)
850
+ return fields
851
+ end)
852
+ return ok and entry or nil
853
+ end
854
+
855
+ local function memory()
856
+ return root().http
857
+ end
858
+
859
+ local function remember(url, entry)
860
+ local kept = memory()
861
+ kept.clock = kept.clock + 1
862
+ entry.used = kept.clock
863
+ if kept.entries[url] == nil then
864
+ kept.count = kept.count + 1
865
+ end
866
+ kept.entries[url] = entry
867
+ while kept.count > MEMORY_LIMIT do
868
+ local oldest, oldestUrl = math.huge, nil
869
+ for key, value in pairs(kept.entries) do
870
+ if value.used < oldest then
871
+ oldest, oldestUrl = value.used, key
872
+ end
873
+ end
874
+ kept.entries[oldestUrl] = nil
875
+ kept.count = kept.count - 1
876
+ end
877
+ end
878
+
879
+ local function lookup(url)
880
+ local entry = memory().entries[url]
881
+ if entry == nil then
882
+ entry = readDisk(url)
883
+ if entry then
884
+ remember(url, entry)
885
+ end
886
+ end
887
+ return entry
888
+ end
889
+
890
+ local function store(url, entry)
891
+ remember(url, entry)
892
+ writeDisk(url, entry)
893
+ end
894
+
895
+ local function forget(url)
896
+ local kept = memory()
897
+ if kept.entries[url] ~= nil then
898
+ kept.entries[url] = nil
899
+ kept.count = kept.count - 1
900
+ end
901
+ deleteDisk(url)
902
+ end
903
+
904
+ local function clearCache()
905
+ local kept = memory()
906
+ kept.entries = {}
907
+ kept.count = 0
908
+ if hasDisk then
909
+ pcall(function()
910
+ local folder = diskState().folder
911
+ if not fs.isfolder(folder) then
912
+ return
913
+ end
914
+ if fs.deletefolder then
915
+ fs.deletefolder(folder)
916
+ elseif fs.list then
917
+ for _, path in fs.list(folder) do
918
+ fs.delete(path)
919
+ end
920
+ end
921
+ end)
922
+ end
923
+ end
924
+
925
+ --------------------------------------------------------------------------------
926
+ -- Responses
927
+ --------------------------------------------------------------------------------
928
+
929
+ local Result = {}
930
+ Result.__index = Result
931
+
932
+ function Result.json(self)
933
+ return __JSON__.decode(self.body)
934
+ end
935
+
936
+ local function result(url, status, statusText, headers, body, fromCache)
937
+ return freeze(setmetatable({
938
+ url = url,
939
+ status = status,
940
+ statusText = statusText or "",
941
+ ok = status >= 200 and status < 300,
942
+ headers = freeze(copyOf(headers)),
943
+ body = body,
944
+ fromCache = fromCache,
945
+ }, Result))
946
+ end
947
+
948
+ local function fromEntry(entry, fresh)
949
+ local kept = memory()
950
+ kept.clock = kept.clock + 1
951
+ entry.used = kept.clock
952
+ local headers = copyOf(entry.headers)
953
+ headers["age"] = tostring(math.floor(currentAge(entry)))
954
+ return result(entry.url, entry.status, entry.statusText, headers, entry.body, fresh)
955
+ end
956
+
957
+ --------------------------------------------------------------------------------
958
+ -- The builder
959
+ --------------------------------------------------------------------------------
960
+
961
+ local Builder = {}
962
+ Builder.__index = Builder
963
+
964
+ local states = setmetatable({}, { __mode = "k" })
965
+
966
+ local function make(state)
967
+ local builder = freeze(setmetatable({}, Builder))
968
+ states[builder] = freeze(state)
969
+ return builder
970
+ end
971
+
972
+ local function stateOf(builder, method)
973
+ local state = states[builder]
974
+ if state == nil then
975
+ error(("http builder:%s: call it with `:` on a builder"):format(method), 3)
976
+ end
977
+ return state
978
+ end
979
+
980
+ -- A copy of the builder's state with `changes` made to it
981
+ local function derive(builder, method, changes)
982
+ local state = copyOf(stateOf(builder, method))
983
+ for key, value in pairs(changes) do
984
+ state[key] = value
985
+ end
986
+ return make(state)
987
+ end
988
+
989
+ local function encodeComponent(value)
990
+ return (string.gsub(tostring(value), "[^%w%-%._~]", function(c)
991
+ return string.format("%%%02X", string.byte(c))
992
+ end))
993
+ end
994
+
995
+ -- Headers are kept by their name in lower case, as `{ name, value }`, so one
996
+ -- set twice in two cases is one header
997
+ local function withHeader(headers, name, value)
998
+ local out = copyOf(headers)
999
+ out[string.lower(name)] = value ~= nil and freeze({ name, tostring(value) }) or nil
1000
+ return freeze(out)
1001
+ end
1002
+
1003
+ function Builder.path(self, path)
1004
+ local url = stateOf(self, "path").url
1005
+ local main, rest = string.match(url, "^([^?#]*)(.*)$")
1006
+ path = tostring(path)
1007
+ if path == "" then
1008
+ return self
1009
+ end
1010
+ main = string.gsub(main, "/+$", "")
1011
+ path = string.gsub(path, "^/+", "")
1012
+ return derive(self, "path", { url = main .. "/" .. path .. rest })
1013
+ end
1014
+
1015
+ function Builder.query(self, name, value)
1016
+ local query = copyOf(stateOf(self, "query").query)
1017
+ if type(name) == "table" then
1018
+ local keys = {}
1019
+ for key in pairs(name) do
1020
+ keys[#keys + 1] = tostring(key)
1021
+ end
1022
+ table.sort(keys)
1023
+ for _, key in keys do
1024
+ query[#query + 1] = encodeComponent(key) .. "=" .. encodeComponent(name[key])
1025
+ end
1026
+ else
1027
+ query[#query + 1] = encodeComponent(name) .. "=" .. encodeComponent(value)
1028
+ end
1029
+ return derive(self, "query", { query = freeze(query) })
1030
+ end
1031
+
1032
+ function Builder.header(self, name, value)
1033
+ return derive(self, "header", { headers = withHeader(stateOf(self, "header").headers, name, value) })
1034
+ end
1035
+
1036
+ function Builder.headers(self, headers)
1037
+ local out = stateOf(self, "headers").headers
1038
+ for name, value in pairs(headers) do
1039
+ out = withHeader(out, name, value)
1040
+ end
1041
+ return derive(self, "headers", { headers = out })
1042
+ end
1043
+
1044
+ function Builder.cookie(self, name, value)
1045
+ local cookies = copyOf(stateOf(self, "cookie").cookies)
1046
+ cookies[name] = value
1047
+ return derive(self, "cookie", { cookies = freeze(cookies) })
1048
+ end
1049
+
1050
+ function Builder.method(self, method)
1051
+ stateOf(self, "method")
1052
+ return derive(self, "method", { method = string.upper(method) })
1053
+ end
1054
+
1055
+ function Builder.body(self, body, contentType)
1056
+ local headers = stateOf(self, "body").headers
1057
+ if contentType ~= nil then
1058
+ headers = withHeader(headers, "Content-Type", contentType)
1059
+ end
1060
+ return derive(self, "body", { body = tostring(body), headers = headers })
1061
+ end
1062
+
1063
+ function Builder.json(self, value)
1064
+ local headers = stateOf(self, "json").headers
1065
+ if type(value) == "function" then
1066
+ value = value(types)
1067
+ end
1068
+ if headers["content-type"] == nil then
1069
+ headers = withHeader(headers, "Content-Type", "application/json")
1070
+ end
1071
+ return derive(self, "json", { body = __JSON__.encode(value), headers = headers })
1072
+ end
1073
+
1074
+ function Builder.cache(self, mode)
1075
+ stateOf(self, "cache")
1076
+ return derive(self, "cache", { cache = mode })
1077
+ end
1078
+
1079
+ local function urlOf(state)
1080
+ local url = string.match(state.url, "^([^#]*)")
1081
+ if #state.query == 0 then
1082
+ return url
1083
+ end
1084
+ return url .. (string.find(url, "?", 1, true) and "&" or "?") .. table.concat(state.query, "&")
1085
+ end
1086
+
1087
+ local function requestOf(state)
1088
+ local headers = {}
1089
+ for _, header in pairs(state.headers) do
1090
+ headers[header[1]] = header[2]
1091
+ end
1092
+ return {
1093
+ Url = urlOf(state),
1094
+ Method = state.method,
1095
+ -- Left out when there are none: see withoutEmptyHeaders
1096
+ Headers = next(headers) ~= nil and headers or nil,
1097
+ Body = state.body,
1098
+ Cookies = next(state.cookies) ~= nil and copyOf(state.cookies) or nil,
1099
+ }
1100
+ end
1101
+
1102
+ function Builder.build(self)
1103
+ return requestOf(stateOf(self, "build"))
1104
+ end
1105
+
1106
+ local function perform(state)
1107
+ local options = requestOf(state)
1108
+ local url = options.Url
1109
+ local method = options.Method
1110
+ local requestHeaders = lowerHeaders(options.Headers)
1111
+ local control = directives(requestHeaders["cache-control"])
1112
+ if requestHeaders["cache-control"] == nil and requestHeaders["pragma"]
1113
+ and string.find(string.lower(requestHeaders["pragma"]), "no-cache", 1, true) then
1114
+ control["no-cache"] = true
1115
+ end
1116
+ local mode = state.cache
1117
+ if control["no-store"] then
1118
+ mode = "no-store"
1119
+ elseif control["only-if-cached"] then
1120
+ mode = "only-if-cached"
1121
+ end
1122
+
1123
+ local cacheable = method == "GET"
1124
+ local entry
1125
+ if cacheable and mode ~= "no-store" and mode ~= "reload" then
1126
+ entry = lookup(url)
1127
+ if entry and not varyMatches(entry, requestHeaders) then
1128
+ entry = nil
1129
+ end
1130
+ end
1131
+ if mode == "only-if-cached" then
1132
+ if entry then
1133
+ return fromEntry(entry, true)
1134
+ end
1135
+ return result(url, 504, "Gateway Timeout", {}, "", false)
1136
+ end
1137
+
1138
+ local revalidating = false
1139
+ if entry then
1140
+ local decision = decide(entry, control, mode)
1141
+ if decision == "use" then
1142
+ return fromEntry(entry, true)
1143
+ elseif decision == "validate" then
1144
+ options.Headers = options.Headers or {}
1145
+ if entry.etag and requestHeaders["if-none-match"] == nil then
1146
+ options.Headers["If-None-Match"] = entry.etag
1147
+ end
1148
+ if entry.lastModified and requestHeaders["if-modified-since"] == nil then
1149
+ options.Headers["If-Modified-Since"] = entry.lastModified
1150
+ end
1151
+ revalidating = true
1152
+ end
1153
+ end
1154
+
1155
+ local requestTime = os.time()
1156
+ local response = send(options)
1157
+ local responseTime = os.time()
1158
+ local status = tonumber(response.StatusCode) or 0
1159
+ local headers = lowerHeaders(response.Headers)
1160
+
1161
+ if revalidating and status == 304 then
1162
+ -- Still good: what was kept, with the headers the 304 brought
1163
+ local merged = copyOf(entry.headers)
1164
+ -- The kept Date and Age were of the first answer, not of this one
1165
+ merged["date"], merged["age"] = nil, nil
1166
+ for name, value in pairs(headers) do
1167
+ merged[name] = value
1168
+ end
1169
+ local refreshed = makeEntry(url, requestHeaders, entry.status, entry.statusText, merged, entry.body, requestTime, responseTime)
1170
+ if refreshed then
1171
+ store(url, refreshed)
1172
+ return fromEntry(refreshed, true)
1173
+ end
1174
+ forget(url)
1175
+ return result(url, entry.status, entry.statusText, merged, entry.body, true)
1176
+ end
1177
+
1178
+ local body = response.Body or ""
1179
+ if cacheable then
1180
+ local made = mode ~= "no-store" and CACHEABLE[status] and makeEntry(url, requestHeaders, status, response.StatusMessage, headers, body, requestTime, responseTime)
1181
+ if made then
1182
+ store(url, made)
1183
+ elseif entry or mode == "reload" then
1184
+ forget(url)
1185
+ end
1186
+ elseif UNSAFE[method] and status >= 200 and status < 400 then
1187
+ forget(url)
1188
+ end
1189
+ return result(url, status, response.StatusMessage, headers, body, false)
1190
+ end
1191
+
1192
+ function Builder.send(self)
1193
+ return perform(stateOf(self, "send"))
1194
+ end
1195
+
1196
+ for _, method in { "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS" } do
1197
+ local name = string.lower(method)
1198
+ Builder[name] = function(self)
1199
+ local state = copyOf(stateOf(self, name))
1200
+ state.method = method
1201
+ return perform(state)
1202
+ end
1203
+ end
1204
+
1205
+ __NAME__.http.to = send and function(url)
1206
+ if type(url) ~= "string" then
1207
+ error("http.to: a URL is a string", 2)
1208
+ end
1209
+ return make({
1210
+ url = url,
1211
+ method = "GET",
1212
+ query = freeze({}),
1213
+ headers = freeze({}),
1214
+ cookies = freeze({}),
1215
+ cache = "default",
1216
+ })
1217
+ end or nil
1218
+
1219
+ __NAME__.http.clearcache = clearCache