@reventlessdev/reventless-seed 1.0.0-alpha.2 → 1.0.0-alpha.20

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 (158) hide show
  1. package/CHANGELOG.md +137 -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 +5 -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 +6 -3
  12. package/lib/bs/src/Seed.res.mjs +3 -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 +228 -15
  18. package/lib/bs/src/Seed_Client.res.mjs +196 -23
  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 +27 -18
  24. package/lib/bs/src/Seed_Connect.res.mjs +10 -6
  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 +110 -35
  30. package/lib/bs/src/Seed_Prompt.res.mjs +73 -8
  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 +38 -7
  37. package/lib/bs/src/Seed_Runner.res.mjs +19 -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/src/Seed_Users-ReventlessSeed.cmi +0 -0
  46. package/lib/bs/src/Seed_Users-ReventlessSeed.cmj +0 -0
  47. package/lib/bs/src/Seed_Users-ReventlessSeed.cmt +0 -0
  48. package/lib/bs/src/Seed_Users.ast +0 -0
  49. package/lib/bs/src/Seed_Users.res +80 -0
  50. package/lib/bs/src/Seed_Users.res.mjs +90 -0
  51. package/lib/bs/tests/Seed_ClientTest-ReventlessSeed.cmi +0 -0
  52. package/lib/bs/tests/Seed_ClientTest-ReventlessSeed.cmj +0 -0
  53. package/lib/bs/tests/Seed_ClientTest-ReventlessSeed.cmt +0 -0
  54. package/lib/bs/tests/Seed_ClientTest.ast +0 -0
  55. package/lib/bs/tests/Seed_ClientTest.res +157 -0
  56. package/lib/bs/tests/Seed_ClientTest.res.mjs +167 -0
  57. package/lib/bs/tests/Seed_PromptTest-ReventlessSeed.cmi +0 -0
  58. package/lib/bs/tests/Seed_PromptTest-ReventlessSeed.cmj +0 -0
  59. package/lib/bs/tests/Seed_PromptTest-ReventlessSeed.cmt +0 -0
  60. package/lib/bs/tests/Seed_PromptTest.ast +0 -0
  61. package/lib/bs/tests/Seed_PromptTest.res +59 -0
  62. package/lib/bs/tests/Seed_PromptTest.res.mjs +63 -0
  63. package/lib/bs/tests/Seed_RandomTest-ReventlessSeed.cmi +0 -0
  64. package/lib/bs/tests/Seed_RandomTest-ReventlessSeed.cmj +0 -0
  65. package/lib/bs/tests/Seed_RandomTest-ReventlessSeed.cmt +0 -0
  66. package/lib/bs/tests/Seed_RandomTest.ast +0 -0
  67. package/lib/bs/tests/Seed_RandomTest.res +160 -0
  68. package/lib/bs/tests/Seed_RandomTest.res.mjs +208 -0
  69. package/lib/bs/tests/Seed_UsersTest-ReventlessSeed.cmi +0 -0
  70. package/lib/bs/tests/Seed_UsersTest-ReventlessSeed.cmj +0 -0
  71. package/lib/bs/tests/Seed_UsersTest-ReventlessSeed.cmt +0 -0
  72. package/lib/bs/tests/Seed_UsersTest.ast +0 -0
  73. package/lib/bs/tests/Seed_UsersTest.res +92 -0
  74. package/lib/bs/tests/Seed_UsersTest.res.mjs +95 -0
  75. package/lib/ocaml/.compiler.log +2 -2
  76. package/lib/ocaml/ReventlessSeed.cmi +0 -0
  77. package/lib/ocaml/ReventlessSeed.cmt +0 -0
  78. package/lib/ocaml/ReventlessSeed.mlmap +5 -0
  79. package/lib/ocaml/Seed-ReventlessSeed.cmi +0 -0
  80. package/lib/ocaml/Seed-ReventlessSeed.cmt +0 -0
  81. package/lib/ocaml/Seed.ast +0 -0
  82. package/lib/ocaml/Seed.res +6 -3
  83. package/lib/ocaml/Seed_Client-ReventlessSeed.cmi +0 -0
  84. package/lib/ocaml/Seed_Client-ReventlessSeed.cmj +0 -0
  85. package/lib/ocaml/Seed_Client-ReventlessSeed.cmt +0 -0
  86. package/lib/ocaml/Seed_Client.ast +0 -0
  87. package/lib/ocaml/Seed_Client.res +228 -15
  88. package/lib/ocaml/Seed_ClientTest-ReventlessSeed.cmi +0 -0
  89. package/lib/ocaml/Seed_ClientTest-ReventlessSeed.cmj +0 -0
  90. package/lib/ocaml/Seed_ClientTest-ReventlessSeed.cmt +0 -0
  91. package/lib/ocaml/Seed_ClientTest.ast +0 -0
  92. package/lib/ocaml/Seed_ClientTest.res +157 -0
  93. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmi +0 -0
  94. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmj +0 -0
  95. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmt +0 -0
  96. package/lib/ocaml/Seed_Connect.ast +0 -0
  97. package/lib/ocaml/Seed_Connect.res +27 -18
  98. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmi +0 -0
  99. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmj +0 -0
  100. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmt +0 -0
  101. package/lib/ocaml/Seed_Prompt.ast +0 -0
  102. package/lib/ocaml/Seed_Prompt.res +110 -35
  103. package/lib/ocaml/Seed_PromptTest-ReventlessSeed.cmi +0 -0
  104. package/lib/ocaml/Seed_PromptTest-ReventlessSeed.cmj +0 -0
  105. package/lib/ocaml/Seed_PromptTest-ReventlessSeed.cmt +0 -0
  106. package/lib/ocaml/Seed_PromptTest.ast +0 -0
  107. package/lib/ocaml/Seed_PromptTest.res +59 -0
  108. package/lib/ocaml/Seed_Random-ReventlessSeed.cmt +0 -0
  109. package/lib/ocaml/Seed_RandomTest-ReventlessSeed.cmi +0 -0
  110. package/lib/ocaml/Seed_RandomTest-ReventlessSeed.cmj +0 -0
  111. package/lib/ocaml/Seed_RandomTest-ReventlessSeed.cmt +0 -0
  112. package/lib/ocaml/Seed_RandomTest.ast +0 -0
  113. package/lib/ocaml/Seed_RandomTest.res +160 -0
  114. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmi +0 -0
  115. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmj +0 -0
  116. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmt +0 -0
  117. package/lib/ocaml/Seed_Runner.ast +0 -0
  118. package/lib/ocaml/Seed_Runner.res +38 -7
  119. package/lib/ocaml/Seed_Types-ReventlessSeed.cmt +0 -0
  120. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmi +0 -0
  121. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmj +0 -0
  122. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmt +0 -0
  123. package/lib/ocaml/Seed_Upload.ast +0 -0
  124. package/lib/ocaml/Seed_Upload.res +40 -42
  125. package/lib/ocaml/Seed_Users-ReventlessSeed.cmi +0 -0
  126. package/lib/ocaml/Seed_Users-ReventlessSeed.cmj +0 -0
  127. package/lib/ocaml/Seed_Users-ReventlessSeed.cmt +0 -0
  128. package/lib/ocaml/Seed_Users.ast +0 -0
  129. package/lib/ocaml/Seed_Users.res +80 -0
  130. package/lib/ocaml/Seed_UsersTest-ReventlessSeed.cmi +0 -0
  131. package/lib/ocaml/Seed_UsersTest-ReventlessSeed.cmj +0 -0
  132. package/lib/ocaml/Seed_UsersTest-ReventlessSeed.cmt +0 -0
  133. package/lib/ocaml/Seed_UsersTest.ast +0 -0
  134. package/lib/ocaml/Seed_UsersTest.res +92 -0
  135. package/package.json +7 -2
  136. package/rescript.json +9 -1
  137. package/src/Seed.res +6 -3
  138. package/src/Seed.res.mjs +3 -0
  139. package/src/Seed_Client.res +228 -15
  140. package/src/Seed_Client.res.mjs +196 -23
  141. package/src/Seed_Connect.res +27 -18
  142. package/src/Seed_Connect.res.mjs +10 -6
  143. package/src/Seed_Prompt.res +110 -35
  144. package/src/Seed_Prompt.res.mjs +73 -8
  145. package/src/Seed_Runner.res +38 -7
  146. package/src/Seed_Runner.res.mjs +19 -1
  147. package/src/Seed_Upload.res +40 -42
  148. package/src/Seed_Upload.res.mjs +65 -69
  149. package/src/Seed_Users.res +80 -0
  150. package/src/Seed_Users.res.mjs +90 -0
  151. package/tests/Seed_ClientTest.res +157 -0
  152. package/tests/Seed_ClientTest.res.mjs +167 -0
  153. package/tests/Seed_PromptTest.res +59 -0
  154. package/tests/Seed_PromptTest.res.mjs +63 -0
  155. package/tests/Seed_RandomTest.res +160 -0
  156. package/tests/Seed_RandomTest.res.mjs +208 -0
  157. package/tests/Seed_UsersTest.res +92 -0
  158. package/tests/Seed_UsersTest.res.mjs +95 -0
