@voxgig/sdkgen 4.40.1 → 4.41.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 (85) hide show
  1. package/bin/voxgig-sdkgen +1 -1
  2. package/dist/cmp/Main.js +4 -0
  3. package/dist/cmp/Main.js.map +1 -1
  4. package/dist/helpers/testPolicy.d.ts +5 -1
  5. package/dist/helpers/testPolicy.js +32 -3
  6. package/dist/helpers/testPolicy.js.map +1 -1
  7. package/dist/helpers/useragent.d.ts +2 -0
  8. package/dist/helpers/useragent.js +31 -0
  9. package/dist/helpers/useragent.js.map +1 -0
  10. package/dist/sdkgen.d.ts +2 -2
  11. package/dist/sdkgen.js +6 -3
  12. package/dist/sdkgen.js.map +1 -1
  13. package/dist/testkit.js +1 -1
  14. package/dist/testkit.js.map +1 -1
  15. package/dist/tsconfig.tsbuildinfo +1 -1
  16. package/model/sdkgen.aontu +6 -0
  17. package/package.json +1 -1
  18. package/project/.sdk/src/cmp/csharp/TestEntity_csharp.ts +35 -16
  19. package/project/.sdk/src/cmp/go/ReadmeExamplesTest_go.ts +7 -6
  20. package/project/.sdk/src/cmp/go/TestEntity_go.ts +24 -13
  21. package/project/.sdk/src/cmp/java/TestEntity_java.ts +21 -11
  22. package/project/.sdk/src/cmp/kotlin/TestEntity_kotlin.ts +26 -14
  23. package/project/.sdk/src/cmp/lua/ReadmeExamplesTest_lua.ts +7 -5
  24. package/project/.sdk/src/cmp/lua/ReadmeHowto_lua.ts +12 -0
  25. package/project/.sdk/src/cmp/lua/TestEntity_lua.ts +25 -13
  26. package/project/.sdk/src/cmp/perl/ReadmeExamplesTest_perl.ts +15 -1
  27. package/project/.sdk/src/cmp/perl/TestEntity_perl.ts +23 -13
  28. package/project/.sdk/src/cmp/php/ReadmeExamplesTest_php.ts +31 -2
  29. package/project/.sdk/src/cmp/php/TestEntity_php.ts +29 -14
  30. package/project/.sdk/src/cmp/py/ReadmeExamplesTest_py.ts +14 -1
  31. package/project/.sdk/src/cmp/py/TestEntity_py.ts +28 -14
  32. package/project/.sdk/src/cmp/rb/ReadmeExamplesTest_rb.ts +18 -1
  33. package/project/.sdk/src/cmp/rb/TestEntity_rb.ts +24 -13
  34. package/project/.sdk/src/cmp/rust/TestEntity_rust.ts +27 -14
  35. package/project/.sdk/src/cmp/ts/ReadmeExamplesTest_ts.ts +7 -2
  36. package/project/.sdk/tm/c/feature/test.c +22 -2
  37. package/project/.sdk/tm/c/tests/transport_test.c +2 -2
  38. package/project/.sdk/tm/c/utility/http.c +1 -1
  39. package/project/.sdk/tm/clojure/src/sdk/core.clj +1 -1
  40. package/project/.sdk/tm/clojure/src/sdk/features.clj +13 -1
  41. package/project/.sdk/tm/cpp/feature/test.hpp +16 -2
  42. package/project/.sdk/tm/csharp/feature/TestFeature.cs +18 -0
  43. package/project/.sdk/tm/csharp/utility/Fetcher.cs +5 -4
  44. package/project/.sdk/tm/elixir/lib/projectname/feature/test.ex +19 -1
  45. package/project/.sdk/tm/elixir/lib/projectname/utility.ex +1 -1
  46. package/project/.sdk/tm/go/feature/test_feature.go +16 -0
  47. package/project/.sdk/tm/go/utility/fetcher.go +4 -3
  48. package/project/.sdk/tm/java/feature/TestFeature.java +15 -0
  49. package/project/.sdk/tm/java/utility/Fetcher.java +4 -4
  50. package/project/.sdk/tm/js/src/feature/test/TestFeature.js +16 -0
  51. package/project/.sdk/tm/js/src/utility/FetcherUtility.js +4 -3
  52. package/project/.sdk/tm/js/src/utility/ResultBodyUtility.js +19 -1
  53. package/project/.sdk/tm/js/test/live-entity.js +2 -1
  54. package/project/.sdk/tm/kotlin/feature/TestFeature.kt +15 -0
  55. package/project/.sdk/tm/kotlin/utility/Fetcher.kt +1 -1
  56. package/project/.sdk/tm/lua/feature/secrets_feature.lua +9 -2
  57. package/project/.sdk/tm/lua/feature/test_feature.lua +18 -0
  58. package/project/.sdk/tm/lua/utility/fetcher.lua +11 -25
  59. package/project/.sdk/tm/lua/utility/tls.lua +241 -0
  60. package/project/.sdk/tm/ocaml/sdk_features.ml +18 -1
  61. package/project/.sdk/tm/perl/feature/test_feature.pm +12 -0
  62. package/project/.sdk/tm/perl/utility/fetcher.pm +4 -4
  63. package/project/.sdk/tm/php/feature/TestFeature.php +18 -1
  64. package/project/.sdk/tm/php/utility/Fetcher.php +4 -4
  65. package/project/.sdk/tm/py/pkg/feature/test_feature.py +20 -4
  66. package/project/.sdk/tm/py/pkg/utility/fetcher.py +4 -4
  67. package/project/.sdk/tm/rb/feature/test_feature.rb +14 -1
  68. package/project/.sdk/tm/rb/utility/fetcher.rb +56 -6
  69. package/project/.sdk/tm/rust/feature/test.rs +18 -0
  70. package/project/.sdk/tm/rust/utility/fetcher.rs +4 -4
  71. package/project/.sdk/tm/scala/feature/TestFeature.scala +12 -0
  72. package/project/.sdk/tm/scala/utility/Fetcher.scala +1 -1
  73. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/feature/TestFeature.swift +15 -0
  74. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Fetcher.swift +1 -1
  75. package/project/.sdk/tm/ts/src/feature/test/TestFeature.ts +26 -5
  76. package/project/.sdk/tm/ts/src/utility/FetcherUtility.ts +4 -3
  77. package/project/.sdk/tm/ts/src/utility/ResultBodyUtility.ts +19 -1
  78. package/project/.sdk/tm/ts/test/live-entity.ts +2 -1
  79. package/project/.sdk/tm/zig/feature/test.zig +23 -0
  80. package/project/sdkgen-package.json +1 -1
  81. package/src/cmp/Main.ts +5 -0
  82. package/src/helpers/testPolicy.ts +32 -3
  83. package/src/helpers/useragent.ts +41 -0
  84. package/src/sdkgen.ts +4 -0
  85. package/src/testkit.ts +1 -1
