@reventlessdev/reventless-seed 1.0.0-alpha.1 → 1.0.0-alpha.11

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 (106) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/lib/bs/.compiler.log +2 -2
  3. package/lib/bs/.sourcedirs.json +1 -0
  4. package/lib/bs/ReventlessSeed.cmi +0 -0
  5. package/lib/bs/ReventlessSeed.cmt +0 -0
  6. package/lib/bs/ReventlessSeed.mlmap +3 -0
  7. package/lib/bs/compiler-info.json +2 -2
  8. package/lib/bs/src/Seed-ReventlessSeed.cmi +0 -0
  9. package/lib/bs/src/Seed-ReventlessSeed.cmt +0 -0
  10. package/lib/bs/src/Seed.ast +0 -0
  11. package/lib/bs/src/Seed.res +19 -0
  12. package/lib/bs/src/Seed.res.mjs +6 -0
  13. package/lib/bs/src/Seed_Client-ReventlessSeed.cmi +0 -0
  14. package/lib/bs/src/Seed_Client-ReventlessSeed.cmj +0 -0
  15. package/lib/bs/src/Seed_Client-ReventlessSeed.cmt +0 -0
  16. package/lib/bs/src/Seed_Client.ast +0 -0
  17. package/lib/bs/src/Seed_Client.res +62 -11
  18. package/lib/bs/src/Seed_Client.res.mjs +51 -5
  19. package/lib/bs/src/Seed_Connect-ReventlessSeed.cmi +0 -0
  20. package/lib/bs/src/Seed_Connect-ReventlessSeed.cmj +0 -0
  21. package/lib/bs/src/Seed_Connect-ReventlessSeed.cmt +0 -0
  22. package/lib/bs/src/Seed_Connect.ast +0 -0
  23. package/lib/bs/src/Seed_Connect.res +86 -0
  24. package/lib/bs/src/Seed_Connect.res.mjs +62 -0
  25. package/lib/bs/src/Seed_Prompt-ReventlessSeed.cmi +0 -0
  26. package/lib/bs/src/Seed_Prompt-ReventlessSeed.cmj +0 -0
  27. package/lib/bs/src/Seed_Prompt-ReventlessSeed.cmt +0 -0
  28. package/lib/bs/src/Seed_Prompt.ast +0 -0
  29. package/lib/bs/src/Seed_Prompt.res +178 -0
  30. package/lib/bs/src/Seed_Prompt.res.mjs +172 -0
  31. package/lib/bs/src/Seed_Random-ReventlessSeed.cmt +0 -0
  32. package/lib/bs/src/Seed_Runner-ReventlessSeed.cmi +0 -0
  33. package/lib/bs/src/Seed_Runner-ReventlessSeed.cmj +0 -0
  34. package/lib/bs/src/Seed_Runner-ReventlessSeed.cmt +0 -0
  35. package/lib/bs/src/Seed_Runner.ast +0 -0
  36. package/lib/bs/src/Seed_Runner.res +122 -6
  37. package/lib/bs/src/Seed_Runner.res.mjs +87 -1
  38. package/lib/bs/src/Seed_Types-ReventlessSeed.cmt +0 -0
  39. package/lib/bs/src/Seed_Upload-ReventlessSeed.cmi +0 -0
  40. package/lib/bs/src/Seed_Upload-ReventlessSeed.cmj +0 -0
  41. package/lib/bs/src/Seed_Upload-ReventlessSeed.cmt +0 -0
  42. package/lib/bs/src/Seed_Upload.ast +0 -0
  43. package/lib/bs/src/Seed_Upload.res +40 -42
  44. package/lib/bs/src/Seed_Upload.res.mjs +65 -69
  45. package/lib/bs/tests/Seed_RandomTest-ReventlessSeed.cmi +0 -0
  46. package/lib/bs/tests/Seed_RandomTest-ReventlessSeed.cmj +0 -0
  47. package/lib/bs/tests/Seed_RandomTest-ReventlessSeed.cmt +0 -0
  48. package/lib/bs/tests/Seed_RandomTest.ast +0 -0
  49. package/lib/bs/tests/Seed_RandomTest.res +160 -0
  50. package/lib/bs/tests/Seed_RandomTest.res.mjs +208 -0
  51. package/lib/ocaml/.compiler.log +2 -2
  52. package/lib/ocaml/ReventlessSeed.cmi +0 -0
  53. package/lib/ocaml/ReventlessSeed.cmt +0 -0
  54. package/lib/ocaml/ReventlessSeed.mlmap +3 -0
  55. package/lib/ocaml/Seed-ReventlessSeed.cmi +0 -0
  56. package/lib/ocaml/Seed-ReventlessSeed.cmt +0 -0
  57. package/lib/ocaml/Seed.ast +0 -0
  58. package/lib/ocaml/Seed.res +19 -0
  59. package/lib/ocaml/Seed_Client-ReventlessSeed.cmi +0 -0
  60. package/lib/ocaml/Seed_Client-ReventlessSeed.cmj +0 -0
  61. package/lib/ocaml/Seed_Client-ReventlessSeed.cmt +0 -0
  62. package/lib/ocaml/Seed_Client.ast +0 -0
  63. package/lib/ocaml/Seed_Client.res +62 -11
  64. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmi +0 -0
  65. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmj +0 -0
  66. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmt +0 -0
  67. package/lib/ocaml/Seed_Connect.ast +0 -0
  68. package/lib/ocaml/Seed_Connect.res +86 -0
  69. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmi +0 -0
  70. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmj +0 -0
  71. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmt +0 -0
  72. package/lib/ocaml/Seed_Prompt.ast +0 -0
  73. package/lib/ocaml/Seed_Prompt.res +178 -0
  74. package/lib/ocaml/Seed_Random-ReventlessSeed.cmt +0 -0
  75. package/lib/ocaml/Seed_RandomTest-ReventlessSeed.cmi +0 -0
  76. package/lib/ocaml/Seed_RandomTest-ReventlessSeed.cmj +0 -0
  77. package/lib/ocaml/Seed_RandomTest-ReventlessSeed.cmt +0 -0
  78. package/lib/ocaml/Seed_RandomTest.ast +0 -0
  79. package/lib/ocaml/Seed_RandomTest.res +160 -0
  80. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmi +0 -0
  81. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmj +0 -0
  82. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmt +0 -0
  83. package/lib/ocaml/Seed_Runner.ast +0 -0
  84. package/lib/ocaml/Seed_Runner.res +122 -6
  85. package/lib/ocaml/Seed_Types-ReventlessSeed.cmt +0 -0
  86. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmi +0 -0
  87. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmj +0 -0
  88. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmt +0 -0
  89. package/lib/ocaml/Seed_Upload.ast +0 -0
  90. package/lib/ocaml/Seed_Upload.res +40 -42
  91. package/package.json +6 -2
  92. package/rescript.json +9 -1
  93. package/src/Seed.res +19 -0
  94. package/src/Seed.res.mjs +6 -0
  95. package/src/Seed_Client.res +62 -11
  96. package/src/Seed_Client.res.mjs +51 -5
  97. package/src/Seed_Connect.res +86 -0
  98. package/src/Seed_Connect.res.mjs +62 -0
  99. package/src/Seed_Prompt.res +178 -0
  100. package/src/Seed_Prompt.res.mjs +172 -0
  101. package/src/Seed_Runner.res +122 -6
  102. package/src/Seed_Runner.res.mjs +87 -1
  103. package/src/Seed_Upload.res +40 -42
  104. package/src/Seed_Upload.res.mjs +65 -69
  105. package/tests/Seed_RandomTest.res +160 -0
  106. package/tests/Seed_RandomTest.res.mjs +208 -0
