samagotchi 0.185.0 → 0.187.0

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.
Files changed (67) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -1
  3. data/bin/chi +2 -0
  4. data/docs/cli.md +1 -0
  5. data/docs/configuration.md +18 -0
  6. data/docs/guardrails.md +13 -0
  7. data/docs/internals/bridge.md +1 -0
  8. data/docs/internals/engine.md +15 -1
  9. data/docs/internals/inline-widgets.md +18 -0
  10. data/docs/internals/pages.md +172 -0
  11. data/docs/internals/prompt-caching.md +14 -0
  12. data/docs/internals/remote-sessions.md +7 -0
  13. data/docs/internals/web-frontend.md +5 -4
  14. data/docs/memory.md +7 -0
  15. data/docs/pages.md +150 -0
  16. data/docs/thin-clients.md +67 -2
  17. data/lib/samagotchi/bridge.rb +1 -1
  18. data/lib/samagotchi/bundles/system/manifest.yml +5 -2
  19. data/lib/samagotchi/bundles/system/self_map.md +5 -1
  20. data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
  21. data/lib/samagotchi/config.rb +3 -1
  22. data/lib/samagotchi/context_absorber.rb +5 -2
  23. data/lib/samagotchi/engine.rb +9 -2
  24. data/lib/samagotchi/inline_widgets.rb +65 -0
  25. data/lib/samagotchi/llm/chat_loop.rb +16 -2
  26. data/lib/samagotchi/page_command.rb +234 -0
  27. data/lib/samagotchi/pages/builder.rb +187 -0
  28. data/lib/samagotchi/pages/launch.rb +187 -0
  29. data/lib/samagotchi/pages/runner.rb +154 -0
  30. data/lib/samagotchi/pages/store.rb +143 -0
  31. data/lib/samagotchi/pages.rb +119 -0
  32. data/lib/samagotchi/plain_reply.rb +75 -0
  33. data/lib/samagotchi/reply_for.rb +254 -0
  34. data/lib/samagotchi/run_options.rb +1 -0
  35. data/lib/samagotchi/session_access/ask.rb +5 -2
  36. data/lib/samagotchi/session_access/contract.rb +1 -1
  37. data/lib/samagotchi/session_access/exchange/token.rb +42 -7
  38. data/lib/samagotchi/session_access/exchange.rb +5 -2
  39. data/lib/samagotchi/session_access/local.rb +4 -2
  40. data/lib/samagotchi/session_access/remote.rb +5 -1
  41. data/lib/samagotchi/session_manager/delivery.rb +36 -6
  42. data/lib/samagotchi/steer.rb +30 -8
  43. data/lib/samagotchi/turn_anchors.rb +65 -17
  44. data/lib/samagotchi/turn_checkpoint.rb +5 -3
  45. data/lib/samagotchi/version.rb +1 -1
  46. data/lib/samagotchi/web/app.rb +6 -6
  47. data/lib/samagotchi/web/ask_routes.rb +62 -17
  48. data/lib/samagotchi/web/page_routes.rb +116 -0
  49. data/lib/samagotchi/web/participant_access.rb +1 -1
  50. data/lib/samagotchi/web/public/app.js +24 -84
  51. data/lib/samagotchi/web/public/index.html +3 -0
  52. data/lib/samagotchi/web/public/page_blocks.js +58 -0
  53. data/lib/samagotchi/web/public/page_links.js +33 -0
  54. data/lib/samagotchi/web/public/page_model.js +68 -0
  55. data/lib/samagotchi/web/public/page_route.js +24 -0
  56. data/lib/samagotchi/web/public/page_table.js +74 -0
  57. data/lib/samagotchi/web/public/page_table_model.js +76 -0
  58. data/lib/samagotchi/web/public/page_view.js +218 -0
  59. data/lib/samagotchi/web/public/pages.css +77 -0
  60. data/lib/samagotchi/web/public/pages_group.js +65 -0
  61. data/lib/samagotchi/web/public/peer_text.js +22 -5
  62. data/lib/samagotchi/web/public/views.js +161 -0
  63. data/lib/samagotchi/web/session_access_routes.rb +30 -2
  64. data/lib/samagotchi/web/session_control.rb +21 -2
  65. data/lib/samagotchi/web/viewer.rb +1 -1
  66. data/lib/samagotchi/worker.rb +2 -1
  67. metadata +23 -1
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../pages"
4
+
5
+ module Samagotchi
6
+ module Pages
7
+ # The page runner: the process Launch starts for one run of one page,
8
+ # ruby -I <lib> -e 'require "samagotchi/pages/runner"; exit Samagotchi::Pages::Runner.run(ARGV)' NAME [TIMEOUT DEADLINE]
9
+ # with the page's lock on fd 3. It holds that lock while it lives and,
10
+ # given a DEADLINE (seconds from its start), stops itself and its group
11
+ # there, recording the cut: a launcher killed mid-run (chi web) leaves at
12
+ # most one bounded run, and the page "already running" until it ends.
13
+ # Requiring this file runs nothing. It loads Pages only (no engine, no
14
+ # config, no web, no plugins, no ProcessGroup), so a run is as light as a
15
+ # Ruby script, and a page's surroundings are the same from the terminal
16
+ # and from chi web.
17
+ #
18
+ # The script is loaded with a fresh module as its wrap (Kernel#load), which
19
+ # gives it `page` and keeps its own methods off Object. What the run built,
20
+ # or what it raised, goes to the output file (Store), never to stdout: a
21
+ # `puts` in a script is the script's own. A TERM (Launch's cut) is not
22
+ # rescued: the launcher records the cut itself.
23
+ module Runner
24
+ # The script's `page "Title" do |ui| … end`, once per run.
25
+ class Collector
26
+ attr_reader :builder
27
+
28
+ def dsl
29
+ collector = self
30
+ Module.new do
31
+ define_method(:page) do |title, &block|
32
+ collector.page(title, &block)
33
+ end
34
+ end
35
+ end
36
+
37
+ def page(title)
38
+ raise Refused, "a page script calls page once" if @builder
39
+
40
+ @builder = Builder.new(title)
41
+ yield @builder if block_given?
42
+ nil
43
+ end
44
+ end
45
+
46
+ # The fd Launch hands the page's lock on (Launch::LOCK_FD).
47
+ LOCK_FD = 3
48
+
49
+ module_function
50
+
51
+ # @param argv [Array<String>] [NAME] or [NAME, TIMEOUT, DEADLINE]
52
+ # @return [Integer] 0 the page ran, 1 the script failed (recorded), 2
53
+ # no such page (nothing recorded: Launch checks this first)
54
+ def run(argv)
55
+ hold_lock
56
+ name, timeout, deadline = argv
57
+ return 2 unless Pages.valid_name?(name) && File.file?(Pages.script_path(name))
58
+
59
+ # The deadline thread and the result's write take this in turn, and
60
+ # the write sets done under it: a run recorded before the deadline
61
+ # fires (an at_exit still going, the exit itself) is never
62
+ # overwritten by the cut.
63
+ recording = Mutex.new
64
+ done = [false]
65
+ arm_deadline(name, timeout, Float(deadline), recording, done) if deadline
66
+ path = Pages.script_path(name)
67
+ sha = Digest::SHA256.file(path).hexdigest
68
+ collector = Collector.new
69
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
70
+ begin
71
+ load(path, collector.dsl)
72
+ raise Refused, "the script never called page" unless collector.builder
73
+
74
+ data = collector.builder.data
75
+ ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
76
+ recording.synchronize do
77
+ Store.record_run(name, title: data["title"], blocks: data["blocks"], duration_ms: ms, script_sha: sha)
78
+ done[0] = true
79
+ end
80
+ 0
81
+ # SystemStackError (endless recursion) and NoMemoryError are no
82
+ # StandardError, but a script's own bug all the same.
83
+ rescue StandardError, ScriptError, SystemExit, SystemStackError, NoMemoryError => e
84
+ recording.synchronize do
85
+ Store.record_failure(name, message: message(e, path), line: line(e, path), script_sha: sha)
86
+ done[0] = true
87
+ end
88
+ 1
89
+ end
90
+ end
91
+
92
+ # The first act: the inherited lock fd is close-on-exec here, so the
93
+ # runner holds the lock alone. A child the script execs, even one that
94
+ # leaves the group (and so outlives the run), never inherits it: it
95
+ # would keep the page "already running" for as long as it lives. A
96
+ # runner started by hand has no lock there: fd 3 is closed (EBADF) or,
97
+ # as Ruby keeps it for itself when nothing is inherited there, refused
98
+ # (ArgumentError, "RubyVM reserves it").
99
+ def hold_lock
100
+ IO.for_fd(LOCK_FD, autoclose: false).close_on_exec = true
101
+ rescue Errno::EBADF, ArgumentError
102
+ nil
103
+ end
104
+
105
+ # At +deadline+ seconds from now the cut is recorded (a dead launcher
106
+ # can't), unless the run's own result is already written (+done+), and
107
+ # the runner's whole group is KILLed either way (it leads its group).
108
+ # A Ruby thread: it can't fire while a C extension holds the GVL
109
+ # (docs/internals/pages.md). Plain Process calls, no ProcessGroup, to
110
+ # stay light.
111
+ def arm_deadline(name, timeout, deadline, recording, done)
112
+ Thread.new do
113
+ sleep(deadline)
114
+ recording.lock
115
+ begin
116
+ unless done[0]
117
+ Store.record_failure(name, message: "the script was stopped after #{timeout} s", line: nil,
118
+ script_sha: Store.script_sha(name))
119
+ end
120
+ # Not an ensure: a normal exit kills this thread, and its ensure would KILL the group.
121
+ rescue StandardError # degrade-ok: the KILL matters more than the record (a dead launcher records nothing)
122
+ nil
123
+ end
124
+ Process.kill("KILL", -Process.pid)
125
+ end
126
+ end
127
+
128
+ # The error as the page shows it: a syntax error without its leading
129
+ # "path:line:" (its line is #line's), an exit as what it was.
130
+ def message(error, path)
131
+ case error
132
+ when ScriptError then error.message.sub(/\A#{Regexp.escape(path)}:\d+:\s*/, "")
133
+ when SystemExit
134
+ words = error.message == "exit" ? nil : error.message
135
+ words || "the script called exit #{error.status}"
136
+ else error.message
137
+ end
138
+ end
139
+
140
+ # The script's line: a syntax error's from its message's first line
141
+ # (the rest differs between Rubies), anything else's from the first
142
+ # backtrace entry inside the script file. nil when neither has one.
143
+ def line(error, path)
144
+ prefix = "#{path}:"
145
+ if error.is_a?(ScriptError)
146
+ found = error.message.lines.first.to_s[/\A#{Regexp.escape(prefix)}(\d+)/, 1]
147
+ return found.to_i if found
148
+ end
149
+ entry = Array(error.backtrace).find { |frame| frame.start_with?(prefix) }
150
+ entry && entry.delete_prefix(prefix)[/\A\d+/]&.to_i
151
+ end
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,143 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require_relative "../pages"
5
+
6
+ module Samagotchi
7
+ module Pages
8
+ # Where pages live: the scripts (<config>/samagotchi/pages/NAME.rb), each
9
+ # one's output (<state>/samagotchi/pages/NAME/output.json) and its lock
10
+ # (<state>/samagotchi/pages/NAME.lock, beside the folder so a remove can
11
+ # delete the folder while holding it). A failed run rewrites only the
12
+ # error: the blocks of the last good run stay. Every path is built after
13
+ # Pages.check_name!.
14
+ module Store
15
+ OUTPUT = "output.json"
16
+ # How much of a failure's message is kept.
17
+ MAX_MESSAGE = 2000
18
+
19
+ module_function
20
+
21
+ def output_dir(name) = File.join(Pages.state_dir, Pages.check_name!(name))
22
+ def output_path(name) = File.join(output_dir(name), OUTPUT)
23
+ def lock_path(name) = File.join(Pages.state_dir, "#{Pages.check_name!(name)}.lock")
24
+
25
+ # @return [String, nil] the sha256 of NAME's script, nil when it has none
26
+ def script_sha(name)
27
+ path = Pages.script_path(name)
28
+ File.file?(path) ? Digest::SHA256.file(path).hexdigest : nil
29
+ end
30
+
31
+ # @return [Stored] never ran when the output file is missing or unreadable
32
+ def read(name)
33
+ raw = read_raw(name)
34
+ error = raw["error"]
35
+ error = if error.is_a?(Hash) && error["message"].is_a?(String)
36
+ Failure.new(message: error["message"], line: error["line"].is_a?(Integer) ? error["line"] : nil,
37
+ at: string(error["at"]), script_sha: string(error["script_sha"]))
38
+ end
39
+ ran_at = string(raw["ran_at"])
40
+ Stored.new(name: name, title: string(raw["title"]), blocks: ran_at && raw["blocks"].is_a?(Array) ? raw["blocks"] : [],
41
+ ran_at: ran_at, duration_ms: raw["duration_ms"].is_a?(Numeric) ? raw["duration_ms"] : nil,
42
+ script_sha: string(raw["script_sha"]), error: error, current_sha: script_sha(name))
43
+ end
44
+
45
+ # Every script with a valid name, by name; a file whose name breaks
46
+ # the rule is skipped.
47
+ # @return [Array<Stored>]
48
+ def list
49
+ return [] unless File.directory?(Pages.scripts_dir)
50
+
51
+ Dir.children(Pages.scripts_dir).filter_map do |file|
52
+ name = file.delete_suffix(".rb")
53
+ name if file.end_with?(".rb") && Pages.valid_name?(name) && File.file?(File.join(Pages.scripts_dir, file))
54
+ end.sort.map { |name| read(name) }
55
+ end
56
+
57
+ # A good run: its blocks replace the last ones and the error is cleared.
58
+ # @raise [Refused] the output is over MAX_OUTPUT_BYTES
59
+ # @return [Stored]
60
+ def record_run(name, title:, blocks:, duration_ms:, script_sha:)
61
+ stored = Stored.new(name: name, title: title, blocks: blocks, ran_at: now, duration_ms: duration_ms,
62
+ script_sha: script_sha, error: nil, current_sha: script_sha)
63
+ json = JSON.generate(stored.to_json_hash)
64
+ if json.bytesize > MAX_OUTPUT_BYTES
65
+ raise Refused, format("the output is %<kb>.1f KB (at most %<max>d KB)", kb: json.bytesize / 1024.0,
66
+ max: MAX_OUTPUT_BYTES / 1024)
67
+ end
68
+
69
+ write(name, json)
70
+ stored
71
+ end
72
+
73
+ # A failed run: the error is set; the last good run's blocks stay.
74
+ # The one writer of a failure, for the runner (the script's) and the
75
+ # launcher (a cut, a runner with no result) alike.
76
+ # @return [Stored]
77
+ def record_failure(name, message:, line:, script_sha:)
78
+ # Scrubbed: a message with stray bytes (backtick output) would make
79
+ # JSON.generate raise inside the runner's rescue and lose the error.
80
+ message = Builder.text_of(message)
81
+ message = "#{message[0, MAX_MESSAGE - 1]}…" if message.size > MAX_MESSAGE
82
+ stored = read(name).with(error: Failure.new(message: message, line: line, at: now, script_sha: script_sha))
83
+ write(name, JSON.generate(stored.to_json_hash))
84
+ stored
85
+ end
86
+
87
+ # Runs the block holding NAME's lock (flock, non-blocking), with the
88
+ # lock's io: Launch hands it to the runner, which then holds the lock
89
+ # for as long as it lives (a killed launcher leaves a run that still
90
+ # holds it).
91
+ # @yieldparam lock [File]
92
+ # @raise [Busy] another process holds it
93
+ def locked(name)
94
+ path = lock_path(name)
95
+ FileUtils.mkdir_p(File.dirname(path))
96
+ File.open(path, File::RDWR | File::CREAT, 0o644) do |lock|
97
+ raise Busy, name unless lock.flock(File::LOCK_EX | File::LOCK_NB)
98
+
99
+ yield lock
100
+ end
101
+ end
102
+
103
+ # Deletes NAME's script and output folder under its lock, then the lock.
104
+ # @raise [Missing] no script and no output
105
+ # @raise [Busy] it is running
106
+ def remove(name)
107
+ script = Pages.script_path(name)
108
+ raise Missing, name unless File.exist?(script) || File.exist?(output_dir(name))
109
+
110
+ locked(name) do
111
+ FileUtils.rm_f(script)
112
+ FileUtils.rm_rf(output_dir(name))
113
+ FileUtils.rm_f(lock_path(name))
114
+ end
115
+ end
116
+
117
+ # The output file's identity (its inode): AtomicFile renames a new file
118
+ # in for every write, so a run that wrote changes it, even within the
119
+ # same second. nil when there is none.
120
+ def file_id(name)
121
+ File.stat(output_path(name)).ino
122
+ rescue SystemCallError
123
+ nil
124
+ end
125
+
126
+ def write(name, json)
127
+ FileUtils.mkdir_p(output_dir(name))
128
+ AtomicFile.write(output_path(name), json)
129
+ end
130
+
131
+ def read_raw(name)
132
+ raw = JSON.parse(File.read(output_path(name), encoding: Encoding::UTF_8))
133
+ raw.is_a?(Hash) ? raw : {}
134
+ rescue JSON::ParserError, SystemCallError, EncodingError
135
+ {}
136
+ end
137
+
138
+ def string(value) = value.is_a?(String) ? value : nil
139
+
140
+ def now = Time.now.utc.iso8601
141
+ end
142
+ end
143
+ end
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "digest"
5
+ require "time"
6
+ require_relative "inline_widgets"
7
+ require_relative "paths"
8
+ require_relative "atomic_file"
9
+
10
+ module Samagotchi
11
+ # Pages: a Ruby script under <config>/samagotchi/pages/NAME.rb says what to
12
+ # show (`page "Title" do |ui| ui.text …; ui.table …; ui.walk … end`); a run
13
+ # stores the blocks it built as JSON under <state>/samagotchi/pages/NAME/,
14
+ # and what shows a page draws from that file (docs/pages.md,
15
+ # docs/internals/pages.md).
16
+ #
17
+ # Light on purpose: the runner (pages/runner.rb) is a process of its own
18
+ # that requires this file only, so nothing here may require the engine, the
19
+ # config, the web, the plugins or the launcher (pages/launch.rb, which
20
+ # spawns the runner and needs ProcessGroup and ChildEnv).
21
+ module Pages
22
+ autoload :Builder, File.expand_path("pages/builder", __dir__)
23
+ autoload :TableBlock, File.expand_path("pages/builder", __dir__)
24
+ autoload :Store, File.expand_path("pages/store", __dir__)
25
+
26
+ # A page's name: lowercase letters, digits and hyphens, a letter or a
27
+ # digit first, at most 40.
28
+ NAME = /\A[a-z0-9][a-z0-9-]{0,39}\z/
29
+ MAX_ROWS = 500
30
+ MAX_COLUMNS = 12
31
+ MAX_CELL = 300
32
+ MAX_BLOCKS = 20
33
+ MAX_TEXT_BYTES = 16 * 1024
34
+ MAX_OUTPUT_BYTES = 256 * 1024
35
+ TIMEOUT_SECONDS = 30
36
+ FORMATS = %i[money count].freeze
37
+
38
+ # Anything that keeps a page from running or from being stored. Each
39
+ # subclass owns its message.
40
+ class Error < StandardError; end
41
+
42
+ # A rule a script broke (a limit, a table's column, page called twice):
43
+ # the run fails with this message.
44
+ class Refused < Error; end
45
+
46
+ # A name that breaks NAME: the command line's fault (exit 2).
47
+ class BadName < Error
48
+ def initialize(name)
49
+ super("#{name.to_s.inspect} isn't a page name (lowercase letters, digits and hyphens, a letter or digit first, at most 40)")
50
+ end
51
+ end
52
+
53
+ # No script for the name.
54
+ class Missing < Error
55
+ def initialize(name)
56
+ super("no page #{name}")
57
+ end
58
+ end
59
+
60
+ # Another run (or a remove) holds the page's lock.
61
+ class Busy < Error
62
+ def initialize(name)
63
+ super("page #{name} is already running")
64
+ end
65
+ end
66
+
67
+ # A failed run: what the script raised (or why it was stopped), the
68
+ # script's line when one is known, when, and the sha256 of the script
69
+ # that failed.
70
+ Failure = Data.define(:message, :line, :at, :script_sha) do
71
+ def to_json_hash = { "message" => message, "line" => line, "at" => at, "script_sha" => script_sha }
72
+ end
73
+
74
+ # A page as stored (Store.read): the blocks of its last good run (none
75
+ # before one, ran_at nil) and the last failure since, if any.
76
+ # +current_sha+ is the script's sha256 now (nil when the script is gone).
77
+ Stored = Data.define(:name, :title, :blocks, :ran_at, :duration_ms, :script_sha, :error, :current_sha) do
78
+ # :never_ran, :ok or :failed (the last run failed; the good blocks, if
79
+ # any, are still there).
80
+ def state
81
+ return :failed if error
82
+ return :ok if ran_at
83
+
84
+ :never_ran
85
+ end
86
+
87
+ # Whether the script differs from the one that made the blocks.
88
+ def changed? = !script_sha.nil? && !current_sha.nil? && current_sha != script_sha
89
+
90
+ # The output file's JSON.
91
+ def to_json_hash
92
+ { "name" => name, "title" => title, "blocks" => blocks, "ran_at" => ran_at, "duration_ms" => duration_ms,
93
+ "script_sha" => script_sha, "error" => error&.to_json_hash }
94
+ end
95
+ end
96
+
97
+ module_function
98
+
99
+ def valid_name?(name) = name.is_a?(String) && NAME.match?(name)
100
+
101
+ # The one check every path goes through before it builds a path.
102
+ # @return [String] +name+
103
+ # @raise [BadName]
104
+ def check_name!(name)
105
+ raise BadName, name unless valid_name?(name)
106
+
107
+ name
108
+ end
109
+
110
+ # @return [String] <config home>/samagotchi/pages (ConfigFile.config_dir
111
+ # lives in config.rb, which loads far more than a runner may)
112
+ def scripts_dir = File.join(Paths.config_home, Paths::APP_DIR, "pages")
113
+
114
+ # @return [String] <state dir>/pages
115
+ def state_dir = File.join(Paths.state_dir, "pages")
116
+
117
+ def script_path(name) = File.join(scripts_dir, "#{check_name!(name)}.rb")
118
+ end
119
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # A reply made plain for a surface that shows plain text only (ReplyFor
5
+ # formatting "plain": a voice Shortcut reads it aloud). Deterministic: the
6
+ # same text gives the same output. On the way out only, in chi web's wait
7
+ # answers (SessionAccessRoutes#wait_result_json); the saved reply, the
8
+ # reply file, the SSE stream and the web bubble keep the model's text.
9
+ #
10
+ # What goes: a heading's, a bullet's and a quote's lead, a table's pipes
11
+ # (a separator row whole), a rule line, ** and __, backticks, a link's URL
12
+ # (its text kept), emoji. What stays: a numbered list's numbers ("1. "),
13
+ # which read well aloud, and a fenced code block's content, byte for byte
14
+ # (its fence lines go; one never closed runs to the end).
15
+ module PlainReply
16
+ # A fence's opening line: its marker (``` or ~~~, three or more). A
17
+ # backtick fence's info string holds no backtick (CommonMark), so a
18
+ # line like "```ls -la``` lists files" is inline code, not a fence.
19
+ FENCE_OPEN = /\A[ \t]*(`{3,}(?=[^`]*\z)|~{3,})/
20
+ HEADING = /^([ \t]*)\#{1,6}[ \t]+/
21
+ BULLET = /^([ \t]*)[-*+][ \t]+/
22
+ QUOTE = /^([ \t]*)(?:>[ \t]?)+/
23
+ RULE = /^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*(\n|\z)/
24
+ TABLE_SEPARATOR = /^[ \t]*\|?[ \t]*:?-{3,}:?[ \t]*(\|[ \t]*:?-{3,}:?[ \t]*)*\|?[ \t]*(\n|\z)/
25
+ TABLE_ROW = /^[ \t]*\|(.*?)\|?[ \t]*$/
26
+ LINK = /\[([^\]\n]+)\]\([^)\s]+(?:[ \t]+"[^"]*")?\)/
27
+ EMPHASIS = /\*\*|__/
28
+ EMOJI = /[ \t]?[\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}\u{2B00}-\u{2BFF}\u{FE0F}\u{200D}]+/
29
+
30
+ module_function
31
+
32
+ # @param text [String, nil]
33
+ # @return [String, nil] nil for nil
34
+ def strip(text)
35
+ return text if text.nil?
36
+
37
+ lines = segments(text.gsub("\r\n", "\n")).flat_map do |code, body|
38
+ next body if code || body.empty?
39
+
40
+ plain(body.join("\n")).split("\n", -1).map { |line| line.rstrip.sub(/\A[ \t]+/, "") }
41
+ end
42
+ lines = lines.drop_while { |line| line.strip.empty? }
43
+ lines.pop while lines.last&.strip&.empty?
44
+ lines.join("\n")
45
+ end
46
+
47
+ # +text+'s lines as [code?, lines] runs: a fence's content (code) and
48
+ # the text between fences, the fence lines left out.
49
+ # @return [Array<Array(Boolean, Array<String>)>]
50
+ def segments(text)
51
+ runs = [[false, []]]
52
+ close = nil
53
+ text.split("\n", -1).each do |line|
54
+ if close&.match?(line)
55
+ close = nil
56
+ runs << [false, []]
57
+ elsif !close && (open = FENCE_OPEN.match(line))
58
+ close = /\A[ \t]*#{Regexp.escape(open[1][0])}{#{open[1].size},}[ \t]*\z/
59
+ runs << [true, []]
60
+ else
61
+ runs.last.last << line
62
+ end
63
+ end
64
+ runs
65
+ end
66
+
67
+ # A text run made plain (no fence in it).
68
+ def plain(text)
69
+ out = text.gsub(TABLE_SEPARATOR, "").gsub(RULE, "")
70
+ out = out.gsub(TABLE_ROW) { Regexp.last_match(1).split("|").map(&:strip).reject(&:empty?).join(", ") }
71
+ out = out.gsub(HEADING, '\1').gsub(BULLET, '\1').gsub(QUOTE, '\1')
72
+ out.gsub(LINK, '\1').gsub(EMPHASIS, "").delete("`").gsub(EMOJI, "")
73
+ end
74
+ end
75
+ end