@@ -3,6 +3,7 @@
3
3
  local vs = require("utility.struct.struct")
4
4
  local json = require("dkjson")
5
5
  local ProjectNameError = require("core.error")
6
+ local tls = require("utility.tls")
6
7
 
7
8
  local GETONLY_ENV = "VOXGIG_GETONLY_GUARD"
8
9
 
@@ -225,27 +226,6 @@ local function decode_body(body, encoding)
225
226
  return inflate_raw(body, 1)
226
227
  end
227
228
 
228
- -- OpenSSL reports a TLS close without close_notify as "unexpected eof while
229
- -- reading", where every other target reads it as the end of the body. The
230
- -- other options are luasec's defaults, which an options list replaces.
231
- local TLS_OPTIONS = { "all", "no_sslv2", "no_sslv3", "no_tlsv1", "ignore_unexpected_eof" }
232
-
233
- local function tls_options()
234
- local ssl_ok, ssl = pcall(require, "ssl")
235
- local known = ssl_ok and type(ssl) == "table" and type(ssl.config) == "table"
236
- and ssl.config.options or nil
237
- if type(known) ~= "table" or not known.ignore_unexpected_eof then
238
- return nil
239
- end
240
- local options = {}
241
- for _, name in ipairs(TLS_OPTIONS) do
242
- if known[name] then
243
- table.insert(options, name)
244
- end
245
- end
246
- return options
247
- end
248
-
249
229
  local function send_once(fullurl, fetchdef)
250
230
  -- Use LuaSocket or similar for real HTTP requests.
251
231
  -- This is the default live implementation.
@@ -268,8 +248,8 @@ local function send_once(fullurl, fetchdef)
268
248
  headers["content-length"] = tostring(#body_str)
269
249
  end
270
250
 
271
- -- Default User-Agent — many CDNs reject requests with no UA. Set a
272
- -- Mozilla-shaped UA unless the caller already set one.
251
+ -- Default User-Agent — many CDNs reject requests with no UA. Set the
252
+ -- project's agent (main.kit.http.useragent) unless the caller set one.
273
253
  local has_ua = false
274
254
  for k, _ in pairs(headers) do
275
255
  if string.lower(k) == "user-agent" then
@@ -278,7 +258,13 @@ local function send_once(fullurl, fetchdef)
278
258
  end
279
259
  end
280
260
  if not has_ua then
281
- headers["User-Agent"] = "Mozilla/5.0 (compatible; ProjectNameSDK/1.0)"
261
+ headers["User-Agent"] = "PROJECTUSERAGENT"
262
+ end
263
+
264
+ -- An https connection is verified before any byte of the request is sent.
265
+ local create, refused = tls.create(fullurl)
266
+ if refused ~= nil then
267
+ return nil, refused
282
268
  end
283
269
 
284
270
  local response_body = {}
@@ -289,7 +275,7 @@ local function send_once(fullurl, fetchdef)
289
275
  source = body_str and ltn12.source.string(body_str) or nil,
290
276
  sink = ltn12.sink.table(response_body),
291
277
  redirect = false,
292
- options = string.find(string.lower(fullurl), "^https:") and tls_options() or nil,
278
+ create = create,
293
279
  })