@@ -1,2 +1,2 @@
1
- #Start(1785055307106)
2
- #Done(1785055311634)
1
+ #Start(1786453304385)
2
+ #Done(1786453304425)
Binary file
Binary file
@@ -1,7 +1,10 @@
1
1
  randjbuildsystem
2
2
  Seed
3
3
  Seed_Client
4
+ Seed_Connect
5
+ Seed_Prompt
4
6
  Seed_Random
7
+ Seed_RandomTest
5
8
  Seed_Runner
6
9
  Seed_Types
7
10
  Seed_Upload
Binary file
Binary file
Binary file
@@ -9,9 +9,28 @@ module Random = Seed_Random
9
9
  module Client = Seed_Client
10
10
  module Runner = Seed_Runner
11
11
  module Upload = Seed_Upload
12
+ module Prompt = Seed_Prompt
13
+ module Connect = Seed_Connect
12
14
 
13
15
  exception Failed = Seed_Types.Failed
14
16
 
17
+ // A live target a data set seeds against: an authenticated client, whether uploads
18
+ // are skipped this run, and a label. Uploads mint through the domain API's
19
+ // `Upload_Presign` mutation on the client (route B), so no upload endpoint is carried.
20
+ type connection = Seed_Connect.connection = {
21
+ client: Seed_Client.t,
22
+ uploadsSkipped: bool,
23
+ label: string,
24
+ }
25
+
26
+ // A named, seedable data set. `seed` owns everything domain-specific.
27
+ type dataSet = Seed_Runner.dataSet = {
28
+ name: string,
29
+ label: string,
30
+ seed: connection => promise<unit>,
31
+ probeViews?: array<string>,
32
+ }
33
+
15
34
  type rec value = Seed_Types.value =
