@cardonjs/testing 0.0.0-stage → 0.7.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 (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +537 -2
  3. package/THIRD_PARTY_NOTICES.md +72 -0
  4. package/dist/access-token-contract.d.ts +26 -0
  5. package/dist/access-token-contract.d.ts.map +1 -0
  6. package/dist/access-token-contract.js +252 -0
  7. package/dist/access-token-contract.js.map +1 -0
  8. package/dist/assertion.d.ts +7 -0
  9. package/dist/assertion.d.ts.map +1 -0
  10. package/dist/assertion.js +11 -0
  11. package/dist/assertion.js.map +1 -0
  12. package/dist/audit-contract.d.ts +52 -0
  13. package/dist/audit-contract.d.ts.map +1 -0
  14. package/dist/audit-contract.js +522 -0
  15. package/dist/audit-contract.js.map +1 -0
  16. package/dist/contract.d.ts +14 -0
  17. package/dist/contract.d.ts.map +1 -0
  18. package/dist/contract.js +8 -0
  19. package/dist/contract.js.map +1 -0
  20. package/dist/envelopes.d.ts +33 -0
  21. package/dist/envelopes.d.ts.map +1 -0
  22. package/dist/envelopes.js +121 -0
  23. package/dist/envelopes.js.map +1 -0
  24. package/dist/idempotency-contract.d.ts +19 -0
  25. package/dist/idempotency-contract.d.ts.map +1 -0
  26. package/dist/idempotency-contract.js +234 -0
  27. package/dist/idempotency-contract.js.map +1 -0
  28. package/dist/index.d.ts +10 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +10 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/logs.d.ts +18 -0
  33. package/dist/logs.d.ts.map +1 -0
  34. package/dist/logs.js +20 -0
  35. package/dist/logs.js.map +1 -0
  36. package/dist/miniflare/bindings.d.ts +43 -0
  37. package/dist/miniflare/bindings.d.ts.map +1 -0
  38. package/dist/miniflare/bindings.js +90 -0
  39. package/dist/miniflare/bindings.js.map +1 -0
  40. package/dist/miniflare/broken.d.ts +12 -0
  41. package/dist/miniflare/broken.d.ts.map +1 -0
  42. package/dist/miniflare/broken.js +27 -0
  43. package/dist/miniflare/broken.js.map +1 -0
  44. package/dist/miniflare/executor-channel.d.ts +37 -0
  45. package/dist/miniflare/executor-channel.d.ts.map +1 -0
  46. package/dist/miniflare/executor-channel.js +144 -0
  47. package/dist/miniflare/executor-channel.js.map +1 -0
  48. package/dist/miniflare/executor.d.ts +42 -0
  49. package/dist/miniflare/executor.d.ts.map +1 -0
  50. package/dist/miniflare/executor.js +121 -0
  51. package/dist/miniflare/executor.js.map +1 -0
  52. package/dist/miniflare/index.d.ts +10 -0
  53. package/dist/miniflare/index.d.ts.map +1 -0
  54. package/dist/miniflare/index.js +10 -0
  55. package/dist/miniflare/index.js.map +1 -0
  56. package/dist/miniflare/migrations.d.ts +23 -0
  57. package/dist/miniflare/migrations.d.ts.map +1 -0
  58. package/dist/miniflare/migrations.js +43 -0
  59. package/dist/miniflare/migrations.js.map +1 -0
  60. package/dist/miniflare/one-call-d1.d.ts +12 -0
  61. package/dist/miniflare/one-call-d1.d.ts.map +1 -0
  62. package/dist/miniflare/one-call-d1.js +223 -0
  63. package/dist/miniflare/one-call-d1.js.map +1 -0
  64. package/dist/miniflare/statements.d.ts +18 -0
  65. package/dist/miniflare/statements.d.ts.map +1 -0
  66. package/dist/miniflare/statements.js +175 -0
  67. package/dist/miniflare/statements.js.map +1 -0
  68. package/dist/miniflare/storage.d.ts +58 -0
  69. package/dist/miniflare/storage.d.ts.map +1 -0
  70. package/dist/miniflare/storage.js +129 -0
  71. package/dist/miniflare/storage.js.map +1 -0
  72. package/dist/miniflare/types.d.ts +25 -0
  73. package/dist/miniflare/types.d.ts.map +1 -0
  74. package/dist/miniflare/types.js +2 -0
  75. package/dist/miniflare/types.js.map +1 -0
  76. package/dist/miniflare/worker.d.ts +70 -0
  77. package/dist/miniflare/worker.d.ts.map +1 -0
  78. package/dist/miniflare/worker.js +137 -0
  79. package/dist/miniflare/worker.js.map +1 -0
  80. package/dist/push-subscription-contract.d.ts +54 -0
  81. package/dist/push-subscription-contract.d.ts.map +1 -0
  82. package/dist/push-subscription-contract.js +735 -0
  83. package/dist/push-subscription-contract.js.map +1 -0
  84. package/dist/routes.d.ts +72 -0
  85. package/dist/routes.d.ts.map +1 -0
  86. package/dist/routes.js +196 -0
  87. package/dist/routes.js.map +1 -0
  88. package/llms.txt +234 -0
  89. package/package.json +69 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"one-call-d1.d.ts","sourceRoot":"","sources":["../../src/miniflare/one-call-d1.ts"],"names":[],"mappings":"AA6BA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,qDAAqD;AACrD,MAAM,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AA6NjE;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,cAAc,GAAG,CAAC,QAAQ,EAAE,MAAM,KAAK,UAAU,CAUjF"}
