sendproof-core 0.1.0.alpha.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.
- checksums.yaml +7 -0
- data/LICENSE +21 -0
- data/README.md +55 -0
- data/lib/sendproof/assets.rb +70 -0
- data/lib/sendproof/attribution.rb +98 -0
- data/lib/sendproof/capture.rb +66 -0
- data/lib/sendproof/clock.rb +54 -0
- data/lib/sendproof/configuration.rb +241 -0
- data/lib/sendproof/data_store.rb +34 -0
- data/lib/sendproof/dynamodb/store.rb +183 -0
- data/lib/sendproof/dynamodb.rb +17 -0
- data/lib/sendproof/elasticsearch/store.rb +24 -0
- data/lib/sendproof/elasticsearch.rb +17 -0
- data/lib/sendproof/firestore/interceptor.rb +38 -0
- data/lib/sendproof/firestore/store.rb +150 -0
- data/lib/sendproof/firestore.rb +99 -0
- data/lib/sendproof/handler.rb +23 -0
- data/lib/sendproof/identity.rb +37 -0
- data/lib/sendproof/limits.rb +113 -0
- data/lib/sendproof/middleware.rb +68 -0
- data/lib/sendproof/mongo/engine.rb +692 -0
- data/lib/sendproof/mongo/guarded.rb +100 -0
- data/lib/sendproof/mongo/plain.rb +45 -0
- data/lib/sendproof/mongo/store.rb +54 -0
- data/lib/sendproof/mongo/subscriber.rb +21 -0
- data/lib/sendproof/mongo.rb +41 -0
- data/lib/sendproof/mongoid/store.rb +58 -0
- data/lib/sendproof/mongoid.rb +65 -0
- data/lib/sendproof/observed_request.rb +108 -0
- data/lib/sendproof/opensearch/store.rb +21 -0
- data/lib/sendproof/opensearch.rb +17 -0
- data/lib/sendproof/operation_matcher.rb +28 -0
- data/lib/sendproof/pool_hooks.rb +80 -0
- data/lib/sendproof/preview_request.rb +44 -0
- data/lib/sendproof/preview_transport.rb +331 -0
- data/lib/sendproof/protocol.rb +81 -0
- data/lib/sendproof/provider.rb +83 -0
- data/lib/sendproof/recorder.rb +298 -0
- data/lib/sendproof/redaction.rb +98 -0
- data/lib/sendproof/redis/commands.rb +76 -0
- data/lib/sendproof/redis/store.rb +205 -0
- data/lib/sendproof/redis.rb +18 -0
- data/lib/sendproof/search/middleware.rb +39 -0
- data/lib/sendproof/search/store.rb +213 -0
- data/lib/sendproof/search.rb +82 -0
- data/lib/sendproof/stores/classify.rb +346 -0
- data/lib/sendproof/stores/guard.rb +127 -0
- data/lib/sendproof/stores/tables.rb +1328 -0
- data/lib/sendproof/stores.rb +12 -0
- data/lib/sendproof/trace_store.rb +110 -0
- data/lib/sendproof/transaction_control.rb +187 -0
- data/lib/sendproof/ui/action-bar.js +91 -0
- data/lib/sendproof/ui/api.js +239 -0
- data/lib/sendproof/ui/app.css +848 -0
- data/lib/sendproof/ui/app.js +742 -0
- data/lib/sendproof/ui/autofill.js +137 -0
- data/lib/sendproof/ui/code-copy.js +71 -0
- data/lib/sendproof/ui/code-picker.js +149 -0
- data/lib/sendproof/ui/commands.js +197 -0
- data/lib/sendproof/ui/components.js +77 -0
- data/lib/sendproof/ui/context-bar.js +82 -0
- data/lib/sendproof/ui/copy.js +92 -0
- data/lib/sendproof/ui/coverage-popover.js +35 -0
- data/lib/sendproof/ui/crumb-fit.js +80 -0
- data/lib/sendproof/ui/deprecation.js +164 -0
- data/lib/sendproof/ui/display-settings.js +175 -0
- data/lib/sendproof/ui/doc-diff.js +209 -0
- data/lib/sendproof/ui/docs-view.js +347 -0
- data/lib/sendproof/ui/favicon.png +0 -0
- data/lib/sendproof/ui/favicon.svg +1 -0
- data/lib/sendproof/ui/field-help.js +52 -0
- data/lib/sendproof/ui/field-modules.js +23 -0
- data/lib/sendproof/ui/fields/controls.js +179 -0
- data/lib/sendproof/ui/fields/dom.js +36 -0
- data/lib/sendproof/ui/fields/infer.js +71 -0
- data/lib/sendproof/ui/fields/lookup-source.js +63 -0
- data/lib/sendproof/ui/fields/lookup.js +285 -0
- data/lib/sendproof/ui/fields/render.js +496 -0
- data/lib/sendproof/ui/fields/select.js +175 -0
- data/lib/sendproof/ui/fields/validate.js +363 -0
- data/lib/sendproof/ui/fields/validation-formats.js +164 -0
- data/lib/sendproof/ui/fields/validation-references.js +68 -0
- data/lib/sendproof/ui/fields/validation-values.js +137 -0
- data/lib/sendproof/ui/generate-menu.js +44 -0
- data/lib/sendproof/ui/generate.js +184 -0
- data/lib/sendproof/ui/header-editor.js +777 -0
- data/lib/sendproof/ui/headers.js +188 -0
- data/lib/sendproof/ui/highlight.js +257 -0
- data/lib/sendproof/ui/history-popover.js +24 -0
- data/lib/sendproof/ui/i18n.js +253 -0
- data/lib/sendproof/ui/icons.js +87 -0
- data/lib/sendproof/ui/index.html +70 -0
- data/lib/sendproof/ui/issues.js +187 -0
- data/lib/sendproof/ui/json-view.js +166 -0
- data/lib/sendproof/ui/lang-icons.js +62 -0
- data/lib/sendproof/ui/layout.js +262 -0
- data/lib/sendproof/ui/listbox.js +334 -0
- data/lib/sendproof/ui/locales/ar-capture.js +366 -0
- data/lib/sendproof/ui/locales/ar-stores.js +116 -0
- data/lib/sendproof/ui/locales/ar.js +561 -0
- data/lib/sendproof/ui/locales/cs-capture.js +442 -0
- data/lib/sendproof/ui/locales/cs-stores.js +116 -0
- data/lib/sendproof/ui/locales/cs.js +689 -0
- data/lib/sendproof/ui/locales/da-capture.js +347 -0
- data/lib/sendproof/ui/locales/da-stores.js +116 -0
- data/lib/sendproof/ui/locales/da.js +522 -0
- data/lib/sendproof/ui/locales/de-capture.js +347 -0
- data/lib/sendproof/ui/locales/de-stores.js +116 -0
- data/lib/sendproof/ui/locales/de.js +519 -0
- data/lib/sendproof/ui/locales/el-capture.js +347 -0
- data/lib/sendproof/ui/locales/el-stores.js +116 -0
- data/lib/sendproof/ui/locales/el.js +520 -0
- data/lib/sendproof/ui/locales/en-capture.js +349 -0
- data/lib/sendproof/ui/locales/en-stores.js +95 -0
- data/lib/sendproof/ui/locales/en.js +522 -0
- data/lib/sendproof/ui/locales/es-capture.js +353 -0
- data/lib/sendproof/ui/locales/es-stores.js +116 -0
- data/lib/sendproof/ui/locales/es.js +525 -0
- data/lib/sendproof/ui/locales/fa-capture.js +348 -0
- data/lib/sendproof/ui/locales/fa-stores.js +116 -0
- data/lib/sendproof/ui/locales/fa.js +521 -0
- data/lib/sendproof/ui/locales/fi-capture.js +347 -0
- data/lib/sendproof/ui/locales/fi-stores.js +116 -0
- data/lib/sendproof/ui/locales/fi.js +523 -0
- data/lib/sendproof/ui/locales/fr-capture.js +353 -0
- data/lib/sendproof/ui/locales/fr-stores.js +116 -0
- data/lib/sendproof/ui/locales/fr.js +525 -0
- data/lib/sendproof/ui/locales/he-capture.js +358 -0
- data/lib/sendproof/ui/locales/he-stores.js +116 -0
- data/lib/sendproof/ui/locales/he.js +529 -0
- data/lib/sendproof/ui/locales/hi-capture.js +348 -0
- data/lib/sendproof/ui/locales/hi-stores.js +116 -0
- data/lib/sendproof/ui/locales/hi.js +523 -0
- data/lib/sendproof/ui/locales/id-capture.js +347 -0
- data/lib/sendproof/ui/locales/id-stores.js +116 -0
- data/lib/sendproof/ui/locales/id.js +521 -0
- data/lib/sendproof/ui/locales/it-capture.js +361 -0
- data/lib/sendproof/ui/locales/it-stores.js +116 -0
- data/lib/sendproof/ui/locales/it.js +523 -0
- data/lib/sendproof/ui/locales/ja-capture.js +346 -0
- data/lib/sendproof/ui/locales/ja-stores.js +116 -0
- data/lib/sendproof/ui/locales/ja.js +521 -0
- data/lib/sendproof/ui/locales/ko-capture.js +346 -0
- data/lib/sendproof/ui/locales/ko-stores.js +116 -0
- data/lib/sendproof/ui/locales/ko.js +522 -0
- data/lib/sendproof/ui/locales/nb-capture.js +349 -0
- data/lib/sendproof/ui/locales/nb-stores.js +116 -0
- data/lib/sendproof/ui/locales/nb.js +521 -0
- data/lib/sendproof/ui/locales/nl-capture.js +355 -0
- data/lib/sendproof/ui/locales/nl-stores.js +116 -0
- data/lib/sendproof/ui/locales/nl.js +520 -0
- data/lib/sendproof/ui/locales/pl-capture.js +432 -0
- data/lib/sendproof/ui/locales/pl-stores.js +116 -0
- data/lib/sendproof/ui/locales/pl.js +528 -0
- data/lib/sendproof/ui/locales/pt-BR-capture.js +350 -0
- data/lib/sendproof/ui/locales/pt-BR-stores.js +116 -0
- data/lib/sendproof/ui/locales/pt-BR.js +523 -0
- data/lib/sendproof/ui/locales/pt-PT-capture.js +350 -0
- data/lib/sendproof/ui/locales/pt-PT-stores.js +116 -0
- data/lib/sendproof/ui/locales/pt-PT.js +523 -0
- data/lib/sendproof/ui/locales/ru-capture.js +437 -0
- data/lib/sendproof/ui/locales/ru-stores.js +116 -0
- data/lib/sendproof/ui/locales/ru.js +624 -0
- data/lib/sendproof/ui/locales/sv-capture.js +349 -0
- data/lib/sendproof/ui/locales/sv-stores.js +116 -0
- data/lib/sendproof/ui/locales/sv.js +518 -0
- data/lib/sendproof/ui/locales/th-capture.js +347 -0
- data/lib/sendproof/ui/locales/th-stores.js +116 -0
- data/lib/sendproof/ui/locales/th.js +521 -0
- data/lib/sendproof/ui/locales/tr-capture.js +348 -0
- data/lib/sendproof/ui/locales/tr-stores.js +116 -0
- data/lib/sendproof/ui/locales/tr.js +521 -0
- data/lib/sendproof/ui/locales/uk-capture.js +442 -0
- data/lib/sendproof/ui/locales/uk-stores.js +116 -0
- data/lib/sendproof/ui/locales/uk.js +630 -0
- data/lib/sendproof/ui/locales/vi-capture.js +346 -0
- data/lib/sendproof/ui/locales/vi-stores.js +116 -0
- data/lib/sendproof/ui/locales/vi.js +523 -0
- data/lib/sendproof/ui/locales/zh-Hans-capture.js +347 -0
- data/lib/sendproof/ui/locales/zh-Hans-stores.js +116 -0
- data/lib/sendproof/ui/locales/zh-Hans.js +523 -0
- data/lib/sendproof/ui/locales/zh-Hant-capture.js +346 -0
- data/lib/sendproof/ui/locales/zh-Hant-stores.js +116 -0
- data/lib/sendproof/ui/locales/zh-Hant.js +522 -0
- data/lib/sendproof/ui/manifest.json +866 -0
- data/lib/sendproof/ui/markdown.js +39 -0
- data/lib/sendproof/ui/model-view.js +182 -0
- data/lib/sendproof/ui/navigation.js +233 -0
- data/lib/sendproof/ui/operation-header.js +76 -0
- data/lib/sendproof/ui/operations.js +7 -0
- data/lib/sendproof/ui/overview-view.js +63 -0
- data/lib/sendproof/ui/personas.js +59 -0
- data/lib/sendproof/ui/popover.js +71 -0
- data/lib/sendproof/ui/preview-false.js +108 -0
- data/lib/sendproof/ui/request-editor.js +496 -0
- data/lib/sendproof/ui/response-metadata.js +354 -0
- data/lib/sendproof/ui/response-viewer.js +618 -0
- data/lib/sendproof/ui/result-blocked.js +155 -0
- data/lib/sendproof/ui/result-capture.js +25 -0
- data/lib/sendproof/ui/result-database.js +185 -0
- data/lib/sendproof/ui/result-effects.js +176 -0
- data/lib/sendproof/ui/result-headers.js +106 -0
- data/lib/sendproof/ui/result-logs.js +408 -0
- data/lib/sendproof/ui/result-states.js +213 -0
- data/lib/sendproof/ui/results.js +371 -0
- data/lib/sendproof/ui/router.js +118 -0
- data/lib/sendproof/ui/schema-model.js +336 -0
- data/lib/sendproof/ui/schema-tree.js +344 -0
- data/lib/sendproof/ui/schema.js +397 -0
- data/lib/sendproof/ui/security.js +31 -0
- data/lib/sendproof/ui/seeded-menu.js +69 -0
- data/lib/sendproof/ui/settings.js +93 -0
- data/lib/sendproof/ui/shortcuts-sheet.js +73 -0
- data/lib/sendproof/ui/shortcuts.js +190 -0
- data/lib/sendproof/ui/sidebar.js +289 -0
- data/lib/sendproof/ui/signin.js +259 -0
- data/lib/sendproof/ui/snippets.js +530 -0
- data/lib/sendproof/ui/store-marks.js +47 -0
- data/lib/sendproof/ui/stores.js +131 -0
- data/lib/sendproof/ui/styles.css +971 -0
- data/lib/sendproof/ui/toggletip.js +53 -0
- data/lib/sendproof/ui/uuid.js +10 -0
- data/lib/sendproof/ui/view.js +122 -0
- data/lib/sendproof/ui/views.css +653 -0
- data/lib/sendproof/version.rb +9 -0
- data/lib/sendproof/workbench.rb +102 -0
- data/lib/sendproof-core.rb +3 -0
- data/lib/sendproof.rb +121 -0
- metadata +292 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "stores/tables"
|
|
4
|
+
require_relative "stores/classify"
|
|
5
|
+
require_relative "stores/guard"
|
|
6
|
+
|
|
7
|
+
module Sendproof
|
|
8
|
+
# Data-store support shared by every store hook: the embedded classification {Tables}, the pure
|
|
9
|
+
# {Classify} functions and the write {Guard}. See spec/data-stores.md.
|
|
10
|
+
module Stores
|
|
11
|
+
end
|
|
12
|
+
end
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Sendproof
|
|
4
|
+
# Keeps observed-send traces for a short time, owner-scoped and bounded.
|
|
5
|
+
#
|
|
6
|
+
# Expiry is evaluated lazily on every reserve and read against an injectable monotonic clock,
|
|
7
|
+
# so tests control retention without sleeping and no timer thread exists.
|
|
8
|
+
class TraceStore
|
|
9
|
+
PER_OWNER = 8
|
|
10
|
+
TOTAL = 32
|
|
11
|
+
READ_WAIT = 5.0
|
|
12
|
+
|
|
13
|
+
# A trace id handed out before its result exists; readers wait for {#complete}.
|
|
14
|
+
class Reservation
|
|
15
|
+
attr_reader :id, :owner, :start
|
|
16
|
+
|
|
17
|
+
def initialize(id, owner, start)
|
|
18
|
+
@id = id
|
|
19
|
+
@owner = owner
|
|
20
|
+
@start = start
|
|
21
|
+
@mutex = Mutex.new
|
|
22
|
+
@condition = ConditionVariable.new
|
|
23
|
+
@done = false
|
|
24
|
+
@result = nil
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# Publishes the trace (or nil when the send was not observed to completion).
|
|
28
|
+
def complete(result)
|
|
29
|
+
@mutex.synchronize do
|
|
30
|
+
next if @done
|
|
31
|
+
|
|
32
|
+
@result = result
|
|
33
|
+
@done = true
|
|
34
|
+
@condition.broadcast
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# @return [Hash, nil] the trace, or nil if it was discarded or did not finish within +timeout+
|
|
39
|
+
def wait(timeout)
|
|
40
|
+
deadline = Clock.now + timeout
|
|
41
|
+
@mutex.synchronize do
|
|
42
|
+
until @done
|
|
43
|
+
remaining = deadline - Clock.now
|
|
44
|
+
return nil unless remaining.positive?
|
|
45
|
+
|
|
46
|
+
@condition.wait(@mutex, remaining)
|
|
47
|
+
end
|
|
48
|
+
@result
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# @param ttl [Numeric] seconds a trace stays readable
|
|
54
|
+
# @param clock [#call] returns monotonic seconds
|
|
55
|
+
def initialize(ttl: 300, clock: Clock.method(:now), per_owner: PER_OWNER, total: TOTAL, wait: READ_WAIT)
|
|
56
|
+
@ttl = ttl
|
|
57
|
+
@clock = clock
|
|
58
|
+
@per_owner = per_owner
|
|
59
|
+
@total = total
|
|
60
|
+
@wait = wait
|
|
61
|
+
@mutex = Mutex.new
|
|
62
|
+
@entries = []
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# @return [Reservation]
|
|
66
|
+
def reserve(owner)
|
|
67
|
+
@mutex.synchronize do
|
|
68
|
+
expire
|
|
69
|
+
owned = @entries.select { |entry| entry.owner == owner }
|
|
70
|
+
remove(owned.first) if owned.length >= @per_owner
|
|
71
|
+
remove(@entries.first) if @entries.length >= @total
|
|
72
|
+
# 128 random bits from the CSPRNG (a UUID would carry only 122).
|
|
73
|
+
Reservation.new(SecureRandom.hex(16), owner, @clock.call).tap { |entry| @entries << entry }
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# @return [Hash, nil] nil for unknown, expired, evicted or foreign ids
|
|
78
|
+
def read(id, owner)
|
|
79
|
+
return nil unless id.to_s.delete("-").match?(/\A\h{32}\z/)
|
|
80
|
+
|
|
81
|
+
key = id.to_s.delete("-").downcase
|
|
82
|
+
reservation = @mutex.synchronize do
|
|
83
|
+
expire
|
|
84
|
+
@entries.find { |entry| entry.id == key && entry.owner == owner }
|
|
85
|
+
end
|
|
86
|
+
reservation&.wait(@wait)
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def discard(reservation)
|
|
90
|
+
@mutex.synchronize { remove(reservation) }
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# Drops everything, releasing any waiting reader.
|
|
94
|
+
def clear
|
|
95
|
+
@mutex.synchronize { @entries.dup.each { |entry| remove(entry) } }
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
private
|
|
99
|
+
|
|
100
|
+
def expire
|
|
101
|
+
now = @clock.call
|
|
102
|
+
remove(@entries.first) while @entries.first && now - @entries.first.start >= @ttl
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def remove(entry)
|
|
106
|
+
@entries.delete(entry)
|
|
107
|
+
entry&.complete(nil)
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
end
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Sendproof
|
|
4
|
+
# Recognizes SQL that would end or escape the transaction a rollback preview runs in (the shared
|
|
5
|
+
# +raw-commit+ and +mysql-escape+ rules, spec/data-stores.md "Transaction-control statements from
|
|
6
|
+
# the handler").
|
|
7
|
+
#
|
|
8
|
+
# The checks are deliberately conservative: a statement that might end the transaction is
|
|
9
|
+
# refused, which can only fail a preview, never confirm one. Savepoint statements stay allowed
|
|
10
|
+
# because ORMs use them for nested transactions, except on the savepoint the provider reserves.
|
|
11
|
+
#
|
|
12
|
+
# On MySQL and MariaDB +CALL+ is refused too, because a stored procedure can commit, unless the
|
|
13
|
+
# host declared that procedure safe by exact name; so are SQL-level +PREPARE+ and +EXECUTE+, which
|
|
14
|
+
# run statement text the guard never saw.
|
|
15
|
+
#
|
|
16
|
+
# Quotes and comments are read the way each server reads them by default: on MySQL backslashes
|
|
17
|
+
# escape inside every string, +#+ starts a comment and +--+ does only when a space follows; elsewhere
|
|
18
|
+
# a standard string has no backslash escapes (PostgreSQL's +E'...'+ strings do) and +$tag$+ quotes a
|
|
19
|
+
# body. A literal that ended later than the server's would hide a statement the server runs.
|
|
20
|
+
module TransactionControl
|
|
21
|
+
# MySQL and MariaDB run the body of +/*! ... */+ and +/*M! ... */+ comments as SQL.
|
|
22
|
+
EXECUTABLE_COMMENT = %r{\A/\*M?!\d*}
|
|
23
|
+
|
|
24
|
+
CONTROL = /\A(?:BEGIN|START\s+TRANSACTION|COMMIT|END|ABORT|ROLLBACK(?!\s+(?:WORK\s+|TRANSACTION\s+)?TO\b)|PREPARE\s+TRANSACTION|XA\b|SET\s+(?:(?:SESSION|GLOBAL|LOCAL)\s+|@@(?:SESSION\.|GLOBAL\.)?)?AUTOCOMMIT\b|SET\s+IMPLICIT_TRANSACTIONS\b)/i
|
|
25
|
+
|
|
26
|
+
# A +SET+ that changes autocommit anywhere in its list (+SET sql_mode = '', autocommit = 1+).
|
|
27
|
+
SET_AUTOCOMMIT = /\ASET\b.*(?<![\w$])AUTOCOMMIT\b/im
|
|
28
|
+
|
|
29
|
+
# MySQL commits the open transaction before (and after) these statements.
|
|
30
|
+
# https://dev.mysql.com/doc/refman/8.4/en/implicit-commit.html
|
|
31
|
+
MYSQL_IMPLICIT_COMMIT = /\A(?:ALTER|CREATE|DROP|RENAME|TRUNCATE|GRANT|REVOKE|LOCK\s+TABLES?|UNLOCK\s+TABLES?|ANALYZE|OPTIMIZE|REPAIR|CHECK\s+TABLES?|FLUSH|INSTALL|UNINSTALL|LOAD\s+(?:INDEX|DATA|XML)|CACHE\s+INDEX|RESET|SET\s+PASSWORD|SET\s+DEFAULT\s+ROLE|START\s+(?:REPLICA|SLAVE|GROUP_REPLICATION)|STOP\s+(?:REPLICA|SLAVE|GROUP_REPLICATION)|CHANGE\s+(?:REPLICATION|MASTER)|IMPORT\s+TABLE|CLONE)\b/i
|
|
32
|
+
MYSQL_TEMPORARY_TABLE = /\A(?:CREATE|DROP)\s+TEMPORARY\s+TABLE\b/i
|
|
33
|
+
|
|
34
|
+
# SQL-level +PREPARE ... FROM+ and +EXECUTE+ (also MariaDB's +EXECUTE IMMEDIATE+): they run statement
|
|
35
|
+
# text the guard never sees.
|
|
36
|
+
MYSQL_EXECUTE = /\A(?:PREPARE|EXECUTE)\b/i
|
|
37
|
+
|
|
38
|
+
# +CALL name+, +CALL schema.name+, with or without backticks; the name is captured.
|
|
39
|
+
MYSQL_CALL = /\ACALL\s+((?:`(?:[^`]|``)+`|[\w$]+)(?:\s*\.\s*(?:`(?:[^`]|``)+`|[\w$]+))?)/i
|
|
40
|
+
MYSQL_CALL_KEYWORD = /\ACALL\b/i
|
|
41
|
+
|
|
42
|
+
# A declared safe procedure: a plain name, optionally qualified with its schema.
|
|
43
|
+
PROCEDURE_NAME = /\A[A-Za-z_][\w$]*(?:\.[A-Za-z_][\w$]*)?\z/
|
|
44
|
+
|
|
45
|
+
module_function
|
|
46
|
+
|
|
47
|
+
# Checks and lower-cases the host's declared safe procedures. MySQL and MariaDB procedure names are
|
|
48
|
+
# case-insensitive, so +Refresh_Totals+ and +refresh_totals+ are one procedure. Exact names only:
|
|
49
|
+
# wildcards and quoting are rejected rather than guessed at.
|
|
50
|
+
#
|
|
51
|
+
# @param names [Array<String>]
|
|
52
|
+
# @return [Array<String>] frozen
|
|
53
|
+
# @raise [ArgumentError] for anything but an exact name
|
|
54
|
+
def normalize_procedures(names)
|
|
55
|
+
Array(names).map do |name|
|
|
56
|
+
raise ArgumentError, "A safe procedure must be an exact name such as \"refresh_totals\", not #{name.inspect}." unless name.is_a?(String) && name.match?(PROCEDURE_NAME)
|
|
57
|
+
|
|
58
|
+
name.downcase.freeze
|
|
59
|
+
end.uniq.freeze
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Splits SQL text into statements, ignoring separators inside quotes and comments. The body of a
|
|
63
|
+
# MySQL executable comment is kept as statement text, because the server runs it: +/*!COMMIT*/+
|
|
64
|
+
# is a COMMIT, not a comment.
|
|
65
|
+
#
|
|
66
|
+
# @param mysql [Boolean] read quotes and comments the way MySQL and MariaDB do
|
|
67
|
+
# @return [Array<String>]
|
|
68
|
+
def split(sql, mysql: false)
|
|
69
|
+
statements = []
|
|
70
|
+
current = +""
|
|
71
|
+
index = 0
|
|
72
|
+
executable = false
|
|
73
|
+
while index < sql.length
|
|
74
|
+
char = sql[index]
|
|
75
|
+
following = sql[index + 1]
|
|
76
|
+
if executable && char == "*" && following == "/"
|
|
77
|
+
executable = false
|
|
78
|
+
index += 2
|
|
79
|
+
current << " "
|
|
80
|
+
elsif char == "-" && following == "-" && (!mysql || sql[index + 2].nil? || sql[index + 2].match?(/[[:space:]]|[[:cntrl:]]/))
|
|
81
|
+
index = line_end(sql, index)
|
|
82
|
+
current << " "
|
|
83
|
+
elsif char == "#" && mysql
|
|
84
|
+
index = line_end(sql, index)
|
|
85
|
+
current << " "
|
|
86
|
+
elsif char == "/" && following == "*" && !executable && (opener = EXECUTABLE_COMMENT.match(sql[index, 16]))
|
|
87
|
+
# Read as SQL on every database: a stricter check elsewhere, where only MySQL runs it.
|
|
88
|
+
executable = true
|
|
89
|
+
index += opener[0].length
|
|
90
|
+
current << " "
|
|
91
|
+
elsif char == "/" && following == "*"
|
|
92
|
+
close = sql.index("*/", index + 2)
|
|
93
|
+
index = close ? close + 2 : sql.length
|
|
94
|
+
current << " "
|
|
95
|
+
elsif ["'", '"', "`"].include?(char)
|
|
96
|
+
stop = closing_quote(sql, index, char, backslash: backslash_escapes?(sql, index, char, mysql))
|
|
97
|
+
current << sql[index...stop]
|
|
98
|
+
index = stop
|
|
99
|
+
elsif char == "$" && (mysql || (index.positive? && sql[index - 1].match?(/[\w$]/)))
|
|
100
|
+
current << char
|
|
101
|
+
index += 1
|
|
102
|
+
elsif char == "$" && (tag = /\A\$[A-Za-z_]*\$/.match(sql[index..]))
|
|
103
|
+
close = sql.index(tag[0], index + tag[0].length)
|
|
104
|
+
stop = close ? close + tag[0].length : sql.length
|
|
105
|
+
current << sql[index...stop]
|
|
106
|
+
index = stop
|
|
107
|
+
elsif char == ";"
|
|
108
|
+
statements << current.strip unless current.strip.empty?
|
|
109
|
+
current = +""
|
|
110
|
+
index += 1
|
|
111
|
+
else
|
|
112
|
+
current << char
|
|
113
|
+
index += 1
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
statements << current.strip unless current.strip.empty?
|
|
117
|
+
statements
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
# @param sql [String] the statement text the application is about to run
|
|
121
|
+
# @param mysql [Boolean] whether the database is MySQL or MariaDB, which also commit implicitly
|
|
122
|
+
# @param safe_procedures [Array<String>] lower-cased names from {normalize_procedures}; any other
|
|
123
|
+
# +CALL+ is refused on MySQL and MariaDB
|
|
124
|
+
# @param reserved [String, nil] a savepoint the provider owns: the handler may not release or roll
|
|
125
|
+
# back to it
|
|
126
|
+
# @return [Boolean] whether it can end or replace the preview transaction
|
|
127
|
+
def ends_transaction?(sql, mysql: false, safe_procedures: [], reserved: nil)
|
|
128
|
+
!reason(sql, mysql: mysql, safe_procedures: safe_procedures, reserved: reserved).nil?
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# Why +sql+ would end or escape the preview transaction, or nil when it is safe.
|
|
132
|
+
# @return [String, nil]
|
|
133
|
+
def reason(sql, mysql: false, safe_procedures: [], reserved: nil)
|
|
134
|
+
split(sql.to_s, mysql: mysql).each do |statement|
|
|
135
|
+
verb = statement.split.first.to_s.upcase
|
|
136
|
+
return "the handler's #{verb} would end the Preview transaction" if statement.match?(CONTROL) || statement.match?(SET_AUTOCOMMIT)
|
|
137
|
+
if reserved && statement.match?(/\A(?:RELEASE|ROLLBACK|SAVEPOINT)\b/i) && statement.match?(/(?<![\w$])`?#{Regexp.escape(reserved)}`?(?![\w$])/i)
|
|
138
|
+
return "the Preview's own savepoint is reserved for Sendproof"
|
|
139
|
+
end
|
|
140
|
+
next unless mysql
|
|
141
|
+
|
|
142
|
+
if statement.match?(MYSQL_CALL_KEYWORD)
|
|
143
|
+
name = MYSQL_CALL.match(statement)&.[](1)
|
|
144
|
+
next if name && safe_procedures.include?(procedure_key(name))
|
|
145
|
+
|
|
146
|
+
return "a CALL can commit the Preview transaction inside the procedure; declare the procedure safe by exact name if it never commits"
|
|
147
|
+
end
|
|
148
|
+
return "the handler's #{verb} runs a statement the Preview can't check" if statement.match?(MYSQL_EXECUTE)
|
|
149
|
+
return "the handler's #{verb} commits implicitly on MySQL" if statement.match?(MYSQL_IMPLICIT_COMMIT) && !statement.match?(MYSQL_TEMPORARY_TABLE)
|
|
150
|
+
end
|
|
151
|
+
nil
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# +`Shop` . `Rebuild`+ -> +"shop.rebuild"+; a quoted name that isn't a plain name never matches.
|
|
155
|
+
def procedure_key(name)
|
|
156
|
+
name.split(/\s*\.\s*/).map { |part| part.delete_prefix("`").delete_suffix("`") }.join(".").downcase
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def line_end(sql, index)
|
|
160
|
+
newline = sql.index("\n", index)
|
|
161
|
+
newline ? newline + 1 : sql.length
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# Whether a backslash escapes the next character inside the quote that opens at +index+.
|
|
165
|
+
def backslash_escapes?(sql, index, quote, mysql)
|
|
166
|
+
return quote != "`" if mysql
|
|
167
|
+
|
|
168
|
+
quote == "'" && index.positive? && sql[index - 1].match?(/[Ee]/) && (index == 1 || !sql[index - 2].match?(/[\w$]/))
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def closing_quote(sql, start, quote, backslash:)
|
|
172
|
+
index = start + 1
|
|
173
|
+
while index < sql.length
|
|
174
|
+
if backslash && sql[index] == "\\"
|
|
175
|
+
index += 2
|
|
176
|
+
elsif sql[index] == quote && sql[index + 1] == quote
|
|
177
|
+
index += 2 # A doubled quote is an escaped quote.
|
|
178
|
+
elsif sql[index] == quote
|
|
179
|
+
return index + 1
|
|
180
|
+
else
|
|
181
|
+
index += 1
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
sql.length
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
end
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// The action bar under the request (mock: request.js "action bar"): a status line that wraps to
|
|
2
|
+
// two lines rather than truncating, then fixed-width Send and Preview buttons. Safe methods
|
|
3
|
+
// show one primary Send and say why there is no Preview instead of disabling it.
|
|
4
|
+
import { esc, icon } from './components.js';
|
|
5
|
+
import { t, th } from './i18n.js';
|
|
6
|
+
import { shortcutAttrs, shortcutHint, shortcutLong, shortcutLabel } from './shortcuts.js';
|
|
7
|
+
import { storeMark, storeNames } from './stores.js';
|
|
8
|
+
|
|
9
|
+
const SAFE = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
10
|
+
|
|
11
|
+
/** True for methods that can't change anything, so Preview has nothing to roll back. */
|
|
12
|
+
export const isReadOnly = op => SAFE.has(op?.method);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The default status line for an operation. `unavailable` is its previewUnavailable entry (an API
|
|
16
|
+
* author marked it preview: false); `blocked` is set when its last Preview was stopped by the
|
|
17
|
+
* write guard, and names the store.
|
|
18
|
+
*/
|
|
19
|
+
export function idleStatus(op, previewAvailable, { unavailable, blocked } = {}) {
|
|
20
|
+
if (blocked) return `<span class="status is-blocked">${icon('ban', true)}<span>${esc(t('bar.lastBlocked', { store: blocked }))}</span></span>`;
|
|
21
|
+
if (unavailable) return `<span class="status">${icon('send', true)}<span>${esc(t('bar.sendOnly'))}</span></span>`;
|
|
22
|
+
if (isReadOnly(op)) return `<span class="status">${icon('eye', true)}<span>${esc(t('bar.readOnly', { method: op.method }))}</span></span>`;
|
|
23
|
+
if (!previewAvailable) return `<span class="status">${icon('info', true)}<span>${esc(t('bar.noPreview'))}</span></span>`;
|
|
24
|
+
return `<span class="status">${icon('undo', true)}<span>${esc(t('bar.rule'))}</span></span>`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Send and Preview. Preview only exists when the operation can be previewed and isn't read-only.
|
|
29
|
+
* An operation marked preview: false keeps a disabled Preview in its place (no layout shift
|
|
30
|
+
* between operations), described by the reason docked above the bar; Send becomes primary.
|
|
31
|
+
*/
|
|
32
|
+
export function runButtons(op, previewAvailable, { unavailable } = {}) {
|
|
33
|
+
const readOnly = isReadOnly(op);
|
|
34
|
+
if (unavailable && !readOnly) {
|
|
35
|
+
return `<button type="button" class="btn btn-run btn-send btn-primary" id="send-btn" data-action="send" ${shortcutAttrs('send')} title="${esc(t('bar.sendTip') + ' · ' + shortcutLong('send'))}">${icon('send', true)}<span>${esc(t('bar.send'))}</span>${shortcutHint('send')}</button>`
|
|
36
|
+
+ `<button type="button" class="btn btn-run btn-preview is-unavailable" data-action="preview" aria-disabled="true" aria-describedby="preview-dock-title" title="${esc(t('bar.previewOffTip'))}">${icon('flask-off', true)}<span>${esc(t('bar.preview'))}</span></button>`;
|
|
37
|
+
}
|
|
38
|
+
const sendShortcut = readOnly ? 'send-read-only' : 'send';
|
|
39
|
+
const send = `<button type="button" class="btn btn-run btn-send${readOnly || !previewAvailable ? ' btn-primary' : ''}" id="send-btn" data-action="send" ${shortcutAttrs(sendShortcut)} title="${esc(t(readOnly ? 'bar.sendTipReadOnly' : 'bar.sendTip') + ' · ' + shortcutLong(sendShortcut))}">${icon('send', true)}<span>${esc(t('bar.send'))}</span>${shortcutHint(sendShortcut)}</button>`;
|
|
40
|
+
const preview = readOnly || !previewAvailable ? ''
|
|
41
|
+
: `<button type="button" class="btn btn-primary btn-run btn-preview" data-action="preview" ${shortcutAttrs('preview')} title="${esc(shortcutLabel('preview') + ' · ' + shortcutLong('preview'))}">${icon('flask', true)}<span>${esc(t('bar.preview'))}</span>${shortcutHint('preview')}</button>`;
|
|
42
|
+
return send + preview;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The whole bar for an idle operation. `options` as for idleStatus. */
|
|
46
|
+
export const actionBar = (op, previewAvailable, options = {}) =>
|
|
47
|
+
op ? idleStatus(op, previewAvailable, options) + runButtons(op, previewAvailable, options) : '';
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The reason a marked operation can't Preview, docked right above the action bar with a caret to
|
|
51
|
+
* the disabled Preview button (mocks 122, 128, 130, m29): the store's mark, "Preview unavailable",
|
|
52
|
+
* the author's reason (their words, in English, so lang="en"), why, and who marked it. It takes
|
|
53
|
+
* layout space, so it never covers the form. On a phone "Why?" opens the explanation.
|
|
54
|
+
*/
|
|
55
|
+
export function previewDock(entry) {
|
|
56
|
+
if (!entry) return '';
|
|
57
|
+
const store = entry.stores[0];
|
|
58
|
+
const why = entry.stores.length ? t('dock.why', { stores: storeNames(entry.stores) }) : t('dock.whyNoStore');
|
|
59
|
+
return `<span class="pv-tile">${store ? storeMark(store, 20) : icon('flask-off')}</span>
|
|
60
|
+
<div class="pv-text">
|
|
61
|
+
<p class="pv-title"><strong id="preview-dock-title">${esc(t('dock.title'))}</strong>${entry.reason ? `<span class="pv-reason" lang="en">${esc(entry.reason)}</span>` : ''}</p>
|
|
62
|
+
<p class="pv-sub"><span class="pv-why" id="preview-dock-why">${esc(why)} </span><span class="pv-by">${th('dock.by', { mark: '<code class="ltr">preview: false</code>' })}</span>
|
|
63
|
+
<button type="button" class="pv-more" data-action="dock-why" aria-expanded="false" aria-controls="preview-dock-why">${esc(t('dock.more'))}</button></p>
|
|
64
|
+
</div>
|
|
65
|
+
<span class="pv-caret" aria-hidden="true"></span>`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The status while a request runs: who it runs as, and that editing stays possible. */
|
|
69
|
+
export function runningStatus(preview, identity) {
|
|
70
|
+
const key = preview ? (identity ? 'bar.previewingAs' : 'bar.previewing') : (identity ? 'bar.sendingAs' : 'bar.sending');
|
|
71
|
+
return `<span class="spinner" aria-hidden="true"></span><span>${esc(t(key, { name: identity }))}</span>`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The status after generated values were filled in, with Undo. */
|
|
75
|
+
export function generatedStatus(count) {
|
|
76
|
+
return `<span class="status is-ok" role="status">${icon('wand', true)}<span>${esc(t('bar.filled', { n: count }))}</span><button type="button" class="btn btn-ghost btn-xs" data-action="undo-fill" ${shortcutAttrs('autofill-undo')}>${esc(t('bar.undo'))} ${shortcutHint('autofill-undo')}</button></span>`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The confirmation that replaces the buttons before a committing Send. Cancel and Confirm send sit
|
|
81
|
+
* in one pair that is at least as wide as Send + Preview, so the status keeps its room, and that
|
|
82
|
+
* grows to fit a long translation instead of clipping it (see .run-pair in app.css).
|
|
83
|
+
*/
|
|
84
|
+
export function confirmation(method, path, stores = []) {
|
|
85
|
+
const text = stores.length ? t('bar.confirmStores', { stores: storeNames(stores) }) : t('bar.confirm', { method, path });
|
|
86
|
+
return `<span class="status${stores.length ? ' is-confirm-store' : ''}" role="status">${stores.length ? icon('warn', true) : ''}<span>${esc(text)}</span></span>
|
|
87
|
+
<span class="run-pair">
|
|
88
|
+
<button type="button" class="btn btn-run btn-ghost" data-action="cancel-confirm" ${shortcutAttrs('escape')}>${esc(t('bar.cancel'))} ${shortcutHint('escape')}</button>
|
|
89
|
+
<button type="button" class="btn btn-run btn-primary" data-action="confirm-send" ${shortcutAttrs('send')}>${icon('send', true)}<span>${esc(t('bar.confirmSend'))}</span>${shortcutHint('send')}</button>
|
|
90
|
+
</span>`;
|
|
91
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { blockedPreview } from './stores.js';
|
|
2
|
+
|
|
3
|
+
const methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'];
|
|
4
|
+
|
|
5
|
+
/** Resolve a local OpenAPI Reference Object without requesting external documents. */
|
|
6
|
+
export function dereference(value, document) {
|
|
7
|
+
if (!value?.$ref?.startsWith('#/')) return value;
|
|
8
|
+
const parts = value.$ref.slice(2).split('/');
|
|
9
|
+
return parts.reduce((node, part) => {
|
|
10
|
+
const key = part.replace(/~1/g, '/').replace(/~0/g, '~');
|
|
11
|
+
return node && Object.hasOwn(node, key) ? node[key] : undefined;
|
|
12
|
+
}, document);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Operation parameters override path-level parameters with the same name and location. */
|
|
16
|
+
export function operations(document) {
|
|
17
|
+
const discovered = [];
|
|
18
|
+
for (const [path, rawItem] of Object.entries(document.paths || {})) {
|
|
19
|
+
const item = dereference(rawItem, document);
|
|
20
|
+
for (const verb of methods) {
|
|
21
|
+
const operation = item?.[verb];
|
|
22
|
+
if (!operation) continue;
|
|
23
|
+
const parameters = new Map();
|
|
24
|
+
for (const raw of [...(item.parameters || []), ...(operation.parameters || [])]) {
|
|
25
|
+
const parameter = dereference(raw, document);
|
|
26
|
+
if (parameter) parameters.set(parameter.in + ':' + parameter.name, parameter);
|
|
27
|
+
}
|
|
28
|
+
const method = verb.toUpperCase();
|
|
29
|
+
discovered.push({
|
|
30
|
+
method, path, operation, parameters: [...parameters.values()],
|
|
31
|
+
title: operation.summary || operation.operationId || method + ' ' + path,
|
|
32
|
+
group: operation.tags?.[0] || 'Operations',
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return discovered;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Prepare the browser body and its matching media type together. The caller
|
|
41
|
+
* passes the same mutable headers object to makeRequest. For multipart bodies
|
|
42
|
+
* fetch supplies the boundary and Content-Type itself.
|
|
43
|
+
*/
|
|
44
|
+
export function encodeRequestBody(value, mediaType = 'application/json', headers = {}) {
|
|
45
|
+
if (value === undefined) return undefined;
|
|
46
|
+
const type = mediaType.split(';')[0].trim().toLowerCase();
|
|
47
|
+
const multipart = type === 'multipart/form-data';
|
|
48
|
+
if (headers instanceof Headers) {
|
|
49
|
+
headers.delete('Content-Type');
|
|
50
|
+
if (!multipart) headers.set('Content-Type', mediaType);
|
|
51
|
+
} else {
|
|
52
|
+
for (const key of Object.keys(headers)) {
|
|
53
|
+
if (key.toLowerCase() === 'content-type') delete headers[key];
|
|
54
|
+
}
|
|
55
|
+
if (!multipart) headers['Content-Type'] = mediaType;
|
|
56
|
+
}
|
|
57
|
+
if (type === 'application/json' || type.endsWith('+json')) return JSON.stringify(value);
|
|
58
|
+
if (multipart || type === 'application/x-www-form-urlencoded') {
|
|
59
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
60
|
+
throw new Error('Form-encoded requests require named fields.');
|
|
61
|
+
}
|
|
62
|
+
const data = multipart ? new FormData() : new URLSearchParams();
|
|
63
|
+
for (const [name, field] of Object.entries(value)) {
|
|
64
|
+
for (const item of Array.isArray(field) ? field : [field]) {
|
|
65
|
+
if (item === undefined) continue;
|
|
66
|
+
if (item instanceof Blob) {
|
|
67
|
+
if (!multipart) throw new Error('File uploads require multipart/form-data.');
|
|
68
|
+
data.append(name, item);
|
|
69
|
+
} else {
|
|
70
|
+
data.append(name, item !== null && typeof item === 'object' ? JSON.stringify(item) : String(item ?? ''));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return data;
|
|
75
|
+
}
|
|
76
|
+
if (value instanceof Blob || typeof value === 'string') return value;
|
|
77
|
+
throw new Error('Supply text or a file for ' + mediaType + '.');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function scalarParts(value, explode) {
|
|
81
|
+
if (Array.isArray(value)) return value.map(String);
|
|
82
|
+
if (typeof value === 'object') {
|
|
83
|
+
return Object.entries(value).flatMap(([key, item]) => explode ? [key + '=' + item] : [key, String(item)]);
|
|
84
|
+
}
|
|
85
|
+
return [String(value)];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function addQuery(query, parameter) {
|
|
89
|
+
const { name, value, style = 'form', explode = style === 'form' } = parameter;
|
|
90
|
+
if (!Array.isArray(value) && typeof value === 'object' && (explode || style === 'deepObject')) {
|
|
91
|
+
for (const [key, item] of Object.entries(value)) {
|
|
92
|
+
query.append(style === 'deepObject' ? name + '[' + key + ']' : key, String(item));
|
|
93
|
+
}
|
|
94
|
+
} else if (Array.isArray(value) && explode) {
|
|
95
|
+
for (const item of value) query.append(name, String(item));
|
|
96
|
+
} else {
|
|
97
|
+
const separator = { spaceDelimited: ' ', pipeDelimited: '|' }[style] ?? ',';
|
|
98
|
+
query.append(name, scalarParts(value, false).join(separator));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function pathParameter({ name, value, style = 'simple', explode = false }) {
|
|
103
|
+
const isObject = typeof value === 'object' && !Array.isArray(value);
|
|
104
|
+
const parts = isObject && explode
|
|
105
|
+
? Object.entries(value).map(([key, item]) => encodeURIComponent(key) + '=' + encodeURIComponent(item))
|
|
106
|
+
: scalarParts(value, false).map(encodeURIComponent);
|
|
107
|
+
if (style === 'label') return '.' + parts.join(explode ? '.' : ',');
|
|
108
|
+
if (style === 'matrix') {
|
|
109
|
+
if (explode && isObject) return ';' + parts.join(';');
|
|
110
|
+
const prefix = ';' + encodeURIComponent(name) + '=';
|
|
111
|
+
return prefix + parts.join(explode ? prefix : ',');
|
|
112
|
+
}
|
|
113
|
+
return parts.join(',');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Construct a same-origin request relative to the mounted application's PathBase. */
|
|
117
|
+
export function makeRequest(op, parameters, body, extraHeaders, basePath) {
|
|
118
|
+
let path = op.path;
|
|
119
|
+
const query = new URLSearchParams();
|
|
120
|
+
const headers = new Headers(extraHeaders);
|
|
121
|
+
for (const parameter of parameters) {
|
|
122
|
+
const { name, value } = parameter;
|
|
123
|
+
if (value === undefined || value === null || value === '') {
|
|
124
|
+
if (parameter.required) throw new Error(name + ' is required');
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
switch (parameter.in) {
|
|
128
|
+
case 'path': path = path.replace('{' + name + '}', () => pathParameter(parameter)); break;
|
|
129
|
+
case 'query': addQuery(query, parameter); break;
|
|
130
|
+
case 'header': headers.set(name, scalarParts(value, parameter.explode).join(',')); break;
|
|
131
|
+
case 'cookie': throw new Error('Cookie parameter ' + name + ' must be supplied by the browser session.');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (/\{[^}]+\}/.test(path)) throw new Error('Complete all path parameters.');
|
|
135
|
+
if (!path.startsWith('/') || path.startsWith('//') || /[\\?#]/.test(path)) {
|
|
136
|
+
throw new Error('The operation must have an application-relative path.');
|
|
137
|
+
}
|
|
138
|
+
const url = new URL(basePath + path.slice(1), location.origin);
|
|
139
|
+
if (url.origin !== location.origin || !url.pathname.startsWith(basePath)) {
|
|
140
|
+
throw new Error('The operation is outside the application path.');
|
|
141
|
+
}
|
|
142
|
+
url.search = query.toString();
|
|
143
|
+
return { method: op.method, url: url.href, headers, body };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Resolve the same-origin wire request for execution or export, including rollback intent. */
|
|
147
|
+
export function transportRequest(request, preview, basePath, { observedSend = false } = {}) {
|
|
148
|
+
const target = new URL(request.url);
|
|
149
|
+
if (target.origin !== location.origin || !target.pathname.startsWith(basePath)) {
|
|
150
|
+
throw new Error('The request is outside the application path.');
|
|
151
|
+
}
|
|
152
|
+
const headers = new Headers(request.headers);
|
|
153
|
+
let url = target.href;
|
|
154
|
+
if (preview) {
|
|
155
|
+
url = new URL('./_preview/' + target.pathname.slice(basePath.length) + target.search, document.baseURI).href;
|
|
156
|
+
headers.set('Prefer', 'tx=rollback');
|
|
157
|
+
} else if (observedSend) {
|
|
158
|
+
const preferences = (headers.get('Prefer') || '').split(',').map(value => value.trim()).filter(Boolean);
|
|
159
|
+
if (!preferences.some(value => /^trace(?:\s*;|$)/i.test(value))) preferences.push('trace');
|
|
160
|
+
headers.set('Prefer', preferences.join(', '));
|
|
161
|
+
}
|
|
162
|
+
return { ...request, url, headers };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export class RequestTransportError extends Error {}
|
|
166
|
+
|
|
167
|
+
async function readTrace(id, signal) {
|
|
168
|
+
if (!/^(?:[a-f\d]{32}|[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})$/i.test(id || '')) return {};
|
|
169
|
+
try {
|
|
170
|
+
const url = new URL('./_api/traces/' + id, document.baseURI);
|
|
171
|
+
const response = await fetch(url.href, { signal, credentials: 'include', redirect: 'error' });
|
|
172
|
+
if (!response.ok) return {};
|
|
173
|
+
const trace = await response.json();
|
|
174
|
+
if (!trace || typeof trace !== 'object') return {};
|
|
175
|
+
const evidence = { traceId: id };
|
|
176
|
+
for (const name of ['changes', 'effects', 'logs']) {
|
|
177
|
+
if (Array.isArray(trace[name])) evidence[name] = trace[name];
|
|
178
|
+
if (trace[name + 'Truncated'] === true) evidence[name + 'Truncated'] = true;
|
|
179
|
+
}
|
|
180
|
+
if (trace.timing && typeof trace.timing === 'object') evidence.timing = trace.timing;
|
|
181
|
+
return evidence;
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (signal?.aborted) throw error;
|
|
184
|
+
// The original request may have committed. Optional trace loss never changes its outcome.
|
|
185
|
+
return {};
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export async function execute(request, preview, basePath, signal, { observedSend = false } = {}) {
|
|
190
|
+
const wireRequest = transportRequest(request, preview, basePath, { observedSend });
|
|
191
|
+
const { url, method, headers, body: payload } = wireRequest;
|
|
192
|
+
const started = performance.now();
|
|
193
|
+
let response, raw;
|
|
194
|
+
try {
|
|
195
|
+
response = await fetch(url, {
|
|
196
|
+
method, headers, body: payload, signal,
|
|
197
|
+
credentials: 'include', redirect: 'error',
|
|
198
|
+
});
|
|
199
|
+
raw = await response.text();
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (signal?.aborted || error.name === 'AbortError') throw error;
|
|
202
|
+
const failure = new RequestTransportError(error.message, { cause: error });
|
|
203
|
+
failure.wireRequest = wireRequest;
|
|
204
|
+
throw failure;
|
|
205
|
+
}
|
|
206
|
+
let body = raw || null;
|
|
207
|
+
if (raw) {
|
|
208
|
+
try { body = JSON.parse(raw); } catch { /* Keep text responses as received. */ }
|
|
209
|
+
}
|
|
210
|
+
const duration = Math.round(performance.now() - started);
|
|
211
|
+
const byteCount = value => new TextEncoder().encode(value).length;
|
|
212
|
+
const metadata = {
|
|
213
|
+
duration, wireRequest, requestUrl: request.url, requestHeaders: Object.fromEntries(headers),
|
|
214
|
+
serverTiming: response.headers.get('Server-Timing') || undefined,
|
|
215
|
+
};
|
|
216
|
+
if (preview) {
|
|
217
|
+
// The write guard stopped the Preview (spec/data-stores.md): a designed result, not an error.
|
|
218
|
+
// Nothing ran to completion, so there are no captured changes, effects or logs to show.
|
|
219
|
+
const blocked = blockedPreview(response.status, body);
|
|
220
|
+
if (blocked) {
|
|
221
|
+
return {
|
|
222
|
+
status: response.status, headers: Object.fromEntries(response.headers), body, raw, blocked,
|
|
223
|
+
changes: [], effects: [], logs: [], ...metadata, size: byteCount(raw), preview: true,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
if (!response.ok || body?.rolledBack !== true || !Number.isInteger(body.status)) {
|
|
227
|
+
throw new Error('Preview was not acknowledged as rolled back (HTTP ' + response.status + '). ' + (body?.title || ''));
|
|
228
|
+
}
|
|
229
|
+
const type = Object.entries(body.headers || {}).find(([name]) => name.toLowerCase() === 'content-type')?.[1] || '';
|
|
230
|
+
const content = body.body == null ? '' :
|
|
231
|
+
typeof body.body === 'string' && !/json/i.test(type) ? body.body : JSON.stringify(body.body);
|
|
232
|
+
return { ...body, ...metadata, raw: content, size: byteCount(content), preview: true };
|
|
233
|
+
}
|
|
234
|
+
const trace = observedSend ? await readTrace(response.headers.get('X-Sendproof-Trace'), signal) : {};
|
|
235
|
+
return {
|
|
236
|
+
status: response.status, headers: Object.fromEntries(response.headers), body, raw,
|
|
237
|
+
changes: [], effects: [], logs: [], ...trace, ...metadata, size: byteCount(raw), preview: false,
|
|
238
|
+
};
|
|
239
|
+
}
|