294
280
 
295
281
  if not res then
@@ -0,0 +1,241 @@
1
+ -- ProjectName SDK utility: tls
2
+ --
3
+ -- What an https request trusts. luasec's own https defaults to verify = "none",
4
+ -- which accepts any certificate for any host, so a request here builds its own
5
+ -- connection instead: (1) the chain is verified against the system trust
6
+ -- store, which SSL_CERT_FILE and SSL_CERT_DIR name as they do for OpenSSL, and
7
+ -- with none found the request is refused, never sent unverified; (2) the host
8
+ -- name is verified, an IP literal as an address; (3) SNI is sent for a name;
9
+ -- (4) PROJECTENV_CA_BUNDLE adds roots beside the system's. Nothing turns this
10
+ -- off: a caller that needs another policy supplies options.system.fetch.
11
+
12
+ local M = {}
13
+
14
+ -- Bundles, then hashed directories, where systems keep their trusted roots.
15
+ local CA_FILES = {
16
+ "/etc/ssl/certs/ca-certificates.crt",
17
+ "/etc/pki/tls/certs/ca-bundle.crt",
18
+ "/etc/ssl/ca-bundle.pem",
19
+ "/etc/pki/tls/cacert.pem",
20
+ "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
21
+ "/etc/ssl/cert.pem",
22
+ "/usr/local/etc/ssl/cert.pem",
23
+ "/usr/local/share/certs/ca-root-nss.crt",
24
+ "/opt/homebrew/etc/openssl@3/cert.pem",
25
+ "/usr/local/etc/openssl@3/cert.pem",
26
+ }
27
+
28
+ local CA_DIRS = {
29
+ "/etc/ssl/certs",
30
+ "/etc/pki/tls/certs",
31
+ "/system/etc/security/cacerts",
32
+ }
33
+
34
+ local SAN = "2.5.29.17"
35
+
36
+ -- OpenSSL reports a TLS close without close_notify as "unexpected eof while
37
+ -- reading", where every other target reads it as the end of the body.
38
+ local OPTIONS = { "all", "no_sslv2", "no_sslv3", "no_tlsv1", "ignore_unexpected_eof" }
39
+
40
+
41
+ local function readable(path)
42
+ local f = io.open(path, "r")
43
+ if f == nil then
44
+ return false
45
+ end
46
+ local ok = f:read(0) ~= nil
47
+ f:close()
48
+ return ok
49
+ end
50
+
51
+ local function present(path)
52
+ return os.rename(path, path) == true
53
+ end
54
+
55
+ local function setting(name)
56
+ local value = os.getenv(name)
57
+ if value == nil or value == "" then
58
+ return nil
59
+ end
60
+ return value
61
+ end
62
+
63
+
64
+ -- The system trust store: what the environment names, or else the first
65
+ -- bundle or directory found.
66
+ local function trust_store()
67
+ local file, dir = setting("SSL_CERT_FILE"), setting("SSL_CERT_DIR")
68
+ if file ~= nil or dir ~= nil then
69
+ if file ~= nil and not readable(file) then
70
+ return nil, nil, "SSL_CERT_FILE names a file that cannot be read: " .. file
71
+ end
72
+ if dir ~= nil and not present(dir) then
73
+ return nil, nil, "SSL_CERT_DIR names a directory that does not exist: " .. dir
74
+ end
75
+ return file, dir
76
+ end
77
+ for _, path in ipairs(CA_FILES) do
78
+ if readable(path) then
79
+ return path, nil
80
+ end
81
+ end
82
+ for _, path in ipairs(CA_DIRS) do
83
+ if present(path) then
84
+ return nil, path
85
+ end
86
+ end
87
+ return nil, nil, "no system trust store was found to verify the server; " ..
88
+ "SSL_CERT_FILE or SSL_CERT_DIR names one"
89
+ end
90
+
91
+
92
+ local function options(ssl)
93
+ local known = type(ssl.config) == "table" and ssl.config.options or nil
94
+ if type(known) ~= "table" then
95
+ return nil
96
+ end
97
+ local out = {}
98
+ for _, name in ipairs(OPTIONS) do
99
+ if known[name] then
100
+ table.insert(out, name)
101
+ end
102
+ end
103
+ return out
104
+ end
105
+
106
+
107
+ local function unbracket(host)
108
+ return (string.gsub(string.lower(host), "^%[(.*)%]$", "%1"))
109
+ end
110
+
111
+ local function is_address(host)
112
+ return string.find(host, "^%d+%.%d+%.%d+%.%d+$") ~= nil or string.find(host, ":", 1, true) ~= nil
113
+ end
114
+
115
+ -- A DNS name against one certificate name: a wildcard stands for the whole
116
+ -- left-most label, and never for a label of a public suffix alone.
117
+ local function name_matches(pattern, host)
118
+ pattern = string.lower(pattern)
119
+ if pattern == host then
120
+ return true
121
+ end
122
+ if string.sub(pattern, 1, 2) ~= "*." then
123
+ return false
124
+ end
125
+ local rest = string.sub(pattern, 2)
126
+ if select(2, string.gsub(rest, "%.", "")) < 2 then
127
+ return false
128
+ end
129
+ local label, tail = string.match(host, "^([^.]+)(%..+)$")
130
+ return label ~= nil and tail == rest
131
+ end
132
+
133
+ -- Whether the certificate names the host: its subject alternative names, or
134
+ -- its common name where it carries no DNS name.
135
+ local function certifies(cert, host)
136
+ host = unbracket(host)
137
+ local ext = cert:extensions() or {}
138
+ local san = ext[SAN] or {}
139
+ if is_address(host) then
140
+ for _, ip in ipairs(san.iPAddress or {}) do
141
+ if string.lower(ip) == host then
142
+ return true
143
+ end
144
+ end
145
+ return false
146
+ end
147
+ local dns = san.dNSName or {}
148
+ if #dns == 0 then
149
+ for _, entry in ipairs(cert:subject() or {}) do
150
+ if entry.name == "commonName" then
151
+ table.insert(dns, entry.value)
152
+ end
153
+ end
154
+ end
155
+ for _, name in ipairs(dns) do
156
+ if name_matches(name, host) then
157
+ return true
158
+ end
159
+ end
160
+ return false
161
+ end
162
+
163
+
164
+ -- A verified context, or the reason none can be made.
165
+ local function context(ssl)
166
+ local cafile, capath, missing = trust_store()
167
+ if missing ~= nil then
168
+ return nil, missing
169
+ end
170
+ local ctx, err = ssl.newcontext({
171
+ mode = "client",
172
+ protocol = "any",
173
+ options = options(ssl),
174
+ verify = "peer",
175
+ cafile = cafile,
176
+ capath = capath,
177
+ })
178
+ if ctx == nil then
179
+ return nil, "the system trust store cannot be loaded: " .. tostring(err)
180
+ end
181
+ local bundle = setting("PROJECTENV_CA_BUNDLE")
182
+ if bundle ~= nil then
183
+ local ok = readable(bundle) and require("ssl.context").locations(ctx, bundle, nil)
184
+ if not ok then
185
+ return nil, "the CA bundle PROJECTENV_CA_BUNDLE names cannot be read: " .. bundle
186
+ end
187
+ end
188
+ return ctx
189
+ end
190
+
191
+
192
+ -- socket.http's `create` for an https URL: a connection verified before any
193
+ -- byte of the request is written. Nil and the reason when it cannot verify.
194
+ function M.create(fullurl)
195
+ if string.find(string.lower(fullurl), "^https:") == nil then
196
+ return nil
197
+ end
198
+ local ok, ssl = pcall(require, "ssl")
199
+ local sock_ok, socket = pcall(require, "socket")
200
+ if not ok or not sock_ok or type(ssl) ~= "table" then
201
+ return nil, "TLS: an https request needs luasec (ssl) installed"
202
+ end
203
+ local ctx, err = context(ssl)
204
+ if ctx == nil then
205
+ return nil, "TLS: " .. err
206
+ end
207
+ local https_ok, https = pcall(require, "ssl.https")
208
+ local timeout = https_ok and type(https) == "table" and https.TIMEOUT or 60
209
+
210
+ return function()
211
+ local conn = { sock = socket.try(socket.tcp()) }
212
+ local settimeout = getmetatable(conn.sock).__index.settimeout
213
+ function conn:settimeout()
214
+ return settimeout(self.sock, timeout)
215
+ end
216
+ function conn:connect(host, port)
217
+ socket.try(self.sock:connect(host, port))
218
+ self.sock = socket.try(ssl.wrap(self.sock, ctx))
219
+ if not is_address(unbracket(host)) then
220
+ self.sock:sni(host)
221
+ end
222
+ self.sock:settimeout(timeout)
223
+ socket.try(self.sock:dohandshake())
224
+ local cert = self.sock:getpeercertificate()
225
+ if cert == nil or not certifies(cert, host) then
226
+ self.sock:close()
227
+ socket.try(nil, "certificate verify failed: the certificate does not name " .. host)
228
+ end
229
+ for name, method in pairs(getmetatable(self.sock).__index) do
230
+ if type(method) == "function" then
231
+ self[name] = function(c, ...) return method(c.sock, ...) end
232
+ end
233
+ end
234
+ return 1
235
+ end
236
+ return conn
237
+ end
238
+ end
239
+
240
+
241
+ return M
@@ -1539,6 +1539,12 @@ let test_feature () : feature =
1539
1539
  let reqd_names point kind =
1540
1540
  let reqd_args = select (getpath_s point ("args." ^ kind)) (jo [("reqd", Bool true)]) in
1541
1541
  transform reqd_args (ja [Str "`$EACH`"; Str ""; Str "`$KEY.name`"]) in
1542
+ (* The entity's declared identity field (`entity.id.field`), where it names
1543
+ one other than the `id` every record already carries. *)
1544
+ let declared_id_field config entname =
1545
+ match getpath_s config ("entity." ^ entname ^ ".id.field") with
1546
+ | Str f when f <> "" && f <> "id" -> Some f
1547
+ | _ -> None in
1542
1548
  let build_args ctx (op : operation) args =
1543
1549
  let opname = op.op_name in
1544
1550
  let entname = match ctx.c_entity with Some e -> e.e_name | None -> "_" in
@@ -1631,6 +1637,9 @@ let test_feature () : feature =
1631
1637
  | Map _ ->
1632
1638
  ignore (delprop ent (Str "$body"));
1633
1639
  setp ent "id" eid;
1640
+ (match declared_id_field fctx.c_config op.op_entity with
1641
+ | Some f when is_nullish (getp ent f) -> setp ent f eid
1642
+ | _ -> ());
1634
1643
  (match eid with Str s -> setp entmap s ent | _ -> ());
1635
1644
  ignore (delprop ent (Str "$KEY"));
1636
1645
  respond fctx 200 (clone ent) None
@@ -1664,7 +1673,15 @@ let test_feature () : feature =
1664
1673
  let entity = match getp opts "entity" with Map _ as m -> m | _ -> empty_map () in
1665
1674
  (cc ctx).cl_mode <- "test";
1666
1675
  ignore (walk ~before:(fun key v _parent path ->
1667
- (if size path = 2 && ismap v && not (is_nullish key) then ignore (setprop v (Str "id") key));
1676
+ (if size path = 2 && ismap v && not (is_nullish key) then begin
1677
+ ignore (setprop v (Str "id") key);
1678
+ match getelem path (Num 0.0) with
1679
+ | Str entname ->
1680
+ (match declared_id_field ctx.c_config entname with
1681
+ | Some f -> ignore (setprop v (Str f) key)
1682
+ | None -> ())
1683
+ | _ -> ()
1684
+ end);
1668
1685
  v) entity);
1669
1686
  let mock = make_mock entity in
1670
1687
  let u = cu ctx in
@@ -26,6 +26,14 @@ sub item_envelope_key {
26
26
  return $1;
27
27
  }
28
28
 
29
+ # The entity's declared identity field (`entity.id.field`), where it names
30
+ # one other than the `id` every record already carries.
31
+ sub declared_id_field {
32
+ my ($config, $entity_name) = @_;
33
+ my $field = ProjectNameHelpers::gpath($config, ['entity', "$entity_name", 'id', 'field']);
34
+ return (defined $field && !ref($field) && '' ne $field && 'id' ne $field) ? $field : undef;
35
+ }
36
+
29
37
  our @ISA = ('ProjectNameBaseFeature');
30
38
 
31
39
  sub new {
@@ -56,6 +64,8 @@ sub init {
56
64
  if (Voxgig::Struct::islist($path) && 2 == @$path
57
65
  && Voxgig::Struct::ismap($val) && defined $key) {
58
66
  $val->{id} = $key;
67
+ my $id_field = declared_id_field($ctx->{config}, $path->[0]);
68
+ $val->{$id_field} = $key if defined $id_field;
59
69
  }
60
70
  return $val;
61
71
  });