@@ -0,0 +1,223 @@
1
+ /**
2
+ * The one-call D1: a `D1Database` for Node whose `prepare` and `bind` are local and whose every
3
+ * execution (`all`, `run`, `raw`, `first`, `batch`, `exec`) is one request to the executor
4
+ * Worker (`executor.ts`, where the wire format is described), which runs it on the real D1
5
+ * binding in workerd.
6
+ *
7
+ * Miniflare's own binding object is a proxy: `prepare`, `bind` and every property read on it is
8
+ * a blocking round trip to workerd, so a Drizzle-shaped query (`prepare().bind().raw()`) costs
9
+ * several synchronous calls and one asynchronous one (about 80 ms on Windows, whose timer
10
+ * resolution makes each blocking call about 16 ms). Here it costs one asynchronous request.
11
+ *
12
+ * D1's binding is JavaScript in workerd (`cloudflare-internal:d1-api`); what it does before a
13
+ * query leaves the Worker is done here with the same code: `prepare` keeps the SQL as given in
14
+ * `statement`; `bind` checks and converts the values into `params` and throws D1's own
15
+ * `D1_TYPE_ERROR` synchronously for one it refuses (a plain array is kept, not copied: D1 keeps
16
+ * the caller's array, so a change made to it before the execution is sent); each execution
17
+ * serialises `statement` and `params` when it is called, as D1 does. `first` looks the column
18
+ * up on the row here, as D1 does. Everything else (running the SQL, `raw`'s column names, the
19
+ * batch's transaction, `exec`'s line split, results, `meta` and errors) is the real binding's,
20
+ * in workerd. Errors come back as `Error`s (or the standard subclass D1 threw) with the same name
21
+ * and message and the same chain of causes; their stack is the Node one, where the call was
22
+ * made.
23
+ *
24
+ * Executions on one database are sent one at a time, in the order they were called: the next
25
+ * request leaves when the previous one is answered. A Worker's D1 calls reach the database in
26
+ * the order they were made; separate requests would not (several connections can deliver them
27
+ * in another order).
28
+ */
29
+ import { types } from "node:util";
30
+ /**
31
+ * One bound value, as D1's `bind` (workerd's `d1-api`) checks and converts it: strings and
32
+ * numbers as they are, booleans as 1 or 0, `null`, an array whose every element is a number from
33
+ * 0 to 255 (the same array, not a copy), an `ArrayBuffer` or any view as an array of its
34
+ * elements (a copy); anything else throws D1's error. An `ArrayBuffer` is recognised as D1 does
35
+ * (`instanceof`), and also by its internal slot, so one from another realm in Node counts, as it
36
+ * does once it is in a Worker; a look-alike with only the tag does not.
37
+ *
38
+ * Adapted from workerd's D1 binding (`src/cloudflare/internal/d1-api.ts`), Copyright (c)
39
+ * Cloudflare, Inc., Apache License 2.0: see THIRD_PARTY_NOTICES.md in this package.
40
+ */
41
+ function d1Value(r) {
42
+ const rType = typeof r;
43
+ if (rType === "number" || rType === "string") {
44
+ return r;
45
+ }
46
+ if (rType === "boolean") {
47
+ return r ? 1 : 0;
48
+ }
49
+ if (rType === "object") {
50
+ if (r === null)
51
+ return r;
52
+ if (Array.isArray(r) && r.every((b) => typeof b === "number" && b >= 0 && b < 256)) {
53
+ return r;
54
+ }
55
+ if (r instanceof ArrayBuffer || types.isArrayBuffer(r)) {
56
+ return Array.from(new Uint8Array(r));
57
+ }
58
+ if (ArrayBuffer.isView(r)) {
59
+ return Array.from(r);
60
+ }
61
+ }
62
+ throw new Error(`D1_TYPE_ERROR: Type '${rType}' not supported for value '${r}'`, {
63
+ cause: new Error(`Type '${rType}' not supported for value '${r}'`),
64
+ });
65
+ }
66
+ const STANDARD_ERRORS = {
67
+ Error,
68
+ TypeError,
69
+ RangeError,
70
+ SyntaxError,
71
+ ReferenceError,
72
+ };
73
+ /** The error the executor reported, rebuilt in Node: same class (if standard), name, message, causes. */
74
+ function revive(wire) {
75
+ const Class = STANDARD_ERRORS[wire.name] ?? Error;
76
+ const error = wire.cause === undefined
77
+ ? new Class(wire.message)
78
+ : new Class(wire.message, { cause: revive(wire.cause) });
79
+ if (error.name !== wire.name)
80
+ error.name = wire.name;
81
+ return error;
82
+ }
83
+ const settle = () => undefined;
84
+ /** One database's requests: sent one at a time, in the order of the calls. */
85
+ class Executor {
86
+ send;
87
+ database;
88
+ /** Settles when the last request sent so far has been answered (never rejects). */
89
+ #tail = Promise.resolve();
90
+ constructor(send, database) {
91
+ this.send = send;
92
+ this.database = database;
93
+ }
94
+ async call(call) {
95
+ // Serialised now, when the method is called, as D1 serialises the values (a change to a
96
+ // bound array after this does not reach this execution; a value JSON refuses rejects here).
97
+ const body = JSON.stringify({ database: this.database, ...call });
98
+ const answered = this.#tail.then(() => this.#exchange(body));
99
+ this.#tail = answered.then(settle, settle);
100
+ const answer = await answered;
101
+ if (answer.error !== undefined)
102
+ throw revive(answer.error);
103
+ return answer.result;
104
+ }
105
+ async #exchange(body) {
106
+ const response = await this.send(body);
107
+ const text = await response.text();
108
+ if (!response.ok) {
109
+ throw new Error(`one-call D1: the executor refused the request (${response.status}): ${text}`);
110
+ }
111
+ return JSON.parse(text);
112
+ }
113
+ }
114
+ /**
115
+ * What `prepare` returns: D1's own fields `statement` and `params` (own, enumerable and
116
+ * writable, as on D1's statement, and read when a method is called, as D1 reads them); each
117
+ * execution is one request.
118
+ */
119
+ class OneCallStatement {
120
+ statement;
121
+ params;
122
+ #executor;
123
+ constructor(executor, statement, values) {
124
+ this.#executor = executor;
125
+ this.statement = statement;
126
+ this.params = values || [];
127
+ }
128
+ /** A new statement with these values (D1's rules; a refused value throws here, as in D1). */
129
+ bind(...values) {
130
+ return new OneCallStatement(this.#executor, this.statement, values.map(d1Value));
131
+ }
132
+ #wire() {
133
+ return { sql: this.statement, params: this.params };
134
+ }
135
+ /** As D1's `first`: the first row, or one of its columns, looked up as D1 looks it up. */
136
+ async first(colName) {
137
+ const firstResult = (await this.#executor.call({ op: "first", statement: this.#wire() }));
138
+ if (firstResult === null || firstResult === undefined)
139
+ return null;
140
+ if (colName !== undefined) {
141
+ if (firstResult?.[colName] === undefined) {
142
+ throw new Error(`D1_COLUMN_NOTFOUND: Column not found (${colName})`, {
143
+ cause: new Error("Column not found"),
144
+ });
145
+ }
146
+ return firstResult[colName];
147
+ }
148
+ return firstResult;
149
+ }
150
+ async all() {
151
+ return this.#executor.call({ op: "all", statement: this.#wire() });
152
+ }
153
+ async run() {
154
+ return this.#executor.call({ op: "run", statement: this.#wire() });
155
+ }
156
+ async raw(options) {
157
+ return this.#executor.call({
158
+ op: "raw",
159
+ statement: this.#wire(),
160
+ columnNames: Boolean(options?.columnNames),
161
+ });
162
+ }
163
+ /** The fields `batch` sends (D1 reads them from each statement). */
164
+ static wireOf(statement) {
165
+ return statement.#wire();
166
+ }
167
+ }
168
+ const UNSUPPORTED = (method) => `one-call D1: ${method} is not supported; for it, take Miniflare's own binding ` +
169
+ `with startBindings({ d1Binding: "direct" }) (or startWorker's)`;
170
+ class OneCallD1Database {
171
+ #executor;
172
+ constructor(executor) {
173
+ this.#executor = executor;
174
+ }
175
+ prepare(query) {
176
+ return new OneCallStatement(this.#executor, query);
177
+ }
178
+ /**
179
+ * As D1's `batch`: `statements.map` reads each statement's fields (so anything but an array
180
+ * fails as it does in D1), and the batch runs on this database. A statement of another one-call
181
+ * D1 runs here, as in D1; anything else (Miniflare's binding's statements, look-alikes) is
182
+ * refused, where D1 would read `statement` and `params` from any object.
183
+ */
184
+ async batch(statements) {
185
+ const wire = statements.map((s) => {
186
+ // Read first, as D1 does: `null` or `undefined` fails here with D1's TypeError.
187
+ void s.statement;
188
+ if (!(s instanceof OneCallStatement)) {
189
+ throw new TypeError("one-call D1: batch takes statements prepared by a one-call D1");
190
+ }
191
+ return OneCallStatement.wireOf(s);
192
+ });
193
+ return this.#executor.call({ op: "batch", statements: wire });
194
+ }
195
+ async exec(query) {
196
+ return this.#executor.call({ op: "exec", sql: query });
197
+ }
198
+ withSession() {
199
+ throw new Error(UNSUPPORTED("withSession"));
200
+ }
201
+ async dump() {
202
+ throw new Error(UNSUPPORTED("dump"));
203
+ }
204
+ }
205
+ /**
206
+ * One-call D1s over the executor Worker that `send` reaches: `d1(name)` is the database bound as
207
+ * `name` there. Synchronous and cheap: nothing is sent until the first execution. Every object
208
+ * for one name shares that database's queue, so executions on it are sent in call order whichever
209
+ * object they come from; different databases do not wait for each other (D1 orders the queries of
210
+ * one database; two databases have no order between them to keep).
211
+ */
212
+ export function oneCallD1s(send) {
213
+ const executors = new Map();
214
+ return (database) => {
215
+ let executor = executors.get(database);
216
+ if (executor === undefined) {
217
+ executor = new Executor(send, database);
218
+ executors.set(database, executor);
219
+ }
220
+ return new OneCallD1Database(executor);
221
+ };
222
+ }
223
+ //# sourceMappingURL=one-call-d1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"one-call-d1.js","sourceRoot":"","sources":["../../src/miniflare/one-call-d1.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAkBlC;;;;;;;;;;GAUG;AACH,SAAS,OAAO,CAAC,CAAU;IACzB,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC;IACvB,IAAI,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC7C,OAAO,CAAC,CAAC;IACX,CAAC;IACD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC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AAC;QACD,OAAO,IAAI,iBAAiB,CAAC,QAAQ,CAA0B,CAAC;IAClE,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The statements of one migration file, split the way Wrangler splits a migration
3
+ * (`wrangler d1 migrations apply`) for Drizzle Kit output and hand-written SQLite files:
4
+ *
5
+ * - The text is read as SQL: single-quoted strings (`''` inside), double-quoted, backtick and
6
+ * bracket identifiers, `--` line comments and block comments. Comments are dropped (outside
7
+ * strings only); nothing inside a string or a quoted name changes or splits.
8
+ * - A file with Drizzle Kit's `--> statement-breakpoint` is split on those only, and each
9
+ * statement keeps its `;`. A file without any is split on every `;` outside strings, comments
10
+ * and the `BEGIN … END` body of a `CREATE TRIGGER`.
11
+ * - Windows line endings and a byte order mark are accepted; empty statements are skipped.
12
+ *
13
+ * It never throws: an unterminated string, name or block comment makes the rest of the file part
14
+ * of one statement, so the database reports the error. It does not record anything in
15
+ * `d1_migrations`, and does not remove `BEGIN TRANSACTION` / `COMMIT` (D1 refuses them).
16
+ */
17
+ export declare function statementsOf(sql: string): string[];
18
+ //# sourceMappingURL=statements.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"statements.d.ts","sourceRoot":"","sources":["../../src/miniflare/statements.ts"],"names":[],"mappings":"AAmBA;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CA6HlD"}
@@ -0,0 +1,175 @@
1
+ /** What Drizzle Kit writes between the statements of a migration. */
2
+ const BREAKPOINT = "--> statement-breakpoint";
3
+ /** A run of word characters: keywords, unquoted names, numbers. */
4
+ const WORD = /[A-Za-z0-9_$\u0080-￿]+/y;
5
+ const isBlank = (c) => c === " " || c === "\t" || c === "\f" || c === "\v" || c === "\r";
6
+ /** The index after the quote that closes the one at `start` (doubled quotes escape), or -1. */
7
+ function closing(text, start, quote) {
8
+ let from = start + 1;
9
+ for (;;) {
10
+ const at = text.indexOf(quote, from);
11
+ if (at < 0)
12
+ return -1;
13
+ if (text[at + 1] !== quote)
14
+ return at + 1;
15
+ from = at + 2;
16
+ }
17
+ }
18
+ /**
19
+ * The statements of one migration file, split the way Wrangler splits a migration
20
+ * (`wrangler d1 migrations apply`) for Drizzle Kit output and hand-written SQLite files:
21
+ *
22
+ * - The text is read as SQL: single-quoted strings (`''` inside), double-quoted, backtick and
23
+ * bracket identifiers, `--` line comments and block comments. Comments are dropped (outside
24
+ * strings only); nothing inside a string or a quoted name changes or splits.
25
+ * - A file with Drizzle Kit's `--> statement-breakpoint` is split on those only, and each
26
+ * statement keeps its `;`. A file without any is split on every `;` outside strings, comments
27
+ * and the `BEGIN … END` body of a `CREATE TRIGGER`.
28
+ * - Windows line endings and a byte order mark are accepted; empty statements are skipped.
29
+ *
30
+ * It never throws: an unterminated string, name or block comment makes the rest of the file part
31
+ * of one statement, so the database reports the error. It does not record anything in
32
+ * `d1_migrations`, and does not remove `BEGIN TRANSACTION` / `COMMIT` (D1 refuses them).
33
+ */
34
+ export function statementsOf(sql) {
35
+ const text = sql.startsWith("") ? sql.slice(1) : sql;
36
+ const n = text.length;
37
+ const out = [];
38
+ let length = 0; // characters in `out`
39
+ let indent = ""; // the whitespace that starts the current line, held back
40
+ let lineBlank = true; // nothing but whitespace on the current line so far
41
+ const semicolons = [];
42
+ const breakpoints = [];
43
+ // The statement being read: its first words, and how deep a trigger's BEGIN/CASE … END goes.
44
+ let words = 0;
45
+ let create = false;
46
+ let trigger = false;
47
+ let depth = 0;
48
+ const newStatement = () => {
49
+ words = 0;
50
+ create = false;
51
+ trigger = false;
52
+ depth = 0;
53
+ };
54
+ const flush = () => {
55
+ if (indent === "")
56
+ return;
57
+ out.push(indent);
58
+ length += indent.length;
59
+ indent = "";
60
+ };
61
+ const push = (s) => {
62
+ flush();
63
+ out.push(s);
64
+ length += s.length;
65
+ lineBlank = false;
66
+ };
67
+ const word = (w) => {
68
+ const upper = w.toUpperCase();
69
+ words += 1;
70
+ if (words === 1)
71
+ create = upper === "CREATE";
72
+ else if (create && words <= 3 && upper === "TRIGGER")
73
+ trigger = true;
74
+ if (!trigger)
75
+ return;
76
+ if (upper === "BEGIN" || upper === "CASE")
77
+ depth += 1;
78
+ else if (upper === "END" && depth > 0)
79
+ depth -= 1;
80
+ };
81
+ let i = 0;
82
+ while (i < n) {
83
+ const c = text.charAt(i);
84
+ if (c === "\n" || (c === "\r" && text[i + 1] === "\n")) {
85
+ // A line ending: CRLF becomes LF (strings keep theirs, they are copied as they are).
86
+ out.push(`${indent}\n`);
87
+ length += indent.length + 1;
88
+ indent = "";
89
+ lineBlank = true;
90
+ i += c === "\r" ? 2 : 1;
91
+ }
92
+ else if (isBlank(c)) {
93
+ if (lineBlank)
94
+ indent += c;
95
+ else
96
+ push(c);
97
+ i += 1;
98
+ }
99
+ else if (c === "'" || c === '"' || c === "`" || c === "[") {
100
+ const end = c === "[" ? text.indexOf("]", i + 1) + 1 : closing(text, i, c);
101
+ if (end <= 0) {
102
+ push(text.slice(i));
103
+ break;
104
+ }
105
+ push(text.slice(i, end));
106
+ i = end;
107
+ }
108
+ else if (c === "-" && text[i + 1] === "-") {
109
+ if (text.startsWith(BREAKPOINT, i)) {
110
+ indent = "";
111
+ breakpoints.push(length);
112
+ newStatement();
113
+ i += BREAKPOINT.length;
114
+ continue;
115
+ }
116
+ const eol = text.indexOf("\n", i);
117
+ const end = eol < 0 ? n : eol;
118
+ if (lineBlank) {
119
+ // A line with only a comment goes, line ending included.
120
+ indent = "";
121
+ i = end + 1;
122
+ }
123
+ else {
124
+ i = end; // the line ending stays (a CR before it went with the comment)
125
+ }
126
+ }
127
+ else if (c === "/" && text[i + 1] === "*") {
128
+ const close = text.indexOf("*/", i + 2);
129
+ if (close < 0) {
130
+ push(text.slice(i));
131
+ break;
132
+ }
133
+ if (!lineBlank)
134
+ push(" ");
135
+ i = close + 2;
136
+ }
137
+ else if (c === ";") {
138
+ if (trigger && depth > 0) {
139
+ push(";");
140
+ }
141
+ else {
142
+ flush();
143
+ semicolons.push(length);
144
+ push(";");
145
+ newStatement();
146
+ }
147
+ i += 1;
148
+ }
149
+ else {
150
+ WORD.lastIndex = i;
151
+ const match = WORD.exec(text);
152
+ if (match === null) {
153
+ push(c);
154
+ i += 1;
155
+ }
156
+ else {
157
+ word(match[0]);
158
+ push(match[0]);
159
+ i += match[0].length;
160
+ }
161
+ }
162
+ }
163
+ const cleaned = out.join("");
164
+ const byBreakpoint = breakpoints.length > 0;
165
+ const points = byBreakpoint ? breakpoints : semicolons;
166
+ const parts = [];
167
+ let start = 0;
168
+ for (const point of points) {
169
+ parts.push(cleaned.slice(start, point));
170
+ start = byBreakpoint ? point : point + 1; // a split on `;` drops it
171
+ }
172
+ parts.push(cleaned.slice(start));
173
+ return parts.map((statement) => statement.trim()).filter((statement) => statement !== "");
174
+ }
175
+ //# sourceMappingURL=statements.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"statements.js","sourceRoot":"","sources":["../../src/miniflare/statements.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,MAAM,UAAU,GAAG,0BAA0B,CAAC;AAE9C,mEAAmE;AACnE,MAAM,IAAI,GAAG,yBAAyB,CAAC;AAEvC,MAAM,OAAO,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC;AAEjG,+FAA+F;AAC/F,SAAS,OAAO,CAAC,IAAY,EAAE,KAAa,EAAE,KAAa;IACzD,IAAI,IAAI,GAAG,KAAK,GAAG,CAAC,CAAC;IACrB,SAAS,CAAC;QACR,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACrC,IAAI,EAAE,GAAG,CAAC;YAAE,OAAO,CAAC,CAAC,CAAC;QACtB,IAAI,IAAI,CAAC,EAAE,GAAG,CAAC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AAC,CAAC;gBACR,CAAC,IAAI,CAAC,CAAC;YACT,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;gBACf,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;gBACf,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;YACvB,CAAC;QACH,CAAC;IACH,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC7B,MAAM,YAAY,GAAG,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC;IAC5C,MAAM,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,UAAU,CAAC;IACvD,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QACxC,KAAK,GAAG,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,0BAA0B;IACtE,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IACjC,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,KAAK,EAAE,CAAC,CAAC;AAC5F,CAAC"}
@@ -0,0 +1,58 @@
1
+ import { Miniflare } from "miniflare";
2
+ /** A module of a Worker, with its source inline. */
3
+ interface ModuleOptions {
4
+ readonly type: "ESModule";
5
+ readonly path: string;
6
+ readonly contents: string;
7
+ }
8
+ /**
9
+ * One Worker's options in Miniflare 4's shape: only the fields this harness sets. Typed here
10
+ * rather than against either major's `MiniflareOptions`, so the harness compiles with both.
11
+ */
12
+ interface WorkerOptions {
13
+ readonly name?: string;
14
+ readonly modules?: boolean | readonly ModuleOptions[];
15
+ readonly modulesRoot?: string;
16
+ readonly script?: string;
17
+ readonly compatibilityDate?: string;
18
+ readonly compatibilityFlags?: readonly string[];
19
+ readonly bindings?: Readonly<Record<string, string>>;
20
+ /** Binding name → database id. */
21
+ readonly d1Databases?: Readonly<Record<string, string>>;
22
+ /** Binding names, or binding name → bucket name. */
23
+ readonly r2Buckets?: readonly string[] | Readonly<Record<string, string>>;
24
+ readonly durableObjects?: Readonly<Record<string, {
25
+ readonly className: string;
26
+ readonly useSQLite: boolean;
27
+ }>>;
28
+ readonly workflows?: Readonly<Record<string, {
29
+ readonly name: string;
30
+ readonly className: string;
31
+ }>>;
32
+ readonly unsafeDirectSockets?: readonly {
33
+ readonly host: string;
34
+ readonly port: number;
35
+ }[];
36
+ }
37
+ /** Options for one Miniflare, in Miniflare 4's shape: one Worker, or several. */
38
+ export type LaunchOptions = WorkerOptions | {
39
+ readonly workers: readonly WorkerOptions[];
40
+ };
41
+ export interface Launched {
42
+ readonly mf: Miniflare;
43
+ /** Where Miniflare listens (`http://127.0.0.1:<random port>/`). */
44
+ readonly url: URL;
45
+ /** The temporary directory that holds the storage of every binding. */
46
+ readonly directory: string;
47
+ /** Disposes Miniflare and removes the directory; later calls return the same promise. */
48
+ dispose(): Promise<void>;
49
+ }
50
+ /** Removes a directory and everything in it. */
51
+ export type Remover = (directory: string) => Promise<void>;
52
+ /**
53
+ * Starts Miniflare with the options for a new storage directory; on failure nothing is left
54
+ * running and the directory is gone. `remove` is replaceable for tests.
55
+ */
56
+ export declare function launch(options: (directory: string) => LaunchOptions, remove?: Remover): Promise<Launched>;
57
+ export {};
58
+ //# sourceMappingURL=storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.d.ts","sourceRoot":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AM,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,CACtE,CAAC;IACF,QAAQ,CAAC,mBAAmB,CAAC,EAAE,SAAS;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAC5F;AAED,iFAAiF;AACjF,MAAM,MAAM,aAAa,GAAG,aAAa,GAAG;IAAE,QAAQ,CAAC,OAAO,EAAE,SAAS,aAAa,EAAE,CAAA;CAAE,CAAC;AAuB3F,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,EAAE,EAAE,SAAS,CAAC;IACvB,mEAAmE;IACnE,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC;IAClB,uEAAuE;IACvE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,yFAAyF;IACzF,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED,gDAAgD;AAChD,MAAM,MAAM,OAAO,GAAG,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAgF3D;;;GAGG;AACH,wBAAsB,MAAM,CAC1B,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,aAAa,EAC7C,MAAM,GAAE,OAAyB,GAChC,OAAO,CAAC,QAAQ,CAAC,CAuBnB"}
@@ -0,0 +1,129 @@
1
+ /**
2
+ * One Miniflare per call, with its storage in a temporary directory of its own that dispose
3
+ * removes. The directory name is short on purpose: on Windows a deep path makes local Workflows
4
+ * lose instances once their files pass the 260-character limit.
5
+ */
6
+ import { rmSync } from "node:fs";
7
+ import { mkdtemp, rm } from "node:fs/promises";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import * as miniflare from "miniflare";
11
+ import { Miniflare } from "miniflare";
12
+ /**
13
+ * Miniflare 5 takes options in a new shape and exports this function to convert Miniflare 4's;
14
+ * Miniflare 4 does not export it. Detected by the export, not by the version.
15
+ */
16
+ const convertV4 = miniflare.convertV4MiniflareOptions;
17
+ /**
18
+ * The options for the installed Miniflare, with every binding's storage under `directory`
19
+ * (`defaultPersistRoot` on Miniflare 4, `resourcePersistencePath` on 5).
20
+ */
21
+ function miniflareOptions(options, directory) {
22
+ if (convertV4 !== undefined)
23
+ return convertV4({ ...options, resourcePersistencePath: directory });
24
+ return { ...options, defaultPersistRoot: directory };
25
+ }
26
+ /** Retries: on Windows workerd may still hold a file for a moment after dispose. */
27
+ const removeDirectory = (directory) => rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
28
+ /**
29
+ * The directories of this process not removed yet. When the process exits without reaching
30
+ * `dispose` (a crash, Ctrl+C in watch mode, a hook that timed out, a missing `afterAll`), one
31
+ * `exit` listener for all of them removes what it can. Only this process's own directories:
32
+ * another test process may be using the other `cardon-*` folders. No signal handlers of its
33
+ * own: SIGINT and SIGTERM end the process as before (Miniflare's handlers call `process.exit`,
34
+ * so this listener runs then too). A process killed outright (SIGKILL) leaves its directories.
35
+ */
36
+ const live = new Set();
37
+ const pause = new Int32Array(new SharedArrayBuffer(4));
38
+ /**
39
+ * Removes a directory synchronously (an `exit` listener cannot wait), retrying for about a
40
+ * second: Miniflare's own listener has just stopped workerd, and on Windows its files stay busy
41
+ * for a moment. (`rmSync`'s `retryDelay` does not wait between retries.)
42
+ */
43
+ function removeNow(directory) {
44
+ for (let attempt = 1;; attempt++) {
45
+ try {
46
+ rmSync(directory, { recursive: true, force: true });
47
+ return;
48
+ }
49
+ catch (error) {
50
+ if (attempt >= 20)
51
+ throw error;
52
+ Atomics.wait(pause, 0, 0, 50);
53
+ }
54
+ }
55
+ }
56
+ function removeLeftovers() {
57
+ for (const directory of live) {
58
+ try {
59
+ removeNow(directory);
60
+ }
61
+ catch {
62
+ // Exiting: nothing left to report to, and the OS temp folder is cleaned eventually.
63
+ }
64
+ }
65
+ live.clear();
66
+ }
67
+ /**
68
+ * Called once Miniflare is constructed: it registers its own `exit` listener then (which stops
69
+ * workerd), and listeners run in order, so this one moves after it. Files workerd still holds
70
+ * cannot be removed.
71
+ */
72
+ function track(directory) {
73
+ live.add(directory);
74
+ process.off("exit", removeLeftovers);
75
+ process.on("exit", removeLeftovers);
76
+ }
77
+ function untrack(directory) {
78
+ live.delete(directory);
79
+ if (live.size === 0)
80
+ process.off("exit", removeLeftovers);
81
+ }
82
+ /**
83
+ * Removes the directory once dispose has run. When it still fails after the retries (on Windows
84
+ * workerd or an antivirus may hold a file), this only warns: the tests passed, and the `exit`
85
+ * listener tries again when the process ends.
86
+ */
87
+ async function release(directory, remove) {
88
+ try {
89
+ await remove(directory);
90
+ }
91
+ catch (error) {
92
+ const reason = error instanceof Error ? error.message : String(error);
93
+ process.emitWarning(`could not remove the test storage ${directory}: ${reason}`, {
94
+ code: "CARDON_TEST_STORAGE",
95
+ });
96
+ return;
97
+ }
98
+ untrack(directory);
99
+ }
100
+ /**
101
+ * Starts Miniflare with the options for a new storage directory; on failure nothing is left
102
+ * running and the directory is gone. `remove` is replaceable for tests.
103
+ */
104
+ export async function launch(options, remove = removeDirectory) {
105
+ const directory = await mkdtemp(join(tmpdir(), "cardon-"));
106
+ let mf;
107
+ try {
108
+ mf = new Miniflare(miniflareOptions(options(directory), directory));
109
+ track(directory);
110
+ const url = await mf.ready;
111
+ let disposed;
112
+ const started = mf;
113
+ return {
114
+ mf: started,
115
+ url,
116
+ directory,
117
+ dispose() {
118
+ disposed ??= started.dispose().finally(() => release(directory, remove));
119
+ return disposed;
120
+ },
121
+ };
122
+ }
123
+ catch (error) {
124
+ await mf?.dispose().catch(() => undefined);
125
+ await release(directory, remove);
126
+ throw error;
127
+ }
128
+ }
129
+ //# sourceMappingURL=storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/miniflare/storage.ts"],"names":[],"mappings":"AAAA;;;;GA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