16
35
  | String(string)
17
36
  | Id(string)
Binary file
@@ -27,9 +27,12 @@ let sleep = (ms: int): promise<unit> => Promise.make((resolve, _) => setTimeout(
27
27
 
28
28
  type config = {
29
29
  endpoint: string,
30
- loginEndpoint: string,
31
- username: string,
32
- password: string,
30
+ // Present only for the `login` flow (a platform that mints tokens over HTTP,
31
+ // e.g. the local dev `/__inmemory/login`). Omit when the bearer is supplied
32
+ // out-of-band via `useToken` (e.g. a Cognito id token minted by the caller).
33
+ loginEndpoint?: string,
34
+ username?: string,
35
+ password?: string,
33
36
  }
34
37
 
35
38
  type t = {config: config, mutable token: option<string>}
@@ -40,6 +43,15 @@ let make = (~config: config): t => {config, token: None}
40
43
  Seed.Upload) can authenticate side-channel requests with the same identity. */
41
44
  let currentToken = (t: t): option<string> => t.token
42
45
 
46
+ /** The GraphQL endpoint this client targets — so `Seed.Upload` can resolve a
47
+ relative presigned `uploadUrl` against the same origin. */
48
+ let endpoint = (t: t): string => t.config.endpoint
49
+
50
+ /** Injects a bearer obtained out-of-band (e.g. a Cognito id token), instead of
51
+ minting one via `login`. Provider-agnostic: the harness only cares that the
52
+ token is a valid bearer for `endpoint`. */
53
+ let useToken = (t: t, token: string): unit => t.token = Some(token)
54
+
43
55
  // ── JSON helpers ────────────────────────────────────────────────────────────
44
56
 
45
57
  let field = (json: JSON.t, key: string): option<JSON.t> =>
@@ -61,28 +73,31 @@ let nodeString = (node: JSON.t, key: string): option<string> =>
61
73
  // ── Requests ────────────────────────────────────────────────────────────────
62
74
 
63
75
  let login = async (t: t): unit => {
76
+ let loginEndpoint = switch t.config.loginEndpoint {
77
+ | Some(e) => e
78
+ | None => throw(Failed("login: no loginEndpoint configured — supply one or call useToken"))
79
+ }
80
+ let username = t.config.username->Option.getOr("")
81
+ let password = t.config.password->Option.getOr("")
64
82
  let body = JSON.stringify(
65
83
  JSON.Encode.object(
66
84
  Dict.fromArray([
67
- ("username", JSON.Encode.string(t.config.username)),
68
- ("password", JSON.Encode.string(t.config.password)),
85
+ ("username", JSON.Encode.string(username)),
86
+ ("password", JSON.Encode.string(password)),
69
87
  ]),
70
88
  ),
71
89
  )
72
90
  let res = try await fetch(
73
- t.config.loginEndpoint,
91
+ loginEndpoint,
74
92
  {method: "POST", headers: Dict.fromArray([("content-type", "application/json")]), body},
75
93
  ) catch {
76
- | _ =>
77
- throw(
78
- Failed(`login: cannot reach ${t.config.loginEndpoint} — is the platform running?`),
79
- )
94
+ | _ => throw(Failed(`login: cannot reach ${loginEndpoint} — is the platform running?`))
80
95
  }
81
96
  if !(res->responseOk) {
82
97
  let detail = await res->responseText
83
98
  throw(
84
99
  Failed(
85
- `login as "${t.config.username}" failed with HTTP ${(res->responseStatus)
100
+ `login as "${username}" failed with HTTP ${(res->responseStatus)
86
101
  ->Int.toString}: ${detail}`,
87
102
  ),
88
103
  )
@@ -205,6 +220,42 @@ let queryAllNodes = async (t: t, ~field as fieldName: string, ~selection: string
205
220
  let countNodes = async (t: t, ~field: string): int =>
206
221
  (await queryAllNodes(t, ~field, ~selection="id"))->Array.length
207
222
 
223
+ /**
224
+ * Polls a connection field until the collected nodes satisfy `satisfied`, or the
225
+ * timeout elapses. Read models are eventually consistent: a view queried the
226
+ * instant after the writes that feed it can still read empty or partial (a
227
+ * DynamoDB connection scan is eventually consistent by default, and the write and
228
+ * read-back can land on different replicas), so a cross-check that asserts on a
229
+ * single immediate read races the projection. Same rationale as `waitForIds`,
230
+ * for the "observe the whole connection" case rather than a fixed id set.
231
+ *
232
+ * On timeout, throws `Failed(onTimeout(finalNodes))` so the caller can report
233
+ * what the view actually settled on — distinguishing a still-empty view from a
234
+ * genuine count mismatch — instead of a bare assertion.
235
+ */
236
+ let queryAllNodesUntil = async (
237
+ t: t,
238
+ ~field: string,
239
+ ~selection: string,
240
+ ~satisfied: array<JSON.t> => bool,
241
+ ~onTimeout: array<JSON.t> => string,
242
+ ~timeoutMs: int=60000,
243
+ ): array<JSON.t> => {
244
+ let deadline = nowMs() +. Int.toFloat(timeoutMs)
245
+ let result = ref(None)
246
+ while result.contents == None {
247
+ let nodes = await queryAllNodes(t, ~field, ~selection)
248
+ if satisfied(nodes) {
249
+ result := Some(nodes)
250
+ } else if nowMs() > deadline {
251
+ throw(Failed(onTimeout(nodes)))
252
+ } else {
253
+ await sleep(500)
254
+ }
255
+ }
256
+ result.contents->Option.getOr([])
257
+ }
258
+
208
259
  /**
209
260
  * Polls a `<View>ByIds` field until every id is present.
210
261
  *
Binary file
@@ -0,0 +1,86 @@
1
+ // Turns endpoints plus a login function into a ready `connection`.
2
+ //
3
+ // A connection is what a data set seeds against: an authenticated GraphQL
4
+ // client, the deployment's upload endpoints (empty when it serves no uploads),
5
+ // and a human label for the target. `make` is provider-agnostic — it prompts for
6
+ // credentials, calls the supplied `login` to obtain a bearer, and wires it onto
7
+ // the client via `useToken`. Where the bearer comes from (a local `/login`
8
+ // round-trip, a Cognito id token) is the caller's concern.
9
+
10
+ open Seed_Types
11
+
12
+ // Under route B the client mints uploads through the domain API's `Upload_Presign`
13
+ // mutation (authenticated by the same bearer as commands), so a connection needs no
14
+ // upload endpoint — just the authenticated client and whether uploads are skipped this
15
+ // run (`SEED_SKIP_UPLOADS`). Which store an asset uploads into is the caller's `~store`.
16
+ type connection = {
17
+ client: Seed_Client.t,
18
+ uploadsSkipped: bool,
19
+ label: string,
20
+ }
21
+
22
+ /**
23
+ * Prompts for credentials, calls `login` to mint a bearer, and returns a
24
+ * connection with that bearer already applied. `login` returns the bearer so a
25
+ * single `useToken` path serves every provider.
26
+ */
27
+ let make = async (
28
+ ~label: string,
29
+ ~endpoint: string,
30
+ ~login: (~username: string, ~password: string) => promise<string>,
31
+ ~localDefaults: bool=false,
32
+ ): connection => {
33
+ // `SEED_SKIP_UPLOADS` forces the upload phase to no-op — seed domain data fast, or
34
+ // skip a broken/absent upload path without editing the data set. The data set reads
35
+ // `connection.uploadsSkipped` and reports the skip.
36
+ let uploadsSkipped = Seed_Upload.uploadsSkipped()
37
+ let (username, password) = await Seed_Prompt.credentials(~localDefaults)
38
+ let token = await login(~username, ~password)
39
+ let client = Seed_Client.make(~config={endpoint: endpoint})
40
+ client->Seed_Client.useToken(token)
41
+ {client, uploadsSkipped, label}
42
+ }
43
+
44
+ /**
45
+ * A login function backed by an HTTP login endpoint (the local dev
46
+ * `/__inmemory/login` shape: POST `{username, password}` → `{token}`). Reuses
47
+ * `Seed_Client.login` but hands the token back for `useToken`.
48
+ */
49
+ let viaLoginEndpoint = (~loginEndpoint: string) => async (
50
+ ~username: string,
51
+ ~password: string,
52
+ ): string => {
53
+ let client = Seed_Client.make(
54
+ ~config={endpoint: loginEndpoint, loginEndpoint, username, password},
55
+ )
56
+ await Seed_Client.login(client)
57
+ switch Seed_Client.currentToken(client) {
58
+ | Some(token) => token
59
+ | None => throw(Failed(`login at ${loginEndpoint} returned no token`))
60
+ }
61
+ }
62
+
63
+ let envOr = (key: string, fallback: string): string =>
64
+ Seed_Prompt.envValue(key)->Option.getOr(fallback)
65
+
66
+ /**
67
+ * A ready `connect` thunk for the local dev platform, with the localhost
68
+ * defaults baked in and overridable per endpoint (arg, then env var, then
69
+ * default). Empty input at the credential prompt falls back to `admin`/`admin`.
70
+ *
71
+ * No upload endpoint: uploads mint through the domain API's `Upload_Presign` mutation
72
+ * on the same `graphql` endpoint, with the store passed per asset.
73
+ */
74
+ let local = (~graphql=?, ~login=?, ()): (unit => promise<connection>) => {
75
+ let endpoint =
76
+ graphql->Option.getOr(envOr("REVENTLESS_GRAPHQL_ENDPOINT", "http://localhost:4000/graphql"))
77
+ let loginEndpoint =
78
+ login->Option.getOr(envOr("REVENTLESS_LOGIN_ENDPOINT", "http://localhost:4000/__inmemory/login"))
79
+ () =>
80
+ make(
81
+ ~label="local",
82
+ ~endpoint,
83
+ ~login=viaLoginEndpoint(~loginEndpoint),
84
+ ~localDefaults=true,
85
+ )
86
+ }
Binary file
@@ -0,0 +1,178 @@
1
+ // One shared readline interface for every interactive prompt in a seed run.
2
+ //
3
+ // The reason this module exists: creating and closing a fresh `readline`
4
+ // interface per prompt leaves NodeProcess.stdin paused after the first `close`, so the
5
+ // second prompt (password after username) never fires and the run hangs. A
6
+ // single interface, created lazily and closed exactly once, avoids that — and a
7
+ // `muted` gate on its output lets password entry reuse the same interface
8
+ // instead of opening a second one just to suppress the echo.
9
+ //
10
+ // Node bindings are declared here as typed externals; this package is
11
+ // stdlib-only, so no `%raw`.
12
+
13
+ open Seed_Types
14
+
15
+ // ── Node bindings ─────────────────────────────────────────────────────────────
16
+
17
+ type rl
18
+ type rlOptions = {input: NodeProcess.stream, output: NodeProcess.stream, terminal?: bool}
19
+ @module("node:readline") external createInterface: rlOptions => rl = "createInterface"
20
+ @send external question: (rl, string, string => unit) => unit = "question"
21
+ @send external closeRl: rl => unit = "close"
22
+ @set external setWriteToOutput: (rl, string => unit) => unit = "_writeToOutput"
23
+
24
+ // ── Shared interface ──────────────────────────────────────────────────────────
25
+
26
+ // Created on first use, closed once via `close`. `muted` gates the echo so the
27
+ // same interface serves both visible and hidden prompts.
28
+ let rlRef: ref<option<rl>> = ref(None)
29
+ let muted = ref(false)
30
+
31
+ let iface = (): rl =>
32
+ switch rlRef.contents {
33
+ | Some(rl) => rl
34
+ | None =>
35
+ let rl = createInterface({input: NodeProcess.stdin, output: NodeProcess.stdout, terminal: true})
36
+ rl->setWriteToOutput(s =>
37
+ if !muted.contents {
38
+ NodeProcess.stdout->NodeProcess.write(s)
39
+ }
40
+ )
41
+ rlRef := Some(rl)
42
+ rl
43
+ }
44
+
45
+ let close = (): unit =>
46
+ switch rlRef.contents {
47
+ | Some(rl) =>
48
+ rl->closeRl
49
+ rlRef := None
50
+ // Closing the interface is not enough: a terminal-mode readline leaves
51
+ // NodeProcess.stdin resumed and reffed, which keeps the event loop alive so the CLI
52
+ // never exits after seeding. Release it explicitly.
53
+ NodeProcess.stdin->NodeProcess.pause
54
+ NodeProcess.stdin->NodeProcess.unref
55
+ | None => ()
56
+ }
57
+
58
+ // ── Env + TTY ─────────────────────────────────────────────────────────────────
59
+
60
+ let envValue = (key: string): option<string> =>
61
+ switch NodeProcess.env->Dict.get(key) {
62
+ | Some(v) if v->String.trim != "" => Some(v->String.trim)
63
+ | _ => None
64
+ }
65
+
66
+ let requireTty = (): unit =>
67
+ if !(NodeProcess.stdin->NodeProcess.isTTY->Option.getOr(false)) {
68
+ throw(
69
+ Failed(
70
+ "no TTY for an interactive prompt — set the documented SEED_* / REVENTLESS_DEMO_* " ++
71
+ "env vars to run non-interactively.",
72
+ ),
73
+ )
74
+ }
75
+
76
+ // ── Prompts ───────────────────────────────────────────────────────────────────
77
+
78
+ let ask = (query: string): promise<string> =>
79
+ Promise.make((resolve, _) => {
80
+ let rl = iface()
81
+ rl->question(query, answer => resolve(answer->String.trim))
82
+ })
83
+
84
+ // Same interface, echo suppressed for the keystrokes. `question` writes the
85
+ // prompt synchronously first (while unmuted), then muting is switched on so only
86
+ // the typed characters are hidden — the canonical readline recipe, which keeps
87
+ // the line editor's cursor state consistent (a manual write + empty `question`
88
+ // left some terminals unable to read the next line).
89
+ let askHidden = (query: string): promise<string> =>
90
+ Promise.make((resolve, _) => {
91
+ let rl = iface()
92
+ rl->question(query, answer => {
93
+ muted := false
94
+ NodeProcess.stdout->NodeProcess.write("\n")
95
+ resolve(answer)
96
+ })
97
+ muted := true
98
+ })
99
+
100
+ /**
101
+ * Chooses one of `options` (a label paired with the value it selects).
102
+ *
103
+ * Auto-returns when there is a single option, so a lone data set or stack needs
104
+ * no keypress. `env` (e.g. `SEED_SET`) preselects by matching label or 1-based
105
+ * index, so CI runs without a TTY. Otherwise it prints a numbered menu.
106
+ */
107
+ let select = async (
108
+ ~title: string,
109
+ ~options: array<(string, 'a)>,
110
+ ~env=?,
111
+ ): 'a =>
112
+ switch options {
113
+ | [(_, only)] => only
114
+ | _ =>
115
+ let fromEnv =
116
+ env
117
+ ->Option.flatMap(envValue)
118
+ ->Option.flatMap(v =>
119
+ switch options->Array.findIndex(((label, _)) => label == v) {
120
+ | -1 =>
121
+ switch Int.fromString(v) {
122
+ | Some(n) if n >= 1 && n <= options->Array.length => options->Array.get(n - 1)
123
+ | _ => None
124
+ }
125
+ | i => options->Array.get(i)
126
+ }
127
+ )
128
+ switch fromEnv {
129
+ | Some((_, value)) => value
130
+ | None =>
131
+ requireTty()
132
+ Console.log("")
133
+ Console.log(title)
134
+ Console.log("")
135
+ options->Array.forEachWithIndex(((label, _), i) =>
136
+ Console.log(` ${(i + 1)->Int.toString}) ${label}`)
137
+ )
138
+ let rec pick = async (): 'a => {
139
+ let answer = await ask(`\nSelect [1-${(options->Array.length)->Int.toString}]: `)
140
+ switch Int.fromString(answer) {
141
+ | Some(n) if n >= 1 && n <= options->Array.length =>
142
+ let (_, value) = options->Array.getUnsafe(n - 1)
143
+ value
144
+ | _ =>
145
+ Console.log(" Not a valid choice.")
146
+ await pick()
147
+ }
148
+ }
149
+ await pick()
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Prompts for a username (visible) and password (echo muted).
155
+ *
156
+ * `REVENTLESS_DEMO_USER` / `REVENTLESS_DEMO_PASSWORD` skip the prompts. With
157
+ * `localDefaults`, empty input falls back to `admin`/`admin` — the dev login.
158
+ */
159
+ let credentials = async (~localDefaults: bool=false): (string, string) => {
160
+ let username = switch envValue("REVENTLESS_DEMO_USER") {
161
+ | Some(u) => u
162
+ | None =>
163
+ requireTty()
164
+ let entered = await ask(localDefaults ? "Username [admin]: " : "Username: ")
165
+ entered == "" && localDefaults ? "admin" : entered
166
+ }
167
+ let password = switch envValue("REVENTLESS_DEMO_PASSWORD") {
168
+ | Some(p) => p
169
+ | None =>
170
+ requireTty()
171
+ let entered = await askHidden(localDefaults ? "Password [admin]: " : "Password: ")
172
+ entered == "" && localDefaults ? "admin" : entered
173
+ }
174
+ if username == "" || password == "" {
175
+ throw(Failed("username and password are required."))
176
+ }
177
+ (username, password)
178
+ }
Binary file
@@ -0,0 +1,160 @@
1
+ open JestGlobals
2
+
3
+ // `Seed_Random` exists so that two seed runs against a fresh store produce the
4
+ // same data — that is what makes a seeded store usable as a screenshot baseline
5
+ // or a comparison target. Its correctness is therefore not "looks random" but
6
+ // "repeats exactly, and stays inside the bounds it advertises".
7
+ //
8
+ // The suite is written around that: every case below fails for a generator that
9
+ // is subtly non-reproducible or that walks out of its range, and none of them
10
+ // would notice a change of algorithm that kept both properties.
11
+
12
+ describe("Seed_Random:", () => {
13
+ let take = (~seed, ~n) => {
14
+ let r = Seed_Random.make(~seed)
15
+ Array.make(~length=n, 0.0)->Array.map(_ => Seed_Random.float(r))
16
+ }
17
+
18
+ describe("reproducibility — the reason this module exists:", () => {
19
+ testSync("the same seed replays the same sequence", () =>
20
+ expect(take(~seed=42, ~n=25))->toEqual(take(~seed=42, ~n=25))
21
+ )
22
+
23
+ // Without this, a generator that returned a constant would satisfy the
24
+ // case above and nothing else in the suite would catch it.
25
+ testSync("different seeds diverge", () =>
26
+ expect(take(~seed=42, ~n=25) == take(~seed=43, ~n=25))->toBe(false)
27
+ )
28
+
29
+ testSync("a fresh generator does not continue the previous one", () => {
30
+ let r = Seed_Random.make(~seed=7)
31
+ let first = Seed_Random.float(r)
32
+ let _ = Seed_Random.float(r)
33
+ expect(Seed_Random.float(Seed_Random.make(~seed=7)))->toEqual(first)
34
+ })
35
+ })
36
+
37
+ describe("float stays a unit interval:", () => {
38
+ // mulberry32's last step is a signed 32-bit value folded back to unsigned.
39
+ // Get that fold wrong and roughly half the draws come out negative, which
40
+ // every consumer below (int, pick, sampleWeighted) silently mis-scales.
41
+ testSync("every draw is in [0, 1)", () =>
42
+ expect(take(~seed=99, ~n=500)->Array.every(f => f >= 0.0 && f < 1.0))->toBe(true)
43
+ )
44
+
45
+ testSync("and the draws are not all the same value", () => {
46
+ let draws = take(~seed=99, ~n=100)
47
+ expect(draws->Array.some(f => f != draws->Array.getUnsafe(0)))->toBe(true)
48
+ })
49
+ })
50
+
51
+ describe("int is inclusive on both ends, as documented:", () => {
52
+ let draws = (~min, ~max, ~n) => {
53
+ let r = Seed_Random.make(~seed=5)
54
+ Array.make(~length=n, 0)->Array.map(_ => Seed_Random.int(r, ~min, ~max))
55
+ }
56
+
57
+ testSync("never escapes the range", () =>
58
+ expect(draws(~min=3, ~max=7, ~n=500)->Array.every(i => i >= 3 && i <= 7))->toBe(true)
59
+ )
60
+
61
+ // The documented contract is "inclusive on both ends"; an off-by-one in the
62
+ // `max - min + 1` scaling shows up as a bound that is never drawn.
63
+ testSync("reaches both bounds", () => {
64
+ let d = draws(~min=3, ~max=7, ~n=500)
65
+ expect((d->Array.includes(3), d->Array.includes(7)))->toEqual((true, true))
66
+ })
67
+
68
+ testSync("a single-value range is that value", () =>
69
+ expect(draws(~min=4, ~max=4, ~n=10)->Array.every(i => i == 4))->toBe(true)
70
+ )
71
+ })
72
+
73
+ describe("pick:", () => {
74
+ testSync("returns None for an empty array", () =>
75
+ expect(Seed_Random.make(~seed=1)->Seed_Random.pick([]))->toEqual(None)
76
+ )
77
+
78
+ testSync("always lands on a member", () => {
79
+ let r = Seed_Random.make(~seed=2)
80
+ let xs = ["a", "b", "c", "d"]
81
+ let hits = Array.make(~length=200, "")->Array.map(_ =>
82
+ r->Seed_Random.pickOr(~fallback="MISS", xs)
83
+ )
84
+ expect(hits->Array.every(h => xs->Array.includes(h)))->toBe(true)
85
+ })
86
+
87
+ testSync("pickOr falls back only when there is nothing to pick", () =>
88
+ expect(Seed_Random.make(~seed=3)->Seed_Random.pickOr(~fallback="fallback", []))->toBe(
89
+ "fallback",
90
+ )
91
+ )
92
+ })
93
+
94
+ describe("sampleWeighted is without replacement:", () => {
95
+ let equal = xs => xs->Array.map(x => (x, 1.0))
96
+
97
+ // The documented shuffle use: equal weights, count = length. If sampling
98
+ // ever replaced instead of removing, duplicates would appear here.
99
+ testSync("count = length yields a permutation, not a multiset", () => {
100
+ let xs = ["a", "b", "c", "d", "e"]
101
+ let out = Seed_Random.make(~seed=11)->Seed_Random.sampleWeighted(equal(xs), ~count=5)
102
+ let sorted = out->Array.toSorted(String.compare)
103
+ expect((out->Array.length, sorted))->toEqual((5, ["a", "b", "c", "d", "e"]))
104
+ })
105
+
106
+ testSync("count < length returns exactly count distinct items", () => {
107
+ let xs = ["a", "b", "c", "d", "e"]
108
+ let out = Seed_Random.make(~seed=12)->Seed_Random.sampleWeighted(equal(xs), ~count=3)
109
+ let distinct = Set.fromArray(out)->Set.size
110
+ expect((out->Array.length, distinct))->toEqual((3, 3))
111
+ })
112
+
113
+ testSync("count > length clamps to the pool", () =>
114
+ expect(
115
+ Seed_Random.make(~seed=13)
116
+ ->Seed_Random.sampleWeighted(equal(["a", "b"]), ~count=99)
117
+ ->Array.length,
118
+ )->toBe(2)
119
+ )
120
+
121
+ testSync("a zero-weight entry is never chosen while others remain", () => {
122
+ let out =
123
+ Seed_Random.make(~seed=14)->Seed_Random.sampleWeighted(
124
+ [("never", 0.0), ("a", 1.0), ("b", 1.0)],
125
+ ~count=2,
126
+ )
127
+ expect(out->Array.includes("never"))->toBe(false)
128
+ })
129
+
130
+ testSync("is reproducible for a given seed", () => {
131
+ let run = () =>
132
+ Seed_Random.make(~seed=15)->Seed_Random.sampleWeighted(
133
+ equal(["a", "b", "c", "d", "e", "f"]),
134
+ ~count=4,
135
+ )
136
+ expect(run())->toEqual(run())
137
+ })
138
+ })
139
+
140
+ describe("zipfWeights skews toward the head:", () => {
141
+ let weights = Seed_Random.zipfWeights(["a", "b", "c", "d", "e"], ~exponent=1.1)
142
+
143
+ testSync("keeps every item, in order", () =>
144
+ expect(weights->Array.map(((item, _)) => item))->toEqual(["a", "b", "c", "d", "e"])
145
+ )
146
+
147
+ testSync("weight decreases monotonically with rank", () => {
148
+ let ws = weights->Array.map(((_, w)) => w)
149
+ let decreasing =
150
+ ws->Array.everyWithIndex((w, i) => i == 0 || w < ws->Array.getUnsafe(i - 1))
151
+ expect(decreasing)->toBe(true)
152
+ })
153
+
154
+ testSync("the leader is clear — first outweighs last several times over", () => {
155
+ let first = weights->Array.get(0)->Option.mapOr(0.0, ((_, w)) => w)
156
+ let last = weights->Array.get(4)->Option.mapOr(0.0, ((_, w)) => w)
157
+ expect(first > last *. 3.0)->toBe(true)
158
+ })
159
+ })
160
+ })
Binary file