@@ -5,6 +5,7 @@ import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
5
5
  import * as Nodereadline from "node:readline";
6
6
  import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.js";
7
7
  import * as Seed_Types$ReventlessSeed from "./Seed_Types.res.mjs";
8
+ import * as Seed_Users$ReventlessSeed from "./Seed_Users.res.mjs";
8
9
 
9
10
  let rlRef = {
10
11
  contents: undefined
@@ -53,7 +54,7 @@ function envValue(key) {
53
54
  }
54
55
 
55
56
  function requireTty() {
56
- if (process.stdin.isTTY) {
57
+ if (Stdlib_Option.getOr(process.stdin.isTTY, false)) {
57
58
  return;
58
59
  }
59
60
  throw {
@@ -82,7 +83,19 @@ function askHidden(query) {
82
83
  });
83
84
  }
84
85
 
85
- async function select(title, options, env) {
86
+ function isAffirmative(answer) {
87
+ let match = answer.trim().toLowerCase();
88
+ switch (match) {
89
+ case "1" :
90
+ case "y" :
91
+ case "yes" :
92
+ return true;
93
+ default:
94
+ return false;
95
+ }
96
+ }
97
+
98
+ async function select(title, options, env, defaultIndex) {
86
99
  if (options.length === 1) {
87
100
  return options[0][1];
88
101
  }
@@ -106,8 +119,13 @@ async function select(title, options, env) {
106
119
  options.forEach((param, i) => {
107
120
  console.log(` ` + (i + 1 | 0).toString() + `) ` + param[0]);
108
121
  });
122
+ let fallback = Stdlib_Option.flatMap(defaultIndex, i => options[i]);
123
+ let hint = defaultIndex !== undefined && fallback !== undefined ? ` (default ` + (defaultIndex + 1 | 0).toString() + `)` : "";
109
124
  let pick = async () => {
110
- let answer = await ask(`\nSelect [1-` + options.length.toString() + `]: `);
125
+ let answer = await ask(`\nSelect [1-` + options.length.toString() + `]` + hint + `: `);
126
+ if (answer === "" && fallback !== undefined) {
127
+ return fallback[1];
128
+ }
111
129
  let n = Stdlib_Int.fromString(answer, undefined);
112
130
  if (n !== undefined) {
113
131
  if (n >= 1 && n <= options.length) {
@@ -124,12 +142,10 @@ async function select(title, options, env) {
124
142
  return await pick();
125
143
  }
126
144
 
127
- async function credentials(localDefaultsOpt) {
128
- let localDefaults = localDefaultsOpt !== undefined ? localDefaultsOpt : false;
129
- let u = envValue("REVENTLESS_DEMO_USER");
145
+ async function askCredentials(localDefaults, envUser) {
130
146
  let username;
131
- if (u !== undefined) {
132
- username = u;
147
+ if (envUser !== undefined) {
148
+ username = envUser;
133
149
  } else {
134
150
  requireTty();
135
151
  let entered = await ask(localDefaults ? "Username [admin]: " : "Username: ");
@@ -144,6 +160,52 @@ async function credentials(localDefaultsOpt) {
144
160
  let entered$1 = await askHidden(localDefaults ? "Password [admin]: " : "Password: ");
145
161
  password = entered$1 === "" && localDefaults ? "admin" : entered$1;
146
162
  }
163
+ return [
164
+ username,
165
+ password
166
+ ];
167
+ }
168
+
169
+ async function fromUsersFile(envUser) {
170
+ let match = Seed_Users$ReventlessSeed.load(envValue("SEED_USERS_FILE"));
171
+ if (match === undefined) {
172
+ return;
173
+ }
174
+ let users = match[1];
175
+ let path = match[0];
176
+ let chosen = envUser !== undefined ? users.find(u => u.username === envUser) : await select(`User (` + path + `):`, users.map(u => [
177
+ Seed_Users$ReventlessSeed.label(u),
178
+ u
179
+ ]), "SEED_USER", 0);
180
+ return Stdlib_Option.map(chosen, u => {
181
+ console.log(`Logging in as ` + u.username + ` (from ` + path + `)`);
182
+ return [
183
+ u.username,
184
+ u.password
185
+ ];
186
+ });
187
+ }
188
+
189
+ async function credentials(localDefaultsOpt) {
190
+ let localDefaults = localDefaultsOpt !== undefined ? localDefaultsOpt : false;
191
+ let envUser = envValue("REVENTLESS_DEMO_USER");
192
+ let match = envValue("REVENTLESS_DEMO_PASSWORD");
193
+ let match$1;
194
+ let exit = 0;
195
+ if (envUser !== undefined && match !== undefined) {
196
+ match$1 = [
197
+ envUser,
198
+ match
199
+ ];
200
+ } else {
201
+ exit = 1;
202
+ }
203
+ if (exit === 1) {
204
+ let pair = await fromUsersFile(envUser);
205
+ match$1 = pair !== undefined ? pair : await askCredentials(localDefaults, envUser);
206
+ }
207
+ let password = match$1[1];
208
+ let username = match$1[0];
147
209
  if (username === "" || password === "") {
148
210
  throw {
149
211
  RE_EXN_ID: Seed_Types$ReventlessSeed.Failed,
@@ -166,7 +228,10 @@ export {
166
228
  requireTty,
167
229
  ask,
168
230
  askHidden,
231
+ isAffirmative,
169
232
  select,
233
+ askCredentials,
234
+ fromUsersFile,
170
235
  credentials,
171
236
  }
172
237
  /* node:readline Not a pure module */
Binary file
@@ -2,11 +2,9 @@
2
2
 
3
3
  open Seed_Types
4
4
 
5
- @scope("process") @val external exit: int => unit = "exit"
6
- @scope("process") @val external env: dict<string> = "env"
7
5
 
8
6
  let envOr = (key: string, fallback: string): string =>
9
- env->Dict.get(key)->Option.getOr(fallback)
7
+ NodeProcess.env->Dict.get(key)->Option.getOr(fallback)
10
8
 
11
9
  /** One line of progress per phase, so a slow run never looks hung. */
12
10
  let report = (line: string): unit => Console.log(` ${line}`)
@@ -90,6 +88,33 @@ let warn = (warnings: array<string>): unit =>
90
88
  warnings->Array.forEach(w => Console.log(` - ${w}`))
91
89
  }
92
90
 
91
+ /**
92
+ * Pre-flight: refuse to seed onto a store that already holds data.
93
+ *
94
+ * The harness is a one-shot against a fresh store — a re-run would hit the
95
+ * domain's own duplicate rejections (`CategoryAlreadyExists`, …) and abort
96
+ * mid-phase. Catching it here, before any command is sent, turns that into an
97
+ * honest "nothing was written" startup abort instead of a misleading
98
+ * half-seeded one. It is the inverse of `verifyViews`: seeding refuses to start
99
+ * unless the store reads empty. Stops at the first non-empty probe view, so a
100
+ * populated store aborts after a single query.
101
+ */
102
+ let assertStoreEmpty = async (client: Seed_Client.t, ~probeViews: array<string>): unit =>
103
+ for i in 0 to probeViews->Array.length - 1 {
104
+ switch probeViews->Array.get(i) {
105
+ | Some(name) =>
106
+ let count = await Seed_Client.countNodes(client, ~field=name)
107
+ if count > 0 {
108
+ throw(
109
+ Failed(
110
+ `the target store is not empty — "${name}" already holds ${count->Int.toString} row(s). Seeding is a one-shot against a fresh store; reset the store before re-running.`,
111
+ ),
112
+ )
113
+ }
114
+ | None => ()
115
+ }
116
+ }
117
+
93
118
  /**
94
119
  * Wraps a seed run. On failure it prints the cause and exits non-zero, saying
95
120
  * plainly that the store is now half-seeded — recovery is a reset, not a re-run.
@@ -100,7 +125,7 @@ let run = async (main: unit => promise<unit>): unit =>
100
125
  // Exit cleanly: HTTP keep-alive sockets (and, on the interactive path, the
101
126
  // readline/stdin handle) can otherwise keep the event loop alive so the CLI
102
127
  // appears to hang after a successful run.
103
- exit(0)
128
+ NodeProcess.exit(0)
104
129
  } catch {
105
130
  | Failed(message) =>
106
131
  Console.error("")
@@ -108,7 +133,7 @@ let run = async (main: unit => promise<unit>): unit =>
108
133
  Console.error("fresh store once the cause below is fixed.")
109
134
  Console.error("")
110
135
  Console.error(message)
111
- exit(1)
136
+ NodeProcess.exit(1)
112
137
  | exn =>
113
138
  Console.error("")
114
139
  Console.error("Seeding aborted with an unexpected error:")
@@ -116,7 +141,7 @@ let run = async (main: unit => promise<unit>): unit =>
116
141
  Console.error(
117
142
  exn->JsExn.fromException->Option.flatMap(JsExn.message)->Option.getOr("unknown"),
118
143
  )
119
- exit(1)
144
+ NodeProcess.exit(1)
120
145
  }
121
146
 
122
147
  /**
@@ -128,6 +153,9 @@ type dataSet = {
128
153
  name: string,
129
154
  label: string,
130
155
  seed: Seed_Connect.connection => promise<unit>,
156
+ // View names probed by the fresh-store guard before any command is sent; a
157
+ // non-empty one aborts the run at startup. Omit to skip the guard.
158
+ probeViews?: array<string>,
131
159
  }
132
160
 
133
161
  /**
@@ -142,7 +170,7 @@ let abortStartup = (message: string): unit => {
142
170
  Console.error("Seeding did not start — nothing was written. Fix the cause below and re-run.")
143
171
  Console.error("")
144
172
  Console.error(message)
145
- exit(1)
173
+ NodeProcess.exit(1)
146
174
  }
147
175
 
148
176
  /**
@@ -179,6 +207,9 @@ let seed = (~sets: array<dataSet>, ~connect: unit => promise<Seed_Connect.connec
179
207
  }
180
208
  let connection = await connect()
181
209
  Seed_Prompt.close()
210
+ // Runs inside this pre-seed `try`, so refusing a non-empty store (or a
211
+ // failed probe query) is reported as "did not start", not "half-seeded".
212
+ await assertStoreEmpty(connection.client, ~probeViews=chosen.probeViews->Option.getOr([]))
182
213
  Some((chosen, connection))
183
214
  } catch {
184
215
  | Failed(message) =>
@@ -83,6 +83,22 @@ function warn(warnings) {
83
83
  }
84
84
  }
85
85
 
86
+ async function assertStoreEmpty(client, probeViews) {
87
+ for (let i = 0, i_finish = probeViews.length; i < i_finish; ++i) {
88
+ let name = probeViews[i];
89
+ if (name !== undefined) {
90
+ let count = await Seed_Client$ReventlessSeed.countNodes(client, name);
91
+ if (count > 0) {
92
+ throw {
93
+ RE_EXN_ID: Seed_Types$ReventlessSeed.Failed,
94
+ _1: `the target store is not empty — "` + name + `" already holds ` + count.toString() + ` row(s). Seeding is a one-shot against a fresh store; reset the store before re-running.`,
95
+ Error: new Error()
96
+ };
97
+ }
98
+ }
99
+ }
100
+ }
101
+
86
102
  async function run(main) {
87
103
  try {
88
104
  await main();
@@ -139,13 +155,14 @@ function seed(sets, connect) {
139
155
  chosen = await Seed_Prompt$ReventlessSeed.select("Data set:", sets.map(s => [
140
156
  s.label,
141
157
  s
142
- ]), undefined);
158
+ ]), undefined, undefined);
143
159
  }
144
160
  } else {
145
161
  chosen = sets[0];
146
162
  }
147
163
  let connection = await connect();
148
164
  Seed_Prompt$ReventlessSeed.close();
165
+ await assertStoreEmpty(connection.client, Stdlib_Option.getOr(chosen.probeViews, []));
149
166
  started = [
150
167
  chosen,
151
168
  connection
@@ -179,6 +196,7 @@ export {
179
196
  verifyViews,
180
197
  unfillableWarnings,
181
198
  warn,
199
+ assertStoreEmpty,
182
200
  run,
183
201
  abortStartup,
184
202
  seed,
Binary file
@@ -1,27 +1,26 @@
1
- // Seed-time asset upload against the framework's presign-shaped upload contract.
1
+ // Seed-time asset upload against the framework's upload contract (route B).
2
2
  //
3
- // One code path for both providers: the AWS `Upload_Presign_S3` Function URL and
4
- // the local dev upload route expose the SAME shape — POST `{fileName,contentType}`
5
- // → `{uploadUrl, storageRef}`, then PUT the bytes to `uploadUrl`. `uploadAsset`
6
- // resolves `Ok(storageRef)` — the same same-origin `/{prefix}/{key}` ref a command
7
- // stores and the UI renders.
3
+ // Minting is a GraphQL mutation on the domain API — `Upload_Presign(store, fileName,
4
+ // contentType)` — authenticated by the same bearer the seed already uses for commands
5
+ // (no separate endpoint, no anonymous surface). `uploadAsset` issues it through the
6
+ // shared `Seed_Client`, then PUTs the bytes to the returned `uploadUrl` and resolves
7
+ // `Ok(storageRef)` — the same `/{prefix}/{key}` ref a command stores and the UI renders.
8
8
  //
9
- // The seed runs under Node, so the returned `uploadUrl` is resolved to an
10
- // absolute URL against the endpoint's origin: AWS returns an absolute presigned
11
- // S3 URL (unchanged), while the local route returns a same-origin relative
12
- // `/{prefix}/{key}` that Node's `fetch` cannot PUT to until it is made absolute.
9
+ // The seed runs under Node, so a relative `uploadUrl` (the local dev server returns a
10
+ // same-origin `/{prefix}/{key}`) is resolved to an absolute URL against the client's
11
+ // endpoint origin before the PUT; AWS returns an absolute presigned S3 URL (used as-is).
12
+ // The PUT itself is unauthenticated — presigned on AWS, open on the local route.
13
13
 
14
14
  type fetchInit = {method: string, headers: dict<string>, body: string}
15
15
  type response
16
16
 
17
17
  @val external fetch: (string, fetchInit) => promise<response> = "fetch"
18
- @send external responseJson: response => promise<JSON.t> = "json"
19
18
  @send external responseText: response => promise<string> = "text"
20
19
  @get external responseOk: response => bool = "ok"
21
20
  @get external responseStatus: response => int = "status"
22
21
 
23
- // Resolve a possibly-relative URL against a base (WHATWG URL semantics: an
24
- // absolute `input` ignores `base`, a relative one is resolved against it).
22
+ // Resolve a possibly-relative URL against a base (WHATWG URL semantics: an absolute
23
+ // `input` ignores `base`, a relative one is resolved against it).
25
24
  type url
26
25
  @new external makeUrl: (string, string) => url = "URL"
27
26
  @get external urlHref: url => string = "href"
@@ -38,51 +37,50 @@ let asString = (json: JSON.t): option<string> =>
38
37
  | _ => None
39
38
  }
40
39
 
41
- // A `fetch` that reports an unreachable endpoint as `Error` instead of throwing,
42
- // so the two-step upload can thread failures without exceptions.
40
+ // Whether this run should skip uploads entirely. `SEED_SKIP_UPLOADS` seeds domain data
41
+ // fast, or skips a broken/absent upload path without editing the data set.
42
+ let uploadsSkipped = (): bool => Seed_Prompt.envValue("SEED_SKIP_UPLOADS")->Option.isSome
43
+
44
+ // A `fetch` that reports an unreachable endpoint as `Error` instead of throwing.
43
45
  let tryFetch = async (url: string, init: fetchInit): result<response, string> =>
44
46
  try Ok(await fetch(url, init)) catch {
45
47
  | _ => Error(`cannot reach ${url}`)
46
48
  }
47
49
 
48
50
  /**
49
- * Uploads `bytes` under `fileName`/`contentType` through `uploadEndpoint` and
51
+ * Uploads `bytes` under `fileName`/`contentType` into `store` (the qualified
52
+ * `{plugin}.{store}` the asset's field declares, e.g. `"Catalog.productImages"`) and
50
53
  * resolves `Ok(storageRef)` (the stored `/{prefix}/{key}` ref), or `Error(msg)`
51
- * describing the step that failed. `authToken`, when supplied, is sent as a
52
- * Bearer on the presign request (the endpoint decides whether it is required;
53
- * the PUT itself is unauthenticated — presigned on AWS, open locally).
54
+ * describing the step that failed. Mints through the domain API's `Upload_Presign`
55
+ * mutation on `client`, then PUTs the bytes to the returned `uploadUrl`.
54
56
  */
55
57
  let uploadAsset = async (
56
- ~uploadEndpoint: string,
58
+ ~client: Seed_Client.t,
59
+ ~store: string,
57
60
  ~bytes: string,
58
61
  ~fileName: string,
59
62
  ~contentType: string,
60
- ~authToken: option<string>=?,
61
63
  ): result<string, string> => {
62
- let presignHeaders = Dict.fromArray([("content-type", "application/json")])
63
- authToken->Option.forEach(t => presignHeaders->Dict.set("authorization", `Bearer ${t}`))
64
- let presignBody = JSON.stringify(
65
- JSON.Encode.object(
66
- Dict.fromArray([
67
- ("fileName", JSON.Encode.string(fileName)),
68
- ("contentType", JSON.Encode.string(contentType)),
69
- ]),
70
- ),
71
- )
64
+ // GraphQL string literals: JSON-quote the argument values (JSON string escaping is a
65
+ // superset-safe subset of GraphQL's for these ASCII-ish inputs).
66
+ let q = s => JSON.stringify(JSON.Encode.string(s))
67
+ let query = `mutation { r: Upload_Presign(store: ${q(store)}, fileName: ${q(fileName)}, contentType: ${q(contentType)}) { uploadUrl storageRef } }`
68
+
69
+ let presign = try Ok(await Seed_Client.gql(client, ~query, ~label="Upload_Presign")) catch {
70
+ | Seed_Types.Failed(m) => Error(m)
71
+ | _ => Error("Upload_Presign: unexpected error")
72
+ }
72
73
 
73
- switch await tryFetch(uploadEndpoint, {method: "POST", headers: presignHeaders, body: presignBody}) {
74
- | Error(m) => Error(`presign: ${m} — is the platform running?`)
75
- | Ok(presignRes) if !(presignRes->responseOk) =>
76
- let detail = await presignRes->responseText
77
- Error(`presign failed with HTTP ${(presignRes->responseStatus)->Int.toString}: ${detail}`)
78
- | Ok(presignRes) =>
79
- let json = await presignRes->responseJson
74
+ switch presign {
75
+ | Error(m) => Error(`presign: ${m}`)
76
+ | Ok(data) =>
77
+ let r = data->field("r")->Option.getOr(JSON.Encode.null)
80
78
  switch (
81
- json->field("uploadUrl")->Option.flatMap(asString),
82
- json->field("storageRef")->Option.flatMap(asString),
79
+ r->field("uploadUrl")->Option.flatMap(asString),
80
+ r->field("storageRef")->Option.flatMap(asString),
83
81
  ) {
84
82
  | (Some(uploadUrl), Some(storageRef)) =>
85
- let putUrl = urlHref(makeUrl(uploadUrl, uploadEndpoint))
83
+ let putUrl = urlHref(makeUrl(uploadUrl, Seed_Client.endpoint(client)))
86
84
  switch await tryFetch(
87
85
  putUrl,
88
86
  {method: "PUT", headers: Dict.fromArray([("content-type", contentType)]), body: bytes},
@@ -93,7 +91,7 @@ let uploadAsset = async (
93
91
  let detail = await putRes->responseText
94
92
  Error(`upload PUT failed with HTTP ${(putRes->responseStatus)->Int.toString}: ${detail}`)
95
93
  }
96
- | _ => Error("presign response missing uploadUrl/storageRef")
94
+ | _ => Error("Upload_Presign response missing uploadUrl/storageRef")
97
95
  }
98
96
  }
99
97
  }
@@ -1,6 +1,10 @@
1
1
  // Generated by ReScript, PLEASE EDIT WITH CARE
2
2
 
3
3
  import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
4
+ import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.js";
5
+ import * as Seed_Types$ReventlessSeed from "./Seed_Types.res.mjs";
6
+ import * as Seed_Client$ReventlessSeed from "./Seed_Client.res.mjs";
7
+ import * as Seed_Prompt$ReventlessSeed from "./Seed_Prompt.res.mjs";
4
8
 
5
9
  function field(json, key) {
6
10
  if (typeof json === "object" && json !== null && !Array.isArray(json)) {
@@ -14,6 +18,10 @@ function asString(json) {
14
18
  }
15
19
  }
16
20
 
21
+ function uploadsSkipped() {
22
+ return Stdlib_Option.isSome(Seed_Prompt$ReventlessSeed.envValue("SEED_SKIP_UPLOADS"));
23
+ }
24
+
17
25
  async function tryFetch(url, init) {
18
26
  try {
19
27
  return {
@@ -28,91 +36,79 @@ async function tryFetch(url, init) {
28
36
  }
29
37
  }
30
38
 
31
- async function uploadAsset(uploadEndpoint, bytes, fileName, contentType, authToken) {
32
- let presignHeaders = Object.fromEntries([[
33
- "content-type",
34
- "application/json"
35
- ]]);
36
- Stdlib_Option.forEach(authToken, t => {
37
- presignHeaders["authorization"] = `Bearer ` + t;
38
- });
39
- let presignBody = JSON.stringify(Object.fromEntries([
40
- [
41
- "fileName",
42
- fileName
43
- ],
44
- [
45
- "contentType",
46
- contentType
47
- ]
48
- ]));
49
- let m = await tryFetch(uploadEndpoint, {
50
- method: "POST",
51
- headers: presignHeaders,
52
- body: presignBody
53
- });
54
- if (m.TAG !== "Ok") {
39
+ async function uploadAsset(client, store, bytes, fileName, contentType) {
40
+ let query = `mutation { r: Upload_Presign(store: ` + JSON.stringify(store) + `, fileName: ` + JSON.stringify(fileName) + `, contentType: ` + JSON.stringify(contentType) + `) { uploadUrl storageRef } }`;
41
+ let presign;
42
+ try {
43
+ presign = {
44
+ TAG: "Ok",
45
+ _0: await Seed_Client$ReventlessSeed.gql(client, query, "Upload_Presign")
46
+ };
47
+ } catch (raw_m) {
48
+ let m = Primitive_exceptions.internalToException(raw_m);
49
+ presign = m.RE_EXN_ID === Seed_Types$ReventlessSeed.Failed ? ({
50
+ TAG: "Error",
51
+ _0: m._1
52
+ }) : ({
53
+ TAG: "Error",
54
+ _0: "Upload_Presign: unexpected error"
55
+ });
56
+ }
57
+ if (presign.TAG !== "Ok") {
55
58
  return {
56
59
  TAG: "Error",
57
- _0: `presign: ` + m._0 + ` — is the platform running?`
60
+ _0: `presign: ` + presign._0
58
61
  };
59
62
  }
60
- let presignRes = m._0;
61
- if (presignRes.ok) {
62
- let json = await presignRes.json();
63
- let match = Stdlib_Option.flatMap(field(json, "uploadUrl"), asString);
64
- let match$1 = Stdlib_Option.flatMap(field(json, "storageRef"), asString);
65
- if (match === undefined) {
66
- return {
67
- TAG: "Error",
68
- _0: "presign response missing uploadUrl/storageRef"
69
- };
70
- }
71
- if (match$1 === undefined) {
72
- return {
73
- TAG: "Error",
74
- _0: "presign response missing uploadUrl/storageRef"
75
- };
76
- }
77
- let putUrl = new URL(match, uploadEndpoint).href;
78
- let m$1 = await tryFetch(putUrl, {
79
- method: "PUT",
80
- headers: Object.fromEntries([[
81
- "content-type",
82
- contentType
83
- ]]),
84
- body: bytes
85
- });
86
- if (m$1.TAG !== "Ok") {
87
- return {
88
- TAG: "Error",
89
- _0: `upload PUT: ` + m$1._0
90
- };
91
- }
92
- let putRes = m$1._0;
93
- if (putRes.ok) {
94
- return {
95
- TAG: "Ok",
96
- _0: match$1
97
- };
98
- }
99
- let detail = await putRes.text();
63
+ let r = Stdlib_Option.getOr(field(presign._0, "r"), null);
64
+ let match = Stdlib_Option.flatMap(field(r, "uploadUrl"), asString);
65
+ let match$1 = Stdlib_Option.flatMap(field(r, "storageRef"), asString);
66
+ if (match === undefined) {
100
67
  return {
101
68
  TAG: "Error",
102
- _0: `upload PUT failed with HTTP ` + putRes.status.toString() + `: ` + detail
69
+ _0: "Upload_Presign response missing uploadUrl/storageRef"
70
+ };
71
+ }
72
+ if (match$1 === undefined) {
73
+ return {
74
+ TAG: "Error",
75
+ _0: "Upload_Presign response missing uploadUrl/storageRef"
76
+ };
77
+ }
78
+ let putUrl = new URL(match, Seed_Client$ReventlessSeed.endpoint(client)).href;
79
+ let m$1 = await tryFetch(putUrl, {
80
+ method: "PUT",
81
+ headers: Object.fromEntries([[
82
+ "content-type",
83
+ contentType
84
+ ]]),
85
+ body: bytes
86
+ });
87
+ if (m$1.TAG !== "Ok") {
88
+ return {
89
+ TAG: "Error",
90
+ _0: `upload PUT: ` + m$1._0
91
+ };
92
+ }
93
+ let putRes = m$1._0;
94
+ if (putRes.ok) {
95
+ return {
96
+ TAG: "Ok",
97
+ _0: match$1
103
98
  };
104
99
  }
105
- let detail$1 = await presignRes.text();
100
+ let detail = await putRes.text();
106
101
  return {
107
102
  TAG: "Error",
108
- _0: `presign failed with HTTP ` + presignRes.status.toString() + `: ` + detail$1
103
+ _0: `upload PUT failed with HTTP ` + putRes.status.toString() + `: ` + detail
109
104
  };
110
105
  }
111
106
 
112
107
  export {
113
108
  field,
114
109
  asString,
110
+ uploadsSkipped,
115
111
  tryFetch,
116
112
  uploadAsset,
117
113
  }
118
- /* No side effect */
114
+ /* Seed_Prompt-ReventlessSeed Not a pure module */
Binary file