@@ -199,6 +209,8 @@ sub init {
199
209
  my $ent = Voxgig::Struct::clone(_record($fctx->{reqdata}));
200
210
  if (Voxgig::Struct::ismap($ent)) {
201
211
  $ent->{id} = $id;
212
+ my $id_field = declared_id_field($fctx->{config}, $op->{entity});
213
+ $ent->{$id_field} = $id if defined $id_field && !defined $ent->{$id_field};
202
214
  $entmap->{"$id"} = $ent if defined $id && !ref $id;
203
215
  Voxgig::Struct::delprop($ent, '$KEY');
204
216
  my $out = Voxgig::Struct::clone($ent);
@@ -122,11 +122,11 @@ sub _send_once {
122
122
  $has_ua = 1 if lc("$k") eq 'user-agent';
123
123
  $hdrs{$k} = "$v";
124
124
  }
125
- # Default User-Agent - some CDNs block library defaults. Use a
126
- # Mozilla-shaped UA unless the caller already set one, and record it with
127
- # the headers the request sent.
125
+ # Default User-Agent - some CDNs block library defaults. Use the project's
126
+ # agent (main.kit.http.useragent, browser-shaped by default) unless the
127
+ # caller already set one, and record it with the headers the request sent.
128
128
  unless ($has_ua) {
129
- $hdrs{'User-Agent'} = 'Mozilla/5.0 (compatible; ProjectNameSDK/1.0)';
129
+ $hdrs{'User-Agent'} = 'PROJECTUSERAGENT';
130
130
  $headers->{'user-agent'} = $hdrs{'User-Agent'};
131
131
  }
132
132
 
@@ -38,6 +38,14 @@ class ProjectNameTestFeature extends ProjectNameBaseFeature
38
38
  return $m[1];
39
39
  }
40
40
 
41
+ // The entity's declared identity field (`entity.id.field`), where it names
42
+ // one other than the `id` every record already carries.
43
+ private static function declaredIdField(?array $config, mixed $entityName): ?string
44
+ {
45
+ $field = \Voxgig\Struct\Struct::getpath($config, ['entity', (string)$entityName, 'id', 'field']);
46
+ return is_string($field) && '' !== $field && 'id' !== $field ? $field : null;
47
+ }
48
+
41
49
  public function __construct()
42
50
  {
43
51
  parent::__construct();
@@ -62,9 +70,14 @@ class ProjectNameTestFeature extends ProjectNameBaseFeature
62
70
  $this->client->mode = 'test';
63
71
 
64
72
  // Ensure entity ids are correct (walk is by value: keep its result).
65
- $entity_data = \Voxgig\Struct\Struct::walk($entity_data, function ($key, $val, $parent, $path) {
73
+ $config = $ctx->config;
74
+ $entity_data = \Voxgig\Struct\Struct::walk($entity_data, function ($key, $val, $parent, $path) use ($config) {
66
75
  if (count($path) === 2 && is_array($val) && $key !== null) {
67
76
  $val['id'] = $key;
77
+ $idField = self::declaredIdField($config, $path[0]);
78
+ if (null !== $idField) {
79
+ $val[$idField] = $key;
80
+ }
68
81
  }
69
82
  return $val;
70
83
  });
@@ -299,6 +312,10 @@ class ProjectNameTestFeature extends ProjectNameBaseFeature
299
312
 
300
313
  $ent = self::record($fctx->reqdata);
301
314
  $ent['id'] = $id;
315
+ $idField = self::declaredIdField($fctx->config, $entname);
316
+ if (null !== $idField && null === ($ent[$idField] ?? null)) {
317
+ $ent[$idField] = $id;
318
+ }
302
319
  $entmap[$id] = $ent;
303
320
  $entity->data[$entname] = $entmap;
304
321
  if (is_array($ent)) unset($ent['$KEY']);
@@ -9,10 +9,10 @@ class ProjectNameFetcher
9
9
  {
10
10
  // Default User-Agent — many CDNs (notably Cloudflare) reject requests
11
11
  // with PHP's default UA (which file_get_contents doesn't even set),
12
- // returning 403 before the request reaches the origin. Set a Mozilla-
13
- // shaped UA so the SDK behaves like every other HTTP client by default.
14
- // Users can override by passing a User-Agent header in fetchdef.
15
- public const DEFAULT_USER_AGENT = 'Mozilla/5.0 (compatible; ProjectNameSDK/1.0)';
12
+ // returning 403 before the request reaches the origin. The project's
13
+ // agent (main.kit.http.useragent) is browser-shaped unless the model says
14
+ // otherwise. Users can override by passing a User-Agent header in fetchdef.
15
+ public const DEFAULT_USER_AGENT = 'PROJECTUSERAGENT';
16
16
 
17
17
  // One cURL handle per process, reset between calls rather than closed:
18
18
  // curl_reset keeps the connection cache, so the next request to the
@@ -27,6 +27,22 @@ def item_envelope_key(restf):
27
27
  return None if m is None else m.group(1)
28
28
 
29
29
 
30
+ # The entity's declared identity field (`entity.id.field`), where it names
31
+ # one other than the `id` every record already carries.
32
+ def _declared_id_field(config, entity_name):
33
+ field = vs.getpath(config, ["entity", entity_name, "id", "field"])
34
+ return field if isinstance(field, str) and field not in ("", "id") else None
35
+
36
+
37
+ def _seed_id(config, key, val, path):
38
+ if len(path) == 2 and isinstance(val, dict) and key is not None:
39
+ val["id"] = key
40
+ id_field = _declared_id_field(config, path[0])
41
+ if id_field is not None:
42
+ val[id_field] = key
43
+ return val
44
+
45
+
30
46
  # The record the mock keeps: the request data without `$body`, which only the
31
47
  # wire carries.
32
48
  def _record(reqdata):
@@ -55,10 +71,7 @@ class ProjectNameTestFeature(ProjectNameBaseFeature):
55
71
  self.client.mode = "test"
56
72
 
57
73
  # Ensure entity ids are correct.
58
- vs.walk(entity, lambda key, val, parent, path: (
59
- val.__setitem__("id", key) if len(path) == 2 and isinstance(val, dict) and key is not None else None,
60
- val
61
- )[-1])
74
+ vs.walk(entity, lambda key, val, parent, path: _seed_id(ctx.config, key, val, path))
62
75
 
63
76
  test_self = self
64
77
 
@@ -198,6 +211,9 @@ class ProjectNameTestFeature(ProjectNameBaseFeature):
198
211
  ent = vs.clone(_record(fctx.reqdata))
199
212
  if isinstance(ent, dict):
200
213
  ent["id"] = eid
214
+ id_field = _declared_id_field(fctx.config, op.entity)
215
+ if id_field is not None and ent.get(id_field) is None:
216
+ ent[id_field] = eid
201
217
  if isinstance(eid, str):
202
218
  entmap[eid] = ent
203
219
  vs.delprop(ent, "$KEY")
@@ -12,10 +12,10 @@ from projectname_sdk.core.error import ProjectNameError
12
12
 
13
13
  # Default User-Agent — many CDNs (notably Cloudflare) reject requests with
14
14
  # a library's default UA, returning 403 before the request even reaches
15
- # the origin. Set a Mozilla-shaped UA so the SDK behaves like every other
16
- # HTTP client by default. Users can still override by passing a User-Agent
17
- # header in fetchdef.
18
- _DEFAULT_USER_AGENT = "Mozilla/5.0 (compatible; ProjectNameSDK/1.0)"
15
+ # the origin. The project's agent (main.kit.http.useragent) is browser-shaped
16
+ # unless the model says otherwise. Users can still override by passing a
17
+ # User-Agent header in fetchdef.
18
+ _DEFAULT_USER_AGENT = "PROJECTUSERAGENT"
19
19
 
20
20
 
21
21
  _SESSION = None
@@ -28,6 +28,13 @@ class ProjectNameTestFeature < ProjectNameBaseFeature
28
28
  reqdata.reject { |k, _v| k == "$body" }
29
29
  end
30
30
 
31
+ # The entity's declared identity field (`entity.id.field`), where it names
32
+ # one other than the `id` every record already carries.
33
+ def self.declared_id_field(config, entity_name)
34
+ field = VoxgigStruct.getpath(config, ["entity", entity_name, "id", "field"])
35
+ field.is_a?(String) && !["", "id"].include?(field) ? field : nil
36
+ end
37
+
31
38
  def initialize
32
39
  super
33
40
  @version = "0.0.1"
@@ -48,7 +55,11 @@ class ProjectNameTestFeature < ProjectNameBaseFeature
48
55
 
49
56
  # Ensure entity ids are correct.
50
57
  VoxgigStruct.walk(entity, ->(key, val, _parent, path) {
51
- val["id"] = key if path.length == 2 && val.is_a?(Hash) && key
58
+ if path.length == 2 && val.is_a?(Hash) && key
59
+ val["id"] = key
60
+ id_field = ProjectNameTestFeature.declared_id_field(ctx.config, path[0])
61
+ val[id_field] = key unless id_field.nil?
62
+ end
52
63
  val
53
64
  })
54
65
 
@@ -175,6 +186,8 @@ class ProjectNameTestFeature < ProjectNameBaseFeature
175
186
  ent = VoxgigStruct.clone(ProjectNameTestFeature.record(fctx.reqdata))
176
187
  if ent.is_a?(Hash)
177
188
  ent["id"] = id
189
+ id_field = ProjectNameTestFeature.declared_id_field(fctx.config, op.entity)
190
+ ent[id_field] = id if !id_field.nil? && ent[id_field].nil?
178
191
  entmap[id.to_s] = ent if id.is_a?(String)
179
192
  VoxgigStruct.delprop(ent, "$KEY")
180
193
  out = VoxgigStruct.clone(ent)
@@ -3,6 +3,7 @@ require_relative 'struct/voxgig_struct'
3
3
  require 'net/http'
4
4
  require 'uri'
5
5
  require 'json'
6
+ require 'zlib'
6
7
 
7
8
  module ProjectNameUtilities
8
9
  # Started Net::HTTP connections keyed by scheme, host, port and proxy,
@@ -41,6 +42,43 @@ module ProjectNameUtilities
41
42
  nil
42
43
  end
43
44
 
45
+ # A compressed body, decoded here rather than by Net::HTTP: its inflater
46
+ # stops at the end of the first gzip member and silently drops the rest of a
47
+ # body sent as several, and it cannot read a raw deflate stream either.
48
+ def self.decode_body(body, encoding)
49
+ return body if body.nil? || body.empty?
50
+ case encoding
51
+ when "gzip", "x-gzip"
52
+ out = "".b
53
+ rest = body.b
54
+ while rest.bytesize > 2 && rest.start_with?("\x1f\x8b".b)
55
+ inflate = Zlib::Inflate.new(32 + Zlib::MAX_WBITS)
56
+ begin
57
+ out << inflate.inflate(rest)
58
+ used = inflate.total_in
59
+ ensure
60
+ inflate.close
61
+ end
62
+ break if used <= 0
63
+ rest = rest.byteslice(used..)
64
+ end
65
+ out
66
+ when "deflate"
67
+ begin
68
+ Zlib::Inflate.inflate(body)
69
+ rescue Zlib::DataError
70
+ inflate = Zlib::Inflate.new(-Zlib::MAX_WBITS)
71
+ begin
72
+ inflate.inflate(body)
73
+ ensure
74
+ inflate.close
75
+ end
76
+ end
77
+ else
78
+ body
79
+ end
80
+ end
81
+
44
82
  GETONLY_ENV = "VOXGIG_GETONLY_GUARD"
45
83
 
46
84
  # A GET-only live run refuses any other method before it is sent. The error
@@ -123,10 +161,11 @@ module ProjectNameUtilities
123
161
  request[k] = v.to_s
124
162
  end
125
163
  # Default User-Agent — Net::HTTP sets "Ruby" which some CDNs block.
126
- # Use a Mozilla-shaped UA unless the caller already set one, and record
127
- # it with the headers the request sent.
164
+ # Use the project's agent (main.kit.http.useragent, browser-shaped by
165
+ # default) unless the caller already set one, and record it with the
166
+ # headers the request sent.
128
167
  unless has_ua
129
- request['User-Agent'] = 'Mozilla/5.0 (compatible; ProjectNameSDK/1.0)'
168
+ request['User-Agent'] = 'PROJECTUSERAGENT'
130
169
  fetchdef["headers"]['user-agent'] = request['User-Agent'] if fetchdef["headers"].is_a?(Hash)
131
170
  end
132
171
  if body_str.is_a?(String)
@@ -143,7 +182,10 @@ module ProjectNameUtilities
143
182
  http = ProjectNameUtilities.http_checkout(key, uri, proxy)
144
183
  begin
145
184
  # Net::HTTP retries idempotent requests; an EOF can follow a committed POST.
146
- resp = http.request(request)
185
+ resp = http.request(request) do |r|
186
+ r.decode_content = false
187
+ r.read_body
188
+ end
147
189
  rescue StandardError
148
190
  ProjectNameUtilities.http_discard(http)
149
191
  raise
@@ -153,10 +195,18 @@ module ProjectNameUtilities
153
195
  resp_headers = {}
154
196
  resp.each_header { |k, v| resp_headers[k.downcase] = v }
155
197
 
198
+ body = resp.body
199
+ encoding = resp_headers["content-encoding"].to_s.strip.downcase
200
+ if resp_headers["content-range"].nil? && %w[gzip x-gzip deflate identity none].include?(encoding)
201
+ body = ProjectNameUtilities.decode_body(body, encoding)
202
+ resp_headers.delete("content-encoding")
203
+ resp_headers["content-length"] = body.bytesize.to_s if resp_headers.key?("content-length") && body
204
+ end
205
+
156
206
  json_body = nil
157
207
  unreadable = false
158
208
  begin
159
- json_body = JSON.parse(resp.body) if resp.body && !resp.body.strip.empty?
209
+ json_body = JSON.parse(body) if body && !body.strip.empty?
160
210
  rescue JSON::ParserError
161
211
  unreadable = true
162
212
  end
@@ -166,7 +216,7 @@ module ProjectNameUtilities
166
216
  "statusText" => resp.message,
167
217
  "headers" => resp_headers,
168
218
  "json" => -> { json_body },
169
- "body" => resp.body,
219
+ "body" => body,
170
220
  "unreadable" => unreadable,
171
221
  }, nil
172
222
  rescue StandardError => e