@rexezuge/d1 1.6.1 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -60,7 +60,7 @@ try {
60
60
  import { decryptSecret, encryptSecret } from '@rexezuge/d1';
61
61
 
62
62
  const { ciphertext, iv } = await encryptSecret(clientSecret, env.BACKUP_ENCRYPTION_KEY); // store the pair
63
- const cleartext = await decryptSecret(ciphertext, iv, env.BACKUP_ENCRYPTION_KEY);
63
+ const cleartext = await decryptSecret({ ciphertext, iv }, env.BACKUP_ENCRYPTION_KEY);
64
64
  ```
65
65
 
66
66
  Key material is base64 of exactly 32 bytes; a missing or wrong-sized key throws `AesGcmKeyError` rather than storing the secret in the clear. The IV is random per call — reusing one under a key destroys GCM's guarantees, which is why it is returned alongside the ciphertext instead of being internal.
package/dist/BaseDAO.d.ts CHANGED
@@ -1,5 +1,53 @@
1
+ import type { SubrequestMeter } from '@rexezuge/shared';
1
2
  import { D1_RETRY_DEFAULTS } from './D1Retry.ts';
2
3
  import type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';
4
+ /**
5
+ * A prepared statement with the SQL that produced it.
6
+ *
7
+ * The platform's `D1PreparedStatement` carries no `sql` member, so a layer that
8
+ * needs to know *what* it is about to run — to account for a write, to assert a
9
+ * table's billing multiplier, to log a rejected statement in terms a reader can
10
+ * act on — has nowhere to read it from. Carrying it beside the statement is
11
+ * that place, and `bind()` returns a new pair for the same reason the platform's
12
+ * does: bindings are immutable on a prepared statement.
13
+ */
14
+ interface TrackedStatement {
15
+ sql: string;
16
+ statement: D1PreparedStatement;
17
+ bind(...bindings: unknown[]): TrackedStatement;
18
+ }
19
+ /**
20
+ * How many rows a write to `table` costs.
21
+ *
22
+ * A **port, not an implementation**, because the answer is a property of the
23
+ * schema rather than of this layer: D1 bills a write as the table row *plus
24
+ * every index entry it rewrote*, so the multiplier belongs to whoever owns the
25
+ * migrations. This package owns the accounting *shape* — carrying the figure
26
+ * beside `changes` on every write result — and the consumer supplies the table.
27
+ *
28
+ * Returning `null` means "I do not know this table", which is a different answer
29
+ * from "this costs one row" and must not collapse into it: an unknown table
30
+ * errs toward the worst case, because an under-count costs the outage.
31
+ */
32
+ type BilledRowsForTable = (table: string, logicalRows: number) => number | null;
33
+ /**
34
+ * What a write cost, and what it changed.
35
+ *
36
+ * `changes` is progress — how many table rows the statement touched — and
37
+ * `billedRows` is cost. They are not the same number and neither replaces the
38
+ * other: `changes` is what a convergence test measures, `billedRows` is what a
39
+ * daily-allowance budget must be spent against. A caller that reads only
40
+ * `changes` believes it has roughly an order of magnitude more headroom than it
41
+ * does on an indexed table.
42
+ *
43
+ * `billedRows` is `null` — absent, not zero — when no {@link BilledRowsForTable}
44
+ * port is configured, so the type forces the caller to notice that nothing is
45
+ * being accounted rather than reporting a confident `0`.
46
+ */
47
+ interface WriteResult {
48
+ changes: number;
49
+ billedRows: number | null;
50
+ }
3
51
  /**
4
52
  * Canonical DAO base: retry is a policy, methods are a promise.
5
53
  *
@@ -11,18 +59,72 @@ import type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';
11
59
  * each of the two shapes drifted its own method names (`withRetry` vs
12
60
  * `run(sql, bindings)`); the sql-first form is what survived.
13
61
  *
62
+ * ### Every statement is charged
63
+ *
64
+ * D1 counts its own queries against the Workers per-invocation subrequest
65
+ * ceiling, so a statement that spends one without telling anybody makes every
66
+ * number that budgets work wrong — and it has **no symptom** until the platform
67
+ * terminates the invocation, by which point the rows were right and the suite
68
+ * was green. The meter is therefore a constructor dependency rather than a
69
+ * module singleton, and the charge happens here because this is the one path
70
+ * every statement takes; a charge at each call site is a hundred chances to
71
+ * forget one.
72
+ *
73
+ * The charge is **per logical statement, not per attempt**: a retried statement
74
+ * is one statement that the platform refused once and then answered. Charging
75
+ * per attempt would make the ceiling track the fault rate instead of the work.
76
+ *
14
77
  * Non-DAO concerns stay out: cursor pagination lives in `@rexezuge/shared`
15
- * (`CursorCodec`), subrequest accounting is an injectable port. Retry policy
16
- * lives in `D1Retry` — one schedule, one classifier, one place the
17
- * `Failed to <context>` prefix is added.
78
+ * (`CursorCodec`). Retry policy lives in `D1Retry` — one schedule, one
79
+ * classifier, one place the `Failed to <context>` prefix is added.
18
80
  */
19
81
  declare abstract class BaseDAO {
20
82
  protected readonly database: D1Queryable;
21
- protected constructor(database: D1Queryable);
83
+ protected readonly meter: SubrequestMeter;
84
+ private readonly options;
85
+ /**
86
+ * Public, and deliberately so.
87
+ *
88
+ * A composition root instantiates concrete DAOs directly — that is the whole
89
+ * point of a DI container, which binds `() => new UserDAO(db)` rather than
90
+ * handing the container a factory that hides the construction. A `protected`
91
+ * constructor blocks that and buys nothing: the class is `abstract`, so nobody
92
+ * can instantiate `BaseDAO` itself regardless, and the access modifier
93
+ * prevented exactly zero illegal constructions while forcing every concrete
94
+ * DAO to redeclare a pass-through constructor that added no invariant.
95
+ *
96
+ * It was `protected` to keep `database` from being reached as
97
+ * `BaseDAO.database` — but every field below carries its own `protected`, so
98
+ * the field's own modifier is what enforces that, and making the constructor
99
+ * public does not weaken it.
100
+ *
101
+ * @param database The binding.
102
+ * @param meter The invocation's subrequest counter, or an unmetered default.
103
+ * @param options `billedRowsForTable` supplies the schema's write cost.
104
+ */
105
+ constructor(database: D1Queryable, meter?: SubrequestMeter, options?: {
106
+ billedRowsForTable?: BilledRowsForTable;
107
+ });
108
+ /**
109
+ * The invocation's meter, for a DAO that constructs another DAO.
110
+ *
111
+ * A `protected get` rather than a public field, because handing the meter out
112
+ * is how a DAO builds a collaborator correctly: `new SongIdLookupDAO(this.database)`
113
+ * drops it, and the charge that goes missing has no symptom.
114
+ */
115
+ protected get subrequests(): SubrequestMeter;
22
116
  /**
23
117
  A prepared statement with its bindings applied. Bindings are always parameters, never interpolation.
24
118
  */
25
119
  protected statement(sql: string, bindings?: unknown[]): D1PreparedStatement;
120
+ /**
121
+ * The same statement, carrying the SQL beside it.
122
+ *
123
+ * Use this wherever the SQL matters downstream — a write whose cost is
124
+ * accounted, a statement named in an error — and {@link statement} for reads,
125
+ * where nothing reads the SQL back and the pair is one allocation of waste.
126
+ */
127
+ protected tracked(sql: string, bindings?: unknown[]): TrackedStatement;
26
128
  /**
27
129
  * Run a statement. D1 reports a constraint violation or a missing table by
28
130
  * returning `success: false` rather than by throwing, so both forms are
@@ -31,13 +133,13 @@ declare abstract class BaseDAO {
31
133
  */
32
134
  protected run(sql: string, bindings?: unknown[]): Promise<D1Result>;
33
135
  /**
34
- * Read one row. A `null` result is "no row", a success, not an error; only a
35
- * rejected statement is retried and normalized.
36
- *
37
- * `null` rather than `undefined` because that is what the platform says
38
- * (`D1Result.first<T>()` returns `T | null`) and an adapter should hand back
39
- * what it was given. It also makes this layer agree with `KvCache`, which has
40
- * always returned `null` for a miss, so one convention covers both.
136
+ Read one row. A `null` result is "no row", a success, not an error; only a
137
+ rejected statement is retried and normalized.
138
+
139
+ `null` rather than `undefined` because that is what the platform says
140
+ (`D1Result.first<T>()` returns `T | null`) and an adapter should hand back
141
+ what it was given. It also makes this layer agree with `KvCache`, which has
142
+ always returned `null` for a miss, so one convention covers both.
41
143
  */
42
144
  protected first<T>(sql: string, bindings?: unknown[]): Promise<T | null>;
43
145
  /**
@@ -54,6 +156,48 @@ declare abstract class BaseDAO {
54
156
  * failure inside the batch raises rather than passing silently.
55
157
  */
56
158
  protected batch(statements: D1PreparedStatement[]): Promise<D1Result[]>;
159
+ /**
160
+ * Run one write and report what it cost.
161
+ *
162
+ * Takes a {@link TrackedStatement} rather than SQL because the cost is read off
163
+ * the table the SQL names, and the SQL is only available if it was carried.
164
+ * `billedRows` is `null` when no port is configured.
165
+ */
166
+ protected runTracked(tracked: TrackedStatement): Promise<WriteResult>;
167
+ /**
168
+ * Run a batch of writes and report what the whole batch cost.
169
+ *
170
+ * Billed rows are **summed across the batch**, and an unaccountable statement
171
+ * poisons the total to `null` rather than being skipped: a partial figure next
172
+ * to a real one is the one that reads as complete.
173
+ */
174
+ protected runTrackedBatch(tracked: readonly TrackedStatement[]): Promise<WriteResult>;
175
+ /**
176
+ * The writes these statements fit into the invocation's remaining budget.
177
+ *
178
+ * "How many may I issue", as distinct from {@link assertSubrequestBudget}'s
179
+ * "may I issue all of these" — a caller truncating a work list needs the
180
+ * number, and a caller that must not truncate needs the refusal. An unmetered
181
+ * counter answers `Infinity`, so a deployment that does not meter is never
182
+ * clamped by a budget it does not have.
183
+ */
184
+ protected fitToSubrequestBudget(requested: number): number;
185
+ /**
186
+ * Refuse a set of statements the invocation's remaining budget cannot carry.
187
+ *
188
+ * For a write with no partial form — a play queue, a playlist's count, a
189
+ * backfill — because half a queue is a _shorter_ queue, which is a wrong
190
+ * answer rather than an unfinished one. A caller that may truncate uses
191
+ * {@link fitToSubrequestBudget} instead and reports that it did.
192
+ *
193
+ * @param statements How many statements the work needs.
194
+ * @param context Named in the refusal, because this reaches a client as a 413.
195
+ */
196
+ protected assertSubrequestBudget(statements: number, context?: string): void;
197
+ /**
198
+ * Charge the meter and account a completed write against the schema's cost.
199
+ */
200
+ private accountWrite;
57
201
  /**
58
202
  * Generic batched delete of rows older than a cutoff, in ID order, with
59
203
  * retry. Mirrors the per-DAO `DELETE ... WHERE id IN (SELECT ... LIMIT ?)`
@@ -72,5 +216,18 @@ declare abstract class BaseDAO {
72
216
  * parameter binding cannot express.
73
217
  */
74
218
  declare function assertSqlIdentifier(value: string, label: string): void;
75
- export { BaseDAO, assertSqlIdentifier };
219
+ /**
220
+ * The write verb's table name, or `null` when the SQL does not name one.
221
+ *
222
+ * The verb is anchored at the **start** of the statement, after leading
223
+ * whitespace and comments — a bare `/\bINSERT\s+INTO\s+(\w+)/` also matches a
224
+ * verb quoted inside a string literal, and a table read out of a `SELECT`'s
225
+ * projection is worse than no answer at all. An unreadable statement returns
226
+ * `null` for the caller to charge the worst case against, rather than throwing:
227
+ * accounting must not be the thing that turns a failed write into a crashed
228
+ * request.
229
+ */
230
+ declare function statementTable(sql: string): string | null;
231
+ export { BaseDAO, assertSqlIdentifier, statementTable };
232
+ export type { BilledRowsForTable, TrackedStatement, WriteResult };
76
233
  //# sourceMappingURL=BaseDAO.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDAO.d.ts","sourceRoot":"","sources":["../src/BaseDAO.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAoB,MAAM,cAAc,CAAC;AACnE,OAAO,KAAK,EAAE,mBAAmB,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAU/E;;;;;;;;;;;;;;;GAeG;AACH,uBAAe,OAAO;IACE,SAAS,CAAC,QAAQ,CAAC,QAAQ,EAAE,WAAW;IAA9D,SAAS,aAAgC,QAAQ,EAAE,WAAW;IAE9D;;MAEE;IACF,SAAS,CAAC,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,GAAE,OAAO,EAAO,GAAG,mBAAmB;IAI/E;;;;;OAKG;cACa,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,GAAE,OAAO,EAAO,GAAG,OAAO,CAAC,QAAQ,CAAC;IAI7E;;;;;;;;OAQG;cACa,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,GAAE,OAAO,EAAO,GAAG,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;IAQlF;;MAEE;cACc,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,GAAE,OAAO,EAAO,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC;IAQ3E;;MAEE;cACc,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,GAAE,OAAO,EAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAK7E;;;;OAIG;cACa,KAAK,CAAC,UAAU,EAAE,mBAAmB,EAAE,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;IAa7E;;;;;OAKG;qBACoB,eAAe,CACpC,EAAE,EAAE,WAAW,EACf,KAAK,EAA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,GAAG,OAAO,CAAC,WAAW,CAAC;IAqB3F;;;;;;;;OAQG;IACH,SAAS,CAAC,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM;IAK1D;;;;;;;;;;OAUG;IACH,SAAS,CAAC,sBAAsB,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,SAAiB,GAAG,IAAI;IAOpF;;OAEG;IACH,OAAO,CAAC,YAAY;IAOpB;;;;;OAKG;qBACoB,eAAe,CACpC,EAAE,EAAE,WAAW,EACf,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GAAG,MAAM,EACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,CAAC;IAsBlB;;MAEE;IACF,SAAS,CAAC,MAAM,KAAK,aAAa,IAAI,OAAO,iBAAiB,CAE7D;CACF;AAED;;;;GAIG;AACH,iBAAS,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAI/D;AAMD;;;;;;;;;;GAUG;AACH,iBAAS,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAqBlD;AAUD,OAAO,EAAE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,CAAC;AACxD,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,WAAW,EAAE,CAAC"}
package/dist/BaseDAO.js CHANGED
@@ -1,6 +1,7 @@
1
- var l=Object.defineProperty;var u=(s,e)=>l(s,"name",{value:e,configurable:!0});import{DatabaseError as h}from"@rexezuge/errors";import{D1_RETRY_DEFAULTS as w,executeWithRetry as n}from"./D1Retry.js";class d{static{u(this,"BaseDAO")}database;constructor(e){this.database=e}statement(e,t=[]){return t.length>0?this.database.prepare(e).bind(...t):this.database.prepare(e)}async run(e,t=[]){return n(()=>this.statement(e,t).run(),"run statement")}async first(e,t=[]){return(await n(async()=>({success:!0,value:await this.statement(e,t).first()}),"read a row")).value}async all(e,t=[]){return(await n(async()=>({success:!0,value:(await this.statement(e,t).all()).results??[]}),"read rows")).value}async count(e,t=[]){return(await this.first(e,t))?.count??0}async batch(e){if(e.length===0)return[];if(this.database.batch===void 0)throw new h("The D1 binding exposes no batch() \u2014 a multi-statement transaction is not available here");return(await n(async()=>{const r=await this.database.batch(e),a=r.find(o=>!o.success);return{success:a===void 0,error:a?.error,value:r}},"run a batch")).value}static async deleteOlderThan(e,t,r,a,o,c){return i(t,"table"),i(r,"timeColumn"),i(c,"idColumn"),(await n(()=>e.prepare(`DELETE FROM ${t}
2
- WHERE ${c} IN (
3
- SELECT ${c} FROM ${t}
1
+ var b=Object.defineProperty;var i=(s,e)=>b(s,"name",{value:e,configurable:!0});import{UNMETERED_SUBREQUESTS as p}from"@rexezuge/shared";import{SubrequestBudgetExhaustedError as E}from"@rexezuge/errors";import{DatabaseError as g}from"@rexezuge/errors";import{D1_RETRY_DEFAULTS as R,executeWithRetry as c}from"./D1Retry.js";class T{static{i(this,"BaseDAO")}database;meter;options;constructor(e,t=p,r={}){this.database=e,this.meter=t,this.options=r}get subrequests(){return this.meter}statement(e,t=[]){return t.length>0?this.database.prepare(e).bind(...t):this.database.prepare(e)}tracked(e,t=[]){const r=i(n=>({sql:e,statement:n,bind:i((...o)=>r(n.bind(...o)),"bind")}),"make");return r(this.statement(e,t))}async run(e,t=[]){return this.meter.charge(1,"d1"),c(()=>this.statement(e,t).run(),"run statement")}async first(e,t=[]){return this.meter.charge(1,"d1"),(await c(async()=>({success:!0,value:await this.statement(e,t).first()}),"read a row")).value}async all(e,t=[]){return this.meter.charge(1,"d1"),(await c(async()=>({success:!0,value:(await this.statement(e,t).all()).results??[]}),"read rows")).value}async count(e,t=[]){return(await this.first(e,t))?.count??0}async batch(e){if(e.length===0)return[];if(this.meter.charge(1,"d1"),this.database.batch===void 0)throw new g("The D1 binding exposes no batch() \u2014 a multi-statement transaction is not available here");return(await c(async()=>{const r=await this.database.batch(e),n=r.find(o=>!o.success);return{success:n===void 0,error:n?.error,value:r}},"run a batch")).value}async runTracked(e){const t=await c(()=>e.statement.run(),"run a write");return this.accountWrite(e.sql,t)}async runTrackedBatch(e){const t=await this.batch(e.map(a=>a.statement));let r=0,n=this.options.billedRowsForTable!==void 0;for(const[a,u]of t.entries()){const d=e[a];if(!d){n=!1;break}const f=this.accountWrite(d.sql,u);if(f.billedRows===null){n=!1;break}r+=f.billedRows}return{changes:t.reduce((a,u)=>a+m(u),0),billedRows:n?r:null}}fitToSubrequestBudget(e){const t=this.meter.remaining;return Number.isFinite(t)?Math.max(0,Math.min(e,Math.floor(t))):Math.max(0,e)}assertSubrequestBudget(e,t="this request"){if(!this.meter.canAfford(e))throw new E(`${t} needs ${e} database operations and this invocation has ${this.meter.remaining} left. Send fewer items at once.`)}accountWrite(e,t){const r=m(t),n=this.options.billedRowsForTable;return n?{changes:r,billedRows:n(w(e)??"",r)}:{changes:r,billedRows:null}}static async deleteOlderThan(e,t,r,n,o,a){return l(t,"table"),l(r,"timeColumn"),l(a,"idColumn"),(await c(()=>e.prepare(`DELETE FROM ${t}
2
+ WHERE ${a} IN (
3
+ SELECT ${a} FROM ${t}
4
4
  WHERE ${r} < ?
5
5
  LIMIT ?
6
- )`).bind(a,o).run(),`delete old rows from ${t}`)).meta?.changes??0}static get retryDefaults(){return w}}function i(s,e){if(!/^[A-Z_]\w*$/i.test(s))throw new Error(`Unsafe SQL identifier for ${e}: ${JSON.stringify(s)}`)}u(i,"assertSqlIdentifier");export{d as BaseDAO,i as assertSqlIdentifier};
6
+ )`).bind(n,o).run(),`delete old rows from ${t}`)).meta?.changes??0}static get retryDefaults(){return R}}function l(s,e){if(!/^[A-Z_]\w*$/i.test(s))throw new Error(`Unsafe SQL identifier for ${e}: ${JSON.stringify(s)}`)}i(l,"assertSqlIdentifier");function m(s){return s.meta?.changes??0}i(m,"changesOf");function w(s){if(typeof s!="string")return null;let e=s.replace(/^\s+/,"");for(;e.startsWith("--");){const r=e.indexOf(`
7
+ `);if(r===-1)return null;e=e.slice(r+1).replace(/^\s+/,"")}const t=/^(?:INSERT|REPLACE|UPDATE|DELETE)\b/i.exec(e);return t?(e=h(e.slice(t[0].length)),e=h(e,/^(?:OR\s+[A-Z_]+\s+)?/i),e=h(e,/^(?:INTO\s+|FROM\s+)?/i),/^["`[]?([A-Z_]\w*)/i.exec(e)?.[1]??null):null}i(w,"statementTable");function h(s,e){const t=e?.exec(s)?.[0]??"";return s.slice(t.length).replace(/^\s+/,"")}i(h,"consume");export{T as BaseDAO,l as assertSqlIdentifier,w as statementTable};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/BaseDAO.ts"],
4
- "sourcesContent": ["import { DatabaseError } from '@rexezuge/errors';\nimport { D1_RETRY_DEFAULTS, executeWithRetry } from './D1Retry.ts';\nimport type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';\n\n/**\n * A statement result plus the payload it produced, so the retry engine (which\n * inspects `success`) also handles wrapped results like batch arrays.\n */\ninterface StatementEnvelope<T> extends D1Result {\n value: T;\n}\n\n/**\n * Canonical DAO base: retry is a policy, methods are a promise.\n *\n * Converged from the nine consumer repos' BaseDAOs. The API is the **sql-first**\n * shape CalDAV-Bridge and ChordDHT-Tracker used, not the closure-first shape\n * Durable-DAV's family used: a DAO states its SQL and bindings directly, and\n * the retry/normalization wrapper is invisible at the call site. The closure\n * form made every read site pay for a wrapper 90% of them never needed, and\n * each of the two shapes drifted its own method names (`withRetry` vs\n * `run(sql, bindings)`); the sql-first form is what survived.\n *\n * Non-DAO concerns stay out: cursor pagination lives in `@rexezuge/shared`\n * (`CursorCodec`), subrequest accounting is an injectable port. Retry policy\n * lives in `D1Retry` — one schedule, one classifier, one place the\n * `Failed to <context>` prefix is added.\n */\nabstract class BaseDAO {\n protected constructor(protected readonly database: D1Queryable) {}\n\n /**\n A prepared statement with its bindings applied. Bindings are always parameters, never interpolation.\n */\n protected statement(sql: string, bindings: unknown[] = []): D1PreparedStatement {\n return bindings.length > 0 ? this.database.prepare(sql).bind(...bindings) : this.database.prepare(sql);\n }\n\n /**\n * Run a statement. D1 reports a constraint violation or a missing table by\n * returning `success: false` rather than by throwing, so both forms are\n * normalized to a `DatabaseError` here — ignoring the result form is what\n * let a `UNIQUE` failure reach a caller as an opaque 500.\n */\n protected async run(sql: string, bindings: unknown[] = []): Promise<D1Result> {\n return executeWithRetry((): Promise<D1Result> => this.statement(sql, bindings).run(), 'run statement');\n }\n\n /**\n * Read one row. A `null` result is \"no row\", a success, not an error; only a\n * rejected statement is retried and normalized.\n *\n * `null` rather than `undefined` because that is what the platform says\n * (`D1Result.first<T>()` returns `T | null`) and an adapter should hand back\n * what it was given. It also makes this layer agree with `KvCache`, which has\n * always returned `null` for a miss, so one convention covers both.\n */\n protected async first<T>(sql: string, bindings: unknown[] = []): Promise<T | null> {\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T | null>> => {\n const row: T | null = await this.statement(sql, bindings).first<T>();\n return { success: true, value: row };\n }, 'read a row');\n return envelope.value;\n }\n\n /**\n A list read. `.all()` returning `[]` is a success like `first()`'s null.\n */\n protected async all<T>(sql: string, bindings: unknown[] = []): Promise<T[]> {\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T[]>> => {\n const rows = await this.statement(sql, bindings).all<T>();\n return { success: true, value: rows.results ?? [] };\n }, 'read rows');\n return envelope.value;\n }\n\n /**\n A scalar count from a `SELECT count(*)` row; 0 when absent.\n */\n protected async count(sql: string, bindings: unknown[] = []): Promise<number> {\n const row = await this.first<{ count: number }>(sql, bindings);\n return row?.count ?? 0;\n }\n\n /**\n * A batch of prepared statements — one transaction and one subrequest,\n * however many statements it carries. Each result is checked, so a single\n * failure inside the batch raises rather than passing silently.\n */\n protected async batch(statements: D1PreparedStatement[]): Promise<D1Result[]> {\n if (statements.length === 0) return [];\n if (this.database.batch === undefined) {\n throw new DatabaseError('The D1 binding exposes no batch() — a multi-statement transaction is not available here');\n }\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<D1Result[]>> => {\n const results: D1Result[] = await (this.database.batch as NonNullable<D1Queryable['batch']>)(statements);\n const failed: D1Result | undefined = results.find((result): boolean => !result.success);\n return { success: failed === undefined, error: failed?.error, value: results };\n }, 'run a batch');\n return envelope.value;\n }\n\n /**\n * Generic batched delete of rows older than a cutoff, in ID order, with\n * retry. Mirrors the per-DAO `DELETE ... WHERE id IN (SELECT ... LIMIT ?)`\n * pattern that every repo re-implemented per table. The cutoff is exclusive:\n * a delete never touches a row at exactly the boundary timestamp.\n */\n protected static async deleteOlderThan(\n db: D1Queryable,\n table: string,\n timeColumn: string,\n cutoff: number | string,\n limit: number,\n idColumn: string,\n ): Promise<number> {\n assertSqlIdentifier(table, 'table');\n assertSqlIdentifier(timeColumn, 'timeColumn');\n assertSqlIdentifier(idColumn, 'idColumn');\n const result: D1Result = await executeWithRetry(\n (): Promise<D1Result> =>\n db\n .prepare(\n `DELETE FROM ${table}\n WHERE ${idColumn} IN (\n SELECT ${idColumn} FROM ${table}\n WHERE ${timeColumn} < ?\n LIMIT ?\n )`,\n )\n .bind(cutoff, limit)\n .run(),\n `delete old rows from ${table}`,\n );\n return (result.meta as { changes?: number })?.changes ?? 0;\n }\n\n /**\n The retry schedule, for callers that surface it (health checks, tests).\n */\n protected static get retryDefaults(): typeof D1_RETRY_DEFAULTS {\n return D1_RETRY_DEFAULTS;\n }\n}\n\n/**\n * Allow-list one SQL identifier segment. Values never go through this — they\n * are always bound; this exists purely for the table/column names that\n * parameter binding cannot express.\n */\nfunction assertSqlIdentifier(value: string, label: string): void {\n if (!/^[A-Z_]\\w*$/i.test(value)) {\n throw new Error(`Unsafe SQL identifier for ${label}: ${JSON.stringify(value)}`);\n }\n}\n\nexport { BaseDAO, assertSqlIdentifier };\n"],
5
- "mappings": "+EAAA,OAAS,iBAAAA,MAAqB,mBAC9B,OAAS,qBAAAC,EAAmB,oBAAAC,MAAwB,eA2BpD,MAAeC,CAAO,CA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AClB,CAQU,aAAa,gBACrBG,EACAC,EACAC,EACAC,EACAC,EACAC,EAAgB,CAEhB,OAAAC,EAAoBL,EAAO,OAAO,EAClCK,EAAoBJ,EAAY,YAAY,EAC5CI,EAAoBD,EAAU,UAAU,GACf,MAAMf,EAC7B,IACEU,EACG,QACC,eAAeC,CAAK;qBACXI,CAAQ;wBACLA,CAAQ,SAASJ,CAAK;uBACvBC,CAAU;;eAElB,EAEJ,KAAKC,EAAQC,CAAK,EAClB,IAAG,EACR,wBAAwBH,CAAK,EAAE,GAElB,MAA+B,SAAW,CAC3D,CAKU,WAAW,eAAa,CAChC,OAAOZ,CACT,EAQF,SAASiB,EAAoBC,EAAeC,EAAa,CACvD,GAAI,CAAC,eAAe,KAAKD,CAAK,EAC5B,MAAM,IAAI,MAAM,6BAA6BC,CAAK,KAAK,KAAK,UAAUD,CAAK,CAAC,EAAE,CAElF,CAJSf,EAAAc,EAAA",
6
- "names": ["DatabaseError", "D1_RETRY_DEFAULTS", "executeWithRetry", "BaseDAO", "__name", "database", "sql", "bindings", "statements", "results", "failed", "result", "db", "table", "timeColumn", "cutoff", "limit", "idColumn", "assertSqlIdentifier", "value", "label"]
4
+ "sourcesContent": ["import { UNMETERED_SUBREQUESTS } from '@rexezuge/shared';\nimport type { SubrequestMeter } from '@rexezuge/shared';\nimport { SubrequestBudgetExhaustedError } from '@rexezuge/errors';\nimport { DatabaseError } from '@rexezuge/errors';\nimport { D1_RETRY_DEFAULTS, executeWithRetry } from './D1Retry.ts';\nimport type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';\n\n/**\n * A statement result plus the payload it produced, so the retry engine (which\n * inspects `success`) also handles wrapped results like batch arrays.\n */\ninterface StatementEnvelope<T> extends D1Result {\n value: T;\n}\n\n/**\n * A prepared statement with the SQL that produced it.\n *\n * The platform's `D1PreparedStatement` carries no `sql` member, so a layer that\n * needs to know *what* it is about to run — to account for a write, to assert a\n * table's billing multiplier, to log a rejected statement in terms a reader can\n * act on — has nowhere to read it from. Carrying it beside the statement is\n * that place, and `bind()` returns a new pair for the same reason the platform's\n * does: bindings are immutable on a prepared statement.\n */\ninterface TrackedStatement {\n sql: string;\n statement: D1PreparedStatement;\n bind(...bindings: unknown[]): TrackedStatement;\n}\n\n/**\n * How many rows a write to `table` costs.\n *\n * A **port, not an implementation**, because the answer is a property of the\n * schema rather than of this layer: D1 bills a write as the table row *plus\n * every index entry it rewrote*, so the multiplier belongs to whoever owns the\n * migrations. This package owns the accounting *shape* — carrying the figure\n * beside `changes` on every write result — and the consumer supplies the table.\n *\n * Returning `null` means \"I do not know this table\", which is a different answer\n * from \"this costs one row\" and must not collapse into it: an unknown table\n * errs toward the worst case, because an under-count costs the outage.\n */\ntype BilledRowsForTable = (table: string, logicalRows: number) => number | null;\n\n/**\n * What a write cost, and what it changed.\n *\n * `changes` is progress — how many table rows the statement touched — and\n * `billedRows` is cost. They are not the same number and neither replaces the\n * other: `changes` is what a convergence test measures, `billedRows` is what a\n * daily-allowance budget must be spent against. A caller that reads only\n * `changes` believes it has roughly an order of magnitude more headroom than it\n * does on an indexed table.\n *\n * `billedRows` is `null` — absent, not zero — when no {@link BilledRowsForTable}\n * port is configured, so the type forces the caller to notice that nothing is\n * being accounted rather than reporting a confident `0`.\n */\ninterface WriteResult {\n changes: number;\n billedRows: number | null;\n}\n\n/**\n * Canonical DAO base: retry is a policy, methods are a promise.\n *\n * Converged from the nine consumer repos' BaseDAOs. The API is the **sql-first**\n * shape CalDAV-Bridge and ChordDHT-Tracker used, not the closure-first shape\n * Durable-DAV's family used: a DAO states its SQL and bindings directly, and\n * the retry/normalization wrapper is invisible at the call site. The closure\n * form made every read site pay for a wrapper 90% of them never needed, and\n * each of the two shapes drifted its own method names (`withRetry` vs\n * `run(sql, bindings)`); the sql-first form is what survived.\n *\n * ### Every statement is charged\n *\n * D1 counts its own queries against the Workers per-invocation subrequest\n * ceiling, so a statement that spends one without telling anybody makes every\n * number that budgets work wrong — and it has **no symptom** until the platform\n * terminates the invocation, by which point the rows were right and the suite\n * was green. The meter is therefore a constructor dependency rather than a\n * module singleton, and the charge happens here because this is the one path\n * every statement takes; a charge at each call site is a hundred chances to\n * forget one.\n *\n * The charge is **per logical statement, not per attempt**: a retried statement\n * is one statement that the platform refused once and then answered. Charging\n * per attempt would make the ceiling track the fault rate instead of the work.\n *\n * Non-DAO concerns stay out: cursor pagination lives in `@rexezuge/shared`\n * (`CursorCodec`). Retry policy lives in `D1Retry` — one schedule, one\n * classifier, one place the `Failed to <context>` prefix is added.\n */\nabstract class BaseDAO {\n /**\n * Public, and deliberately so.\n *\n * A composition root instantiates concrete DAOs directly — that is the whole\n * point of a DI container, which binds `() => new UserDAO(db)` rather than\n * handing the container a factory that hides the construction. A `protected`\n * constructor blocks that and buys nothing: the class is `abstract`, so nobody\n * can instantiate `BaseDAO` itself regardless, and the access modifier\n * prevented exactly zero illegal constructions while forcing every concrete\n * DAO to redeclare a pass-through constructor that added no invariant.\n *\n * It was `protected` to keep `database` from being reached as\n * `BaseDAO.database` — but every field below carries its own `protected`, so\n * the field's own modifier is what enforces that, and making the constructor\n * public does not weaken it.\n *\n * @param database The binding.\n * @param meter The invocation's subrequest counter, or an unmetered default.\n * @param options `billedRowsForTable` supplies the schema's write cost.\n */\n constructor(\n protected readonly database: D1Queryable,\n protected readonly meter: SubrequestMeter = UNMETERED_SUBREQUESTS,\n private readonly options: { billedRowsForTable?: BilledRowsForTable } = {},\n ) {}\n\n /**\n * The invocation's meter, for a DAO that constructs another DAO.\n *\n * A `protected get` rather than a public field, because handing the meter out\n * is how a DAO builds a collaborator correctly: `new SongIdLookupDAO(this.database)`\n * drops it, and the charge that goes missing has no symptom.\n */\n protected get subrequests(): SubrequestMeter {\n return this.meter;\n }\n\n /**\n A prepared statement with its bindings applied. Bindings are always parameters, never interpolation.\n */\n protected statement(sql: string, bindings: unknown[] = []): D1PreparedStatement {\n return bindings.length > 0 ? this.database.prepare(sql).bind(...bindings) : this.database.prepare(sql);\n }\n\n /**\n * The same statement, carrying the SQL beside it.\n *\n * Use this wherever the SQL matters downstream — a write whose cost is\n * accounted, a statement named in an error — and {@link statement} for reads,\n * where nothing reads the SQL back and the pair is one allocation of waste.\n */\n protected tracked(sql: string, bindings: unknown[] = []): TrackedStatement {\n const make = (prepared: D1PreparedStatement): TrackedStatement => ({\n sql,\n statement: prepared,\n bind: (...next: unknown[]): TrackedStatement => make(prepared.bind(...next)),\n });\n return make(this.statement(sql, bindings));\n }\n\n /**\n * Run a statement. D1 reports a constraint violation or a missing table by\n * returning `success: false` rather than by throwing, so both forms are\n * normalized to a `DatabaseError` here — ignoring the result form is what\n * let a `UNIQUE` failure reach a caller as an opaque 500.\n */\n protected async run(sql: string, bindings: unknown[] = []): Promise<D1Result> {\n this.meter.charge(1, 'd1');\n return executeWithRetry((): Promise<D1Result> => this.statement(sql, bindings).run(), 'run statement');\n }\n\n /**\n Read one row. A `null` result is \"no row\", a success, not an error; only a\n rejected statement is retried and normalized.\n\n `null` rather than `undefined` because that is what the platform says\n (`D1Result.first<T>()` returns `T | null`) and an adapter should hand back\n what it was given. It also makes this layer agree with `KvCache`, which has\n always returned `null` for a miss, so one convention covers both.\n */\n protected async first<T>(sql: string, bindings: unknown[] = []): Promise<T | null> {\n this.meter.charge(1, 'd1');\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T | null>> => {\n const row: T | null = await this.statement(sql, bindings).first<T>();\n return { success: true, value: row };\n }, 'read a row');\n return envelope.value;\n }\n\n /**\n A list read. `.all()` returning `[]` is a success like `first()`'s null.\n */\n protected async all<T>(sql: string, bindings: unknown[] = []): Promise<T[]> {\n this.meter.charge(1, 'd1');\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T[]>> => {\n const rows = await this.statement(sql, bindings).all<T>();\n return { success: true, value: rows.results ?? [] };\n }, 'read rows');\n return envelope.value;\n }\n\n /**\n A scalar count from a `SELECT count(*)` row; 0 when absent.\n */\n protected async count(sql: string, bindings: unknown[] = []): Promise<number> {\n const row = await this.first<{ count: number }>(sql, bindings);\n return row?.count ?? 0;\n }\n\n /**\n * A batch of prepared statements — one transaction and one subrequest,\n * however many statements it carries. Each result is checked, so a single\n * failure inside the batch raises rather than passing silently.\n */\n protected async batch(statements: D1PreparedStatement[]): Promise<D1Result[]> {\n if (statements.length === 0) return [];\n this.meter.charge(1, 'd1');\n if (this.database.batch === undefined) {\n throw new DatabaseError('The D1 binding exposes no batch() — a multi-statement transaction is not available here');\n }\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<D1Result[]>> => {\n const results: D1Result[] = await (this.database.batch as NonNullable<D1Queryable['batch']>)(statements);\n const failed: D1Result | undefined = results.find((result): boolean => !result.success);\n return { success: failed === undefined, error: failed?.error, value: results };\n }, 'run a batch');\n return envelope.value;\n }\n\n /**\n * Run one write and report what it cost.\n *\n * Takes a {@link TrackedStatement} rather than SQL because the cost is read off\n * the table the SQL names, and the SQL is only available if it was carried.\n * `billedRows` is `null` when no port is configured.\n */\n protected async runTracked(tracked: TrackedStatement): Promise<WriteResult> {\n const result = await executeWithRetry((): Promise<D1Result> => tracked.statement.run(), 'run a write');\n return this.accountWrite(tracked.sql, result);\n }\n\n /**\n * Run a batch of writes and report what the whole batch cost.\n *\n * Billed rows are **summed across the batch**, and an unaccountable statement\n * poisons the total to `null` rather than being skipped: a partial figure next\n * to a real one is the one that reads as complete.\n */\n protected async runTrackedBatch(tracked: readonly TrackedStatement[]): Promise<WriteResult> {\n const results = await this.batch(tracked.map((entry) => entry.statement));\n let billedRows = 0;\n let accounted = this.options.billedRowsForTable !== undefined;\n for (const [index, result] of results.entries()) {\n const entry = tracked[index];\n if (!entry) {\n accounted = false;\n break;\n }\n const one = this.accountWrite(entry.sql, result);\n if (one.billedRows === null) {\n accounted = false;\n break;\n }\n billedRows += one.billedRows;\n }\n const changes = results.reduce((total, result) => total + changesOf(result), 0);\n return { changes, billedRows: accounted ? billedRows : null };\n }\n\n /**\n * The writes these statements fit into the invocation's remaining budget.\n *\n * \"How many may I issue\", as distinct from {@link assertSubrequestBudget}'s\n * \"may I issue all of these\" — a caller truncating a work list needs the\n * number, and a caller that must not truncate needs the refusal. An unmetered\n * counter answers `Infinity`, so a deployment that does not meter is never\n * clamped by a budget it does not have.\n */\n protected fitToSubrequestBudget(requested: number): number {\n const remaining = this.meter.remaining;\n return Number.isFinite(remaining) ? Math.max(0, Math.min(requested, Math.floor(remaining))) : Math.max(0, requested);\n }\n\n /**\n * Refuse a set of statements the invocation's remaining budget cannot carry.\n *\n * For a write with no partial form — a play queue, a playlist's count, a\n * backfill — because half a queue is a _shorter_ queue, which is a wrong\n * answer rather than an unfinished one. A caller that may truncate uses\n * {@link fitToSubrequestBudget} instead and reports that it did.\n *\n * @param statements How many statements the work needs.\n * @param context Named in the refusal, because this reaches a client as a 413.\n */\n protected assertSubrequestBudget(statements: number, context = 'this request'): void {\n if (this.meter.canAfford(statements)) return;\n throw new SubrequestBudgetExhaustedError(\n `${context} needs ${statements} database operations and this invocation has ${this.meter.remaining} left. Send fewer items at once.`,\n );\n }\n\n /**\n * Charge the meter and account a completed write against the schema's cost.\n */\n private accountWrite(sql: string, result: D1Result): WriteResult {\n const changes = changesOf(result);\n const port = this.options.billedRowsForTable;\n if (!port) return { changes, billedRows: null };\n return { changes, billedRows: port(statementTable(sql) ?? '', changes) };\n }\n\n /**\n * Generic batched delete of rows older than a cutoff, in ID order, with\n * retry. Mirrors the per-DAO `DELETE ... WHERE id IN (SELECT ... LIMIT ?)`\n * pattern that every repo re-implemented per table. The cutoff is exclusive:\n * a delete never touches a row at exactly the boundary timestamp.\n */\n protected static async deleteOlderThan(\n db: D1Queryable,\n table: string,\n timeColumn: string,\n cutoff: number | string,\n limit: number,\n idColumn: string,\n ): Promise<number> {\n assertSqlIdentifier(table, 'table');\n assertSqlIdentifier(timeColumn, 'timeColumn');\n assertSqlIdentifier(idColumn, 'idColumn');\n const result: D1Result = await executeWithRetry(\n (): Promise<D1Result> =>\n db\n .prepare(\n `DELETE FROM ${table}\n WHERE ${idColumn} IN (\n SELECT ${idColumn} FROM ${table}\n WHERE ${timeColumn} < ?\n LIMIT ?\n )`,\n )\n .bind(cutoff, limit)\n .run(),\n `delete old rows from ${table}`,\n );\n return (result.meta as { changes?: number })?.changes ?? 0;\n }\n\n /**\n The retry schedule, for callers that surface it (health checks, tests).\n */\n protected static get retryDefaults(): typeof D1_RETRY_DEFAULTS {\n return D1_RETRY_DEFAULTS;\n }\n}\n\n/**\n * Allow-list one SQL identifier segment. Values never go through this — they\n * are always bound; this exists purely for the table/column names that\n * parameter binding cannot express.\n */\nfunction assertSqlIdentifier(value: string, label: string): void {\n if (!/^[A-Z_]\\w*$/i.test(value)) {\n throw new Error(`Unsafe SQL identifier for ${label}: ${JSON.stringify(value)}`);\n }\n}\n\nfunction changesOf(result: D1Result): number {\n return (result.meta as { changes?: number })?.changes ?? 0;\n}\n\n/**\n * The write verb's table name, or `null` when the SQL does not name one.\n *\n * The verb is anchored at the **start** of the statement, after leading\n * whitespace and comments — a bare `/\\bINSERT\\s+INTO\\s+(\\w+)/` also matches a\n * verb quoted inside a string literal, and a table read out of a `SELECT`'s\n * projection is worse than no answer at all. An unreadable statement returns\n * `null` for the caller to charge the worst case against, rather than throwing:\n * accounting must not be the thing that turns a failed write into a crashed\n * request.\n */\nfunction statementTable(sql: string): string | null {\n if (typeof sql !== 'string') return null;\n let rest = sql.replace(/^\\s+/, '');\n // A `while` rather than a repeated strip: comments are the only noise, and a\n // bounded loop cannot be made quadratic by a statement full of them.\n while (rest.startsWith('--')) {\n const newline = rest.indexOf('\\n');\n if (newline === -1) return null;\n rest = rest.slice(newline + 1).replace(/^\\s+/, '');\n }\n const verb = /^(?:INSERT|REPLACE|UPDATE|DELETE)\\b/i.exec(rest);\n if (!verb) return null;\n rest = consume(rest.slice(verb[0].length));\n\n // `INSERT OR REPLACE`, `UPDATE OR IGNORE` — a conflict clause between the verb and\n // the table. This is why the parse is stepwise rather than one anchored pattern:\n // a single pattern either grows a nested quantifier the complexity gate rejects,\n // or drops the clause and reads `REPLACE` as a table name.\n rest = consume(rest, /^(?:OR\\s+[A-Z_]+\\s+)?/i);\n rest = consume(rest, /^(?:INTO\\s+|FROM\\s+)?/i);\n return /^[\"`[]?([A-Z_]\\w*)/i.exec(rest)?.[1] ?? null;\n}\n\n/**\n * Drop a leading match and the whitespace after it.\n */\nfunction consume(sql: string, pattern?: RegExp): string {\n const matched = pattern?.exec(sql)?.[0] ?? '';\n return sql.slice(matched.length).replace(/^\\s+/, '');\n}\n\nexport { BaseDAO, assertSqlIdentifier, statementTable };\nexport type { BilledRowsForTable, TrackedStatement, WriteResult };\n"],
5
+ "mappings": "+EAAA,OAAS,yBAAAA,MAA6B,mBAEtC,OAAS,kCAAAC,MAAsC,mBAC/C,OAAS,iBAAAC,MAAqB,mBAC9B,OAAS,qBAAAC,EAAmB,oBAAAC,MAAwB,eA2FpD,MAAeC,CAAO,CA/FtB,MA+FsB,CAAAC,EAAA,gBAsBC,SACA,MACF,QAHnB,YACqBC,EACAC,EAAyBR,EAC3BS,EAAuD,CAAA,EAAE,CAFvD,KAAA,SAAAF,EACA,KAAA,MAAAC,EACF,KAAA,QAAAC,CAChB,CASH,IAAc,aAAW,CACvB,OAAO,KAAK,KACd,CAKU,UAAUC,EAAaC,EAAsB,CAAA,EAAE,CACvD,OAAOA,EAAS,OAAS,EAAI,KAAK,SAAS,QAAQD,CAAG,EAAE,KAAK,GAAGC,CAAQ,EAAI,KAAK,SAAS,QAAQD,CAAG,CACvG,CASU,QAAQA,EAAaC,EAAsB,CAAA,EAAE,CACrD,MAAMC,EAAON,EAACO,IAAqD,CACjE,IAAAH,EACA,UAAWG,EACX,KAAMP,EAAA,IAAIQ,IAAsCF,EAAKC,EAAS,KAAK,GAAGC,CAAI,CAAC,EAArE,UAHK,QAKb,OAAOF,EAAK,KAAK,UAAUF,EAAKC,CAAQ,CAAC,CAC3C,CAQU,MAAM,IAAID,EAAaC,EAAsB,CAAA,EAAE,CACvD,YAAK,MAAM,O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K,GAC3C,OAAOA,EAAI,MAAMqC,EAAQ,MAAM,EAAE,QAAQ,OAAQ,EAAE,CACrD,CAHSzC,EAAAuC,EAAA",
6
+ "names": ["UNMETERED_SUBREQUESTS", "SubrequestBudgetExhaustedError", "DatabaseError", "D1_RETRY_DEFAULTS", "executeWithRetry", "BaseDAO", "__name", "database", "meter", "options", "sql", "bindings", "make", "prepared", "next", "statements", "results", "failed", "result", "tracked", "entry", "billedRows", "accounted", "index", "one", "total", "changesOf", "requested", "remaining", "context", "changes", "port", "statementTable", "db", "table", "timeColumn", "cutoff", "limit", "idColumn", "assertSqlIdentifier", "value", "label", "rest", "newline", "verb", "consume", "pattern", "matched"]
7
7
  }
@@ -26,6 +26,68 @@ declare const RETRYABLE_PATTERNS: RegExp[];
26
26
  * `/connection/i` now correctly claims first.
27
27
  */
28
28
  declare const NON_RETRYABLE_PATTERNS: RegExp[];
29
+ /**
30
+ * A bind-ceiling refusal, checked **before** both lists.
31
+ *
32
+ * `/too\s+many/i` is in the retryable list, and retryable is consulted first by
33
+ * design — so a row in the non-retryable list could never win this one. It has to
34
+ * be its own pre-check for the same reason `DAILY_LIMIT_PATTERN` is: the defect
35
+ * is a query shape, not a fault. `too many SQL variables` fails identically for
36
+ * ever, and retrying it three times with backoff turns a one-line batching fix
37
+ * into a multi-second stall on every page that hits it.
38
+ */
39
+ declare const BIND_CEILING_PATTERN: RegExp;
40
+ /**
41
+ * Cloudflare's daily-allowance refusal, as it arrives.
42
+ *
43
+ * Matched on a substring rather than the whole sentence because the message
44
+ * reaches this layer **inside a wrapper** — `executeWithRetry` throws
45
+ * `Failed to <context>: <message>` — and a classifier that required the bare
46
+ * sentence would answer "not a quota" for a quota.
47
+ *
48
+ * The two words that identify it are `exceeded` and `daily`, and both are
49
+ * load-bearing. `too many` is deliberately **absent**, because a row that says
50
+ * "too many SQL variables" is a defect a repo ships guards for, not a spent
51
+ * allowance — treating that as a quota parks the work until midnight over a
52
+ * query one batching change fixes.
53
+ *
54
+ * The apostrophe accepts `’` as well as `'`. A message that arrives with a
55
+ * typographic apostrophe is still a spent allowance, and matching only the
56
+ * straight one answers "transient, retry" for a refusal that cannot change for
57
+ * hours — the failure this detector exists to prevent.
58
+ */
59
+ declare const DAILY_LIMIT_PATTERN: RegExp;
60
+ /**
61
+ * Which daily allowance is spent, and when it comes back.
62
+ *
63
+ * `resetsAt` is epoch milliseconds and is always **strictly in the future** for
64
+ * the clock it was computed from — including at exactly midnight, where the
65
+ * naive subtraction yields a time that has already passed. That case is not a
66
+ * rounding detail: a pause whose reset is in the past is a pause of zero length,
67
+ * and a chunk that returns immediately is a chunk that re-runs its whole failure
68
+ * path at the alarm's rate.
69
+ */
70
+ interface D1DailyLimit {
71
+ readonly kind: 'read' | 'write';
72
+ readonly resetsAt: number;
73
+ }
74
+ /**
75
+ * The next midnight UTC after `nowMs`, in epoch milliseconds.
76
+ *
77
+ * UTC and not local: the reset is UTC, so a local-time calculation is wrong
78
+ * twice a day — once by the offset, and once because the two midnights disagree.
79
+ */
80
+ declare function nextMidnightUtc(nowMs: number): number;
81
+ /**
82
+ * The spent daily allowance, or `null` for any other failure.
83
+ *
84
+ * `null` rather than `false` because the answer carries two facts, and a boolean
85
+ * forces every caller to recompute the reset time — which is exactly the second
86
+ * answer to one question, and the one that decides whether work resumes at
87
+ * midnight or immediately and fails again.
88
+ */
89
+ declare function isD1DailyLimitError(error: unknown, nowMs?: number): D1DailyLimit | null;
29
90
  declare function isD1ErrorRetryable(errorMessage: string): boolean;
30
- export { isD1ErrorRetryable, RETRYABLE_PATTERNS, NON_RETRYABLE_PATTERNS };
91
+ export { BIND_CEILING_PATTERN, DAILY_LIMIT_PATTERN, isD1DailyLimitError, isD1ErrorRetryable, nextMidnightUtc, RETRYABLE_PATTERNS, NON_RETRYABLE_PATTERNS, };
92
+ export type { D1DailyLimit };
31
93
  //# sourceMappingURL=D1ErrorClassifier.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"D1ErrorClassifier.d.ts","sourceRoot":"","sources":["../src/D1ErrorClassifier.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;;GAOG;AACH,QAAA,MAAM,kBAAkB,EAAE,MAAM,EAc/B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,QAAA,MAAM,sBAAsB,EAAE,MAAM,EAiBnC,CAAC;AAEF,iBAAS,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAmBzD;AAED,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,CAAC"}
1
+ {"version":3,"file":"D1ErrorClassifier.d.ts","sourceRoot":"","sources":["../src/D1ErrorClassifier.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;;GAOG;AACH,QAAA,MAAM,kBAAkB,EAAE,MAAM,EAc/B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,QAAA,MAAM,sBAAsB,EAAE,MAAM,EAiBnC,CAAC;AAEF;;;;;;;;;GASG;AACH,QAAA,MAAM,oBAAoB,QAA0E,CAAC;AAErG;;;;;;;;;;;;;;;;;;GAkBG;AACH,QAAA,MAAM,mBAAmB,QAA6E,CAAC;AAOvG;;;;;;;;;GASG;AACH,UAAU,YAAY;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IAChC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;GAKG;AACH,iBAAS,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAG9C;AAED;;;;;;;GAOG;AACH,iBAAS,mBAAmB,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,GAAE,MAAmB,GAAG,YAAY,GAAG,IAAI,CAK5F;AAED,iBAAS,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAiCzD;AAED,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,mBAAmB,EACnB,kBAAkB,EAClB,eAAe,EACf,kBAAkB,EAClB,sBAAsB,GACvB,CAAC;AACF,YAAY,EAAE,YAAY,EAAE,CAAC"}
@@ -1 +1 @@
1
- var o=Object.defineProperty;var n=(i,t)=>o(i,"name",{value:t,configurable:!0});const e=[/busy/i,/locked/i,/timeout/i,/timed?\s*out/i,/internal\s+(server\s+)?error/i,/connection/i,/network/i,/unavailable/i,/throttl/i,/too\s+many/i,/retry/i,/deadlock/i,/serialization/i],r=[/constraint/i,/\bunique\b/i,/primary\s+key/i,/foreign\s+key/i,/not\s+found/i,/\bsyntax\b/i,/parse\s+error/i,/no\s+such\s+(table|column|index)/i,/type\s+mismatch/i,/\bout\s+of\s+range\b/i,/invalid\s+argument/i,/\bpermission\b/i,/\bauthorization\b/i,/\bauthentication\b/i];function s(i){if(!i)return!1;for(const t of e)if(t.test(i))return!0;for(const t of r)if(t.test(i))return!1;return!1}n(s,"isD1ErrorRetryable");export{r as NON_RETRYABLE_PATTERNS,e as RETRYABLE_PATTERNS,s as isD1ErrorRetryable};
1
+ var f=Object.defineProperty;var e=(t,i)=>f(t,"name",{value:i,configurable:!0});const r=[/busy/i,/locked/i,/timeout/i,/timed?\s*out/i,/internal\s+(server\s+)?error/i,/connection/i,/network/i,/unavailable/i,/throttl/i,/too\s+many/i,/retry/i,/deadlock/i,/serialization/i],o=[/constraint/i,/\bunique\b/i,/primary\s+key/i,/foreign\s+key/i,/not\s+found/i,/\bsyntax\b/i,/parse\s+error/i,/no\s+such\s+(table|column|index)/i,/type\s+mismatch/i,/\bout\s+of\s+range\b/i,/invalid\s+argument/i,/\bpermission\b/i,/\bauthorization\b/i,/\bauthentication\b/i],a=/too\s+many\s+(?:SQL\s+)?(?:variables|bind\s+parameters|parameters)\b/i,n=/exceeded\s+D1['’]?s?\s+free\s+tier\s+daily\s+row\s+(read|write)\s+limit/i,m=864e5;function c(t){return t-t%864e5+864e5}e(c,"nextMidnightUtc");function l(t,i=Date.now()){const u=t instanceof Error?t.message:typeof t=="string"?t:"",s=n.exec(u);return s?{kind:s[1]?.toLowerCase()==="read"?"read":"write",resetsAt:c(i)}:null}e(l,"isD1DailyLimitError");function b(t){if(!t||n.test(t)||a.test(t))return!1;for(const i of r)if(i.test(t))return!0;for(const i of o)if(i.test(t))return!1;return!1}e(b,"isD1ErrorRetryable");export{a as BIND_CEILING_PATTERN,n as DAILY_LIMIT_PATTERN,o as NON_RETRYABLE_PATTERNS,r as RETRYABLE_PATTERNS,l as isD1DailyLimitError,b as isD1ErrorRetryable,c as nextMidnightUtc};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/D1ErrorClassifier.ts"],
4
- "sourcesContent": ["/**\n * Classify a raw D1 (or DO SQLite) error message as transient or permanent.\n *\n * Converged verbatim from Durable-DAV (and ChordDHT's byte-identical copy,\n * modulo the import scope) — the most-documented variant in the family.\n */\n\n/**\n * Patterns for a transient failure worth retrying.\n *\n * Checked **first**. A message matching both lists is treated as transient: one\n * wasted round trip against a real conflict is cheap, whereas mis-classifying a\n * blip as permanent turns a self-healing condition into a user-visible outage\n * that neither the DAO's retry nor the API's 503 mapping will cover.\n */\nconst RETRYABLE_PATTERNS: RegExp[] = [\n /busy/i,\n /locked/i,\n /timeout/i,\n /timed?\\s*out/i,\n /internal\\s+(server\\s+)?error/i,\n /connection/i,\n /network/i,\n /unavailable/i,\n /throttl/i,\n /too\\s+many/i,\n /retry/i,\n /deadlock/i,\n /serialization/i,\n];\n\n/**\n * Patterns for a failure that will not get better on its own.\n *\n * Every entry is deliberately **narrower than its obvious spelling**. This list\n * used to be consulted first and carried bare `/range/i` and `/not\\s+found/i`,\n * both of which match transient conditions:\n *\n * - `/range/i` matched `RangeError: Maximum call stack size exceeded` and\n * `byte range not satisfiable` — neither is a row-level conflict.\n * - `/not\\s+found/i` matched `host not found`, i.e. a DNS blip, which\n * `/connection/i` now correctly claims first.\n */\nconst NON_RETRYABLE_PATTERNS: RegExp[] = [\n /constraint/i,\n /\\bunique\\b/i,\n /primary\\s+key/i,\n /foreign\\s+key/i,\n /not\\s+found/i,\n /\\bsyntax\\b/i,\n /parse\\s+error/i,\n /no\\s+such\\s+(table|column|index)/i,\n /type\\s+mismatch/i,\n // Was `/range/i`, which also matched a stack-overflow `RangeError` and\n // \"byte range not satisfiable\".\n /\\bout\\s+of\\s+range\\b/i,\n /invalid\\s+argument/i,\n /\\bpermission\\b/i,\n /\\bauthorization\\b/i,\n /\\bauthentication\\b/i,\n];\n\nfunction isD1ErrorRetryable(errorMessage: string): boolean {\n if (!errorMessage) return false;\n\n // Retryable is checked first on purpose. An error can carry both a transient\n // signal and a permanent-sounding word — \"connection: host not found\",\n // \"retry: authentication backend unavailable\" — and retrying those is correct,\n // while a bare \"row not found\" or a UNIQUE/FOREIGN KEY violation still matches\n // nothing in the retryable list and is correctly refused. The ordering is\n // pinned by `hardening-round7.test.ts` in Durable-DAV; the kit carries the\n // equivalent expectations in d1.test.ts.\n for (const pattern of RETRYABLE_PATTERNS) {\n if (pattern.test(errorMessage)) return true;\n }\n\n for (const pattern of NON_RETRYABLE_PATTERNS) {\n if (pattern.test(errorMessage)) return false;\n }\n\n return false;\n}\n\nexport { isD1ErrorRetryable, RETRYABLE_PATTERNS, NON_RETRYABLE_PATTERNS };\n"],
5
- "mappings": "+EAeA,MAAMA,EAA+B,CACnC,QACA,UACA,WACA,gBACA,gCACA,cACA,WACA,eACA,WACA,cACA,SACA,YACA,kBAeIC,EAAmC,CACvC,cACA,cACA,iBACA,iBACA,eACA,cACA,iBACA,oCACA,mBAGA,wBACA,sBACA,kBACA,qBACA,uBAGF,SAASC,EAAmBC,EAAoB,CAC9C,GAAI,CAACA,EAAc,MAAO,GAS1B,UAAWC,KAAWJ,EACpB,GAAII,EAAQ,KAAKD,CAAY,EAAG,MAAO,GAGzC,UAAWC,KAAWH,EACpB,GAAIG,EAAQ,KAAKD,CAAY,EAAG,MAAO,GAGzC,MAAO,EACT,CAnBSE,EAAAH,EAAA",
6
- "names": ["RETRYABLE_PATTERNS", "NON_RETRYABLE_PATTERNS", "isD1ErrorRetryable", "errorMessage", "pattern", "__name"]
4
+ "sourcesContent": ["/**\n * Classify a raw D1 (or DO SQLite) error message as transient or permanent.\n *\n * Converged verbatim from Durable-DAV (and ChordDHT's byte-identical copy,\n * modulo the import scope) — the most-documented variant in the family.\n */\n\n/**\n * Patterns for a transient failure worth retrying.\n *\n * Checked **first**. A message matching both lists is treated as transient: one\n * wasted round trip against a real conflict is cheap, whereas mis-classifying a\n * blip as permanent turns a self-healing condition into a user-visible outage\n * that neither the DAO's retry nor the API's 503 mapping will cover.\n */\nconst RETRYABLE_PATTERNS: RegExp[] = [\n /busy/i,\n /locked/i,\n /timeout/i,\n /timed?\\s*out/i,\n /internal\\s+(server\\s+)?error/i,\n /connection/i,\n /network/i,\n /unavailable/i,\n /throttl/i,\n /too\\s+many/i,\n /retry/i,\n /deadlock/i,\n /serialization/i,\n];\n\n/**\n * Patterns for a failure that will not get better on its own.\n *\n * Every entry is deliberately **narrower than its obvious spelling**. This list\n * used to be consulted first and carried bare `/range/i` and `/not\\s+found/i`,\n * both of which match transient conditions:\n *\n * - `/range/i` matched `RangeError: Maximum call stack size exceeded` and\n * `byte range not satisfiable` — neither is a row-level conflict.\n * - `/not\\s+found/i` matched `host not found`, i.e. a DNS blip, which\n * `/connection/i` now correctly claims first.\n */\nconst NON_RETRYABLE_PATTERNS: RegExp[] = [\n /constraint/i,\n /\\bunique\\b/i,\n /primary\\s+key/i,\n /foreign\\s+key/i,\n /not\\s+found/i,\n /\\bsyntax\\b/i,\n /parse\\s+error/i,\n /no\\s+such\\s+(table|column|index)/i,\n /type\\s+mismatch/i,\n // Was `/range/i`, which also matched a stack-overflow `RangeError` and\n // \"byte range not satisfiable\".\n /\\bout\\s+of\\s+range\\b/i,\n /invalid\\s+argument/i,\n /\\bpermission\\b/i,\n /\\bauthorization\\b/i,\n /\\bauthentication\\b/i,\n];\n\n/**\n * A bind-ceiling refusal, checked **before** both lists.\n *\n * `/too\\s+many/i` is in the retryable list, and retryable is consulted first by\n * design — so a row in the non-retryable list could never win this one. It has to\n * be its own pre-check for the same reason `DAILY_LIMIT_PATTERN` is: the defect\n * is a query shape, not a fault. `too many SQL variables` fails identically for\n * ever, and retrying it three times with backoff turns a one-line batching fix\n * into a multi-second stall on every page that hits it.\n */\nconst BIND_CEILING_PATTERN = /too\\s+many\\s+(?:SQL\\s+)?(?:variables|bind\\s+parameters|parameters)\\b/i;\n\n/**\n * Cloudflare's daily-allowance refusal, as it arrives.\n *\n * Matched on a substring rather than the whole sentence because the message\n * reaches this layer **inside a wrapper** — `executeWithRetry` throws\n * `Failed to <context>: <message>` — and a classifier that required the bare\n * sentence would answer \"not a quota\" for a quota.\n *\n * The two words that identify it are `exceeded` and `daily`, and both are\n * load-bearing. `too many` is deliberately **absent**, because a row that says\n * \"too many SQL variables\" is a defect a repo ships guards for, not a spent\n * allowance — treating that as a quota parks the work until midnight over a\n * query one batching change fixes.\n *\n * The apostrophe accepts `’` as well as `'`. A message that arrives with a\n * typographic apostrophe is still a spent allowance, and matching only the\n * straight one answers \"transient, retry\" for a refusal that cannot change for\n * hours — the failure this detector exists to prevent.\n */\nconst DAILY_LIMIT_PATTERN = /exceeded\\s+D1['’]?s?\\s+free\\s+tier\\s+daily\\s+row\\s+(read|write)\\s+limit/i;\n\n/**\n * Milliseconds in a day. Named so the UTC arithmetic below reads as what it is.\n */\nconst MS_PER_DAY = 86_400_000;\n\n/**\n * Which daily allowance is spent, and when it comes back.\n *\n * `resetsAt` is epoch milliseconds and is always **strictly in the future** for\n * the clock it was computed from — including at exactly midnight, where the\n * naive subtraction yields a time that has already passed. That case is not a\n * rounding detail: a pause whose reset is in the past is a pause of zero length,\n * and a chunk that returns immediately is a chunk that re-runs its whole failure\n * path at the alarm's rate.\n */\ninterface D1DailyLimit {\n readonly kind: 'read' | 'write';\n readonly resetsAt: number;\n}\n\n/**\n * The next midnight UTC after `nowMs`, in epoch milliseconds.\n *\n * UTC and not local: the reset is UTC, so a local-time calculation is wrong\n * twice a day — once by the offset, and once because the two midnights disagree.\n */\nfunction nextMidnightUtc(nowMs: number): number {\n const dayMs = nowMs - (nowMs % MS_PER_DAY);\n return dayMs + MS_PER_DAY;\n}\n\n/**\n * The spent daily allowance, or `null` for any other failure.\n *\n * `null` rather than `false` because the answer carries two facts, and a boolean\n * forces every caller to recompute the reset time — which is exactly the second\n * answer to one question, and the one that decides whether work resumes at\n * midnight or immediately and fails again.\n */\nfunction isD1DailyLimitError(error: unknown, nowMs: number = Date.now()): D1DailyLimit | null {\n const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';\n const match = DAILY_LIMIT_PATTERN.exec(message);\n if (!match) return null;\n return { kind: match[1]?.toLowerCase() === 'read' ? 'read' : 'write', resetsAt: nextMidnightUtc(nowMs) };\n}\n\nfunction isD1ErrorRetryable(errorMessage: string): boolean {\n if (!errorMessage) return false;\n\n // A spent daily allowance is answered **before** both lists, and it is the one\n // reason this function is not the whole answer to \"should this be tried\n // again\". An account over its row-write limit is refused a message about\n // upgrading, and adding `/exceeded/` to `RETRYABLE_PATTERNS` would turn a\n // refusal that cannot change for hours into three attempts with backoff, per\n // statement, per chunk, per alarm.\n if (DAILY_LIMIT_PATTERN.test(errorMessage)) return false;\n\n // Same reasoning as the allowance above: `/too\\s+many/i` sits in the retryable\n // list, so this has to be answered before that list is consulted rather than\n // inside the non-retryable one. A bind ceiling is a query-shape defect fixed by\n // batching, and no amount of waiting changes it.\n if (BIND_CEILING_PATTERN.test(errorMessage)) return false;\n\n // Retryable is checked first on purpose. An error can carry both a transient\n // signal and a permanent-sounding word — \"connection: host not found\",\n // \"retry: authentication backend unavailable\" — and retrying those is correct,\n // while a bare \"row not found\" or a UNIQUE/FOREIGN KEY violation still matches\n // nothing in the retryable list and is correctly refused. The ordering is\n // pinned by `hardening-round7.test.ts` in Durable-DAV; the kit carries the\n // equivalent expectations in d1.test.ts.\n for (const pattern of RETRYABLE_PATTERNS) {\n if (pattern.test(errorMessage)) return true;\n }\n\n for (const pattern of NON_RETRYABLE_PATTERNS) {\n if (pattern.test(errorMessage)) return false;\n }\n\n return false;\n}\n\nexport {\n BIND_CEILING_PATTERN,\n DAILY_LIMIT_PATTERN,\n isD1DailyLimitError,\n isD1ErrorRetryable,\n nextMidnightUtc,\n RETRYABLE_PATTERNS,\n NON_RETRYABLE_PATTERNS,\n};\nexport type { D1DailyLimit };\n"],
5
+ "mappings": "+EAeA,MAAMA,EAA+B,CACnC,QACA,UACA,WACA,gBACA,gCACA,cACA,WACA,eACA,WACA,cACA,SACA,YACA,kBAeIC,EAAmC,CACvC,cACA,cACA,iBACA,iBACA,eACA,cACA,iBACA,oCACA,mBAGA,wBACA,sBACA,kBACA,qBACA,uBAaIC,EAAuB,wEAqBvBC,EAAsB,2EAKtBC,EAAa,MAuBnB,SAASC,EAAgBC,EAAa,CAEpC,OADcA,EAASA,EAAQ,MAChB,KACjB,CAHSC,EAAAF,EAAA,mBAaT,SAASG,EAAoBC,EAAgBH,EAAgB,KAAK,IAAG,EAAE,CACrE,MAAMI,EAAUD,aAAiB,MAAQA,EAAM,QAAU,OAAOA,GAAU,SAAWA,EAAQ,GACvFE,EAAQR,EAAoB,KAAKO,CAAO,EAC9C,OAAKC,EACE,CAAE,KAAMA,EAAM,CAAC,GAAG,YAAW,IAAO,OAAS,OAAS,QAAS,SAAUN,EAAgBC,CAAK,CAAC,EADnF,IAErB,CALSC,EAAAC,EAAA,uBAOT,SAASI,EAAmBC,EAAoB,CAe9C,GAdI,CAACA,GAQDV,EAAoB,KAAKU,CAAY,GAMrCX,EAAqB,KAAKW,CAAY,EAAG,MAAO,GASpD,UAAWC,KAAWd,EACpB,GAAIc,EAAQ,KAAKD,CAAY,EAAG,MAAO,GAGzC,UAAWC,KAAWb,EACpB,GAAIa,EAAQ,KAAKD,CAAY,EAAG,MAAO,GAGzC,MAAO,EACT,CAjCSN,EAAAK,EAAA",
6
+ "names": ["RETRYABLE_PATTERNS", "NON_RETRYABLE_PATTERNS", "BIND_CEILING_PATTERN", "DAILY_LIMIT_PATTERN", "MS_PER_DAY", "nextMidnightUtc", "nowMs", "__name", "isD1DailyLimitError", "error", "message", "match", "isD1ErrorRetryable", "errorMessage", "pattern"]
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"D1Retry.d.ts","sourceRoot":"","sources":["../src/D1Retry.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAgB7C;;;;GAIG;AACH,QAAA,MAAM,iBAAiB;;;CAAmF,CAAC;AAE3G,UAAU,cAAc;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,iBAAS,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAExC;AAED;;;;;GAKG;AACH,iBAAS,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/D;AAMD;;;;;;;;;;;;;GAaG;AACH,iBAAe,gBAAgB,CAAC,CAAC,SAAS,QAAQ,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC,CA0CtI;AAED,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,KAAK,EAAE,CAAC;AACjE,YAAY,EAAE,cAAc,EAAE,CAAC"}
1
+ {"version":3,"file":"D1Retry.d.ts","sourceRoot":"","sources":["../src/D1Retry.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAgB7C;;;;GAIG;AACH,QAAA,MAAM,iBAAiB;;;CAAmF,CAAC;AAE3G,UAAU,cAAc;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,iBAAS,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAExC;AAED;;;;;GAKG;AACH,iBAAS,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/D;AAMD;;;;;;;;;;;;;GAaG;AACH,iBAAe,gBAAgB,CAAC,CAAC,SAAS,QAAQ,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC,CAsDtI;AAED,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,KAAK,EAAE,CAAC;AACjE,YAAY,EAAE,cAAc,EAAE,CAAC"}
package/dist/D1Retry.js CHANGED
@@ -1 +1 @@
1
- var y=Object.defineProperty;var o=(e,t)=>y(e,"name",{value:t,configurable:!0});import{DatabaseError as l}from"@rexezuge/errors";import{isD1ErrorRetryable as R}from"./D1ErrorClassifier.js";const E=3,b=100,h={maxRetries:E,baseDelayMs:b};function n(e){return new Promise(t=>setTimeout(t,e))}o(n,"sleep");function i(e,t){return e*2**t}o(i,"backoffMs");function D(e,t){return new l(`Failed to ${t}: ${e}`,R(e))}o(D,"toDatabaseError");async function A(e,t,m){const c=m?.maxRetries??E,f=m?.baseDelayMs??b;for(let a=0;a<=c;a++){const u=a===c;try{const r=await e();if(r.success)return r;const s=r.error??"Unknown database error",w=D(s,t);if(!u&&w.retryable){await n(i(f,a));continue}throw w}catch(r){if(r instanceof l){if(!u&&r.retryable){await n(i(f,a));continue}throw r}if(r instanceof Error){const s=D(r.message,t);if(!u&&s.retryable){await n(i(f,a));continue}throw s}throw r}}throw new l(`Failed to ${t} after ${c+1} attempts`)}o(A,"executeWithRetry");export{h as D1_RETRY_DEFAULTS,i as backoffMs,A as executeWithRetry,n as sleep};
1
+ var D=Object.defineProperty;var o=(r,e)=>D(r,"name",{value:e,configurable:!0});import{DatabaseError as l}from"@rexezuge/errors";import{isD1ErrorRetryable as R}from"./D1ErrorClassifier.js";const b=3,E=100,h={maxRetries:b,baseDelayMs:E};function n(r){return new Promise(e=>setTimeout(e,r))}o(n,"sleep");function i(r,e){return r*2**e}o(i,"backoffMs");function y(r,e){return new l(`Failed to ${e}: ${r}`,R(r))}o(y,"toDatabaseError");async function p(r,e,m){const c=m?.maxRetries??b,f=m?.baseDelayMs??E;for(let a=0;a<=c;a++){const u=a===c;try{const t=await r();if(t==null||typeof t!="object"||!("success"in t)||t.success)return t;const s=t.error??"Unknown database error",w=y(s,e);if(!u&&w.retryable){await n(i(f,a));continue}throw w}catch(t){if(t instanceof l){if(!u&&t.retryable){await n(i(f,a));continue}throw t}if(t instanceof Error){const s=y(t.message,e);if(!u&&s.retryable){await n(i(f,a));continue}throw s}throw t}}throw new l(`Failed to ${e} after ${c+1} attempts`)}o(p,"executeWithRetry");export{h as D1_RETRY_DEFAULTS,i as backoffMs,p as executeWithRetry,n as sleep};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/D1Retry.ts"],
4
- "sourcesContent": ["import { DatabaseError } from '@rexezuge/errors';\nimport { isD1ErrorRetryable } from './D1ErrorClassifier.ts';\nimport type { D1Result } from './D1Types.ts';\n\n/**\n * The single retry engine for D1 statements.\n *\n * Converged from Durable-DAV's `D1Utils.ts` (the richest, most-documented\n * variant) with ChordDHT's byte-identical copy and the straight-line port in\n * Mail-Meow. The seven consumer repos each spelled this differently\n * (`executeD1WithRetry`, `runWithRetry`, `firstWithRetry` with its own schedule);\n * the kit ships one engine plus the schedule constants, and `BaseDAO` is the\n * only intended caller.\n */\n\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_BASE_DELAY_MS = 100;\n\n/**\n * The retry schedule, exported so `BaseDAO` and any other caller cannot\n * hard-code a second, divergent one — re-deriving `baseDelayMs * 2 ** n` at a\n * call site is the same drift one level up.\n */\nconst D1_RETRY_DEFAULTS = { maxRetries: DEFAULT_MAX_RETRIES, baseDelayMs: DEFAULT_BASE_DELAY_MS } as const;\n\ninterface D1RetryOptions {\n maxRetries?: number;\n baseDelayMs?: number;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve: (value: void) => void): unknown => setTimeout(resolve, ms));\n}\n\n/**\n * Backoff before the next attempt. Exponential, and uncapped by design: the\n * default base (100 ms) tops out under a second by attempt 3, while an operator\n * who sets a larger base gets the longer wait they asked for. The point is to\n * ride out a busy/locked D1, not to implement a rate limiter.\n */\nfunction backoffMs(baseDelayMs: number, attempt: number): number {\n return baseDelayMs * 2 ** attempt;\n}\n\nfunction toDatabaseError(errorMessage: string, context: string): DatabaseError {\n return new DatabaseError(`Failed to ${context}: ${errorMessage}`, isD1ErrorRetryable(errorMessage));\n}\n\n/**\n * Run a D1 operation, retrying transient failures with exponential backoff.\n *\n * Two failure shapes are handled, because D1 reports both:\n *\n * 1. **A result with `success: false`.** The operation resolved; the database\n * said no. Retried when the error classifies as transient.\n * 2. **A thrown error.** A transport-level rejection, which never carries a\n * `D1Result` at all. Classified from the message the same way.\n *\n * A `DatabaseError` we raised ourselves in (1) arrives back through the `catch`\n * on the retry attempt, so it must be recognised and re-thrown rather than\n * re-wrapped into a second layer of `Failed to …`.\n */\nasync function executeWithRetry<T extends D1Result>(operation: () => Promise<T>, context: string, options?: D1RetryOptions): Promise<T> {\n const maxRetries: number = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n const baseDelayMs: number = options?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const isLastAttempt = attempt === maxRetries;\n try {\n const result: T = await operation();\n if (result.success) return result;\n const errorMessage: string = result.error ?? 'Unknown database error';\n const failure = toDatabaseError(errorMessage, context);\n if (!isLastAttempt && failure.retryable) {\n await sleep(backoffMs(baseDelayMs, attempt));\n continue;\n }\n throw failure;\n } catch (error: unknown) {\n // Already classified above, or raised by the operation itself. Either way\n // re-wrapping would bury the original context.\n if (error instanceof DatabaseError) {\n if (!isLastAttempt && error.retryable) {\n await sleep(backoffMs(baseDelayMs, attempt));\n continue;\n }\n throw error;\n }\n if (error instanceof Error) {\n const failure = toDatabaseError(error.message, context);\n if (!isLastAttempt && failure.retryable) {\n await sleep(backoffMs(baseDelayMs, attempt));\n continue;\n }\n throw failure;\n }\n throw error;\n }\n }\n\n // Unreachable: the loop either returns a result or throws on its final\n // iteration. Present only so the function is total for a reader who has not\n // traced the `continue` paths.\n throw new DatabaseError(`Failed to ${context} after ${maxRetries + 1} attempts`);\n}\n\nexport { backoffMs, D1_RETRY_DEFAULTS, executeWithRetry, sleep };\nexport type { D1RetryOptions };\n"],
5
- "mappings": "+EAAA,OAAS,iBAAAA,MAAqB,mBAC9B,OAAS,sBAAAC,MAA0B,yBAcnC,MAAMC,EAAsB,EACtBC,EAAwB,IAOxBC,EAAoB,CAAE,WAAYF,EAAqB,YAAaC,CAAqB,EAO/F,SAASE,EAAMC,EAAU,CACvB,OAAO,IAAI,QAASC,GAA4C,WAAWA,EAASD,CAAE,CAAC,CACzF,CAFSE,EAAAH,EAAA,SAUT,SAASI,EAAUC,EAAqBC,EAAe,CACrD,OAAOD,EAAc,GAAKC,CAC5B,CAFSH,EAAAC,EAAA,aAIT,SAASG,EAAgBC,EAAsBC,EAAe,CAC5D,OAAO,IAAId,EAAc,aAAac,CAAO,KAAKD,CAAY,GAAIZ,EAAmBY,CAAY,CAAC,CACpG,CAFSL,EAAAI,EAAA,mBAkBT,eAAeG,EAAqCC,EAA6BF,EAAiBG,EAAwB,CACxH,MAAMC,EAAqBD,GAAS,YAAcf,EAC5CQ,EAAsBO,GAAS,aAAed,EAEpD,QAASQ,EAAU,EAAGA,GAAWO,EAAYP,IAAW,CACtD,MAAMQ,EAAgBR,IAAYO,EAClC,GAAI,CACF,MAAME,EAAY,MAAMJ,EAAS,EACjC,GAAII,EAAO,QAAS,OAAOA,EAC3B,MAAMP,EAAuBO,EAAO,OAAS,yBACvCC,EAAUT,EAAgBC,EAAcC,CAAO,EACrD,GAAI,CAACK,GAAiBE,EAAQ,UAAW,CACvC,MAAMhB,EAAMI,EAAUC,EAAaC,CAAO,CAAC,EAC3C,QACF,CACA,MAAMU,CACR,OAASC,EAAgB,CAGvB,GAAIA,aAAiBtB,EAAe,CAClC,GAAI,CAACmB,GAAiBG,EAAM,UAAW,CACrC,MAAMjB,EAAMI,EAAUC,EAAaC,CAAO,CAAC,EAC3C,QACF,CACA,MAAMW,CACR,CACA,GAAIA,aAAiB,MAAO,CAC1B,MAAMD,EAAUT,EAAgBU,EAAM,QAASR,CAAO,EACtD,GAAI,CAACK,GAAiBE,EAAQ,UAAW,CACvC,MAAMhB,EAAMI,EAAUC,EAAaC,CAAO,CAAC,EAC3C,QACF,CACA,MAAMU,CACR,CACA,MAAMC,CACR,CACF,CAKA,MAAM,IAAItB,EAAc,aAAac,CAAO,UAAUI,EAAa,CAAC,WAAW,CACjF,CA1CeV,EAAAO,EAAA",
4
+ "sourcesContent": ["import { DatabaseError } from '@rexezuge/errors';\nimport { isD1ErrorRetryable } from './D1ErrorClassifier.ts';\nimport type { D1Result } from './D1Types.ts';\n\n/**\n * The single retry engine for D1 statements.\n *\n * Converged from Durable-DAV's `D1Utils.ts` (the richest, most-documented\n * variant) with ChordDHT's byte-identical copy and the straight-line port in\n * Mail-Meow. The seven consumer repos each spelled this differently\n * (`executeD1WithRetry`, `runWithRetry`, `firstWithRetry` with its own schedule);\n * the kit ships one engine plus the schedule constants, and `BaseDAO` is the\n * only intended caller.\n */\n\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_BASE_DELAY_MS = 100;\n\n/**\n * The retry schedule, exported so `BaseDAO` and any other caller cannot\n * hard-code a second, divergent one — re-deriving `baseDelayMs * 2 ** n` at a\n * call site is the same drift one level up.\n */\nconst D1_RETRY_DEFAULTS = { maxRetries: DEFAULT_MAX_RETRIES, baseDelayMs: DEFAULT_BASE_DELAY_MS } as const;\n\ninterface D1RetryOptions {\n maxRetries?: number;\n baseDelayMs?: number;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve: (value: void) => void): unknown => setTimeout(resolve, ms));\n}\n\n/**\n * Backoff before the next attempt. Exponential, and uncapped by design: the\n * default base (100 ms) tops out under a second by attempt 3, while an operator\n * who sets a larger base gets the longer wait they asked for. The point is to\n * ride out a busy/locked D1, not to implement a rate limiter.\n */\nfunction backoffMs(baseDelayMs: number, attempt: number): number {\n return baseDelayMs * 2 ** attempt;\n}\n\nfunction toDatabaseError(errorMessage: string, context: string): DatabaseError {\n return new DatabaseError(`Failed to ${context}: ${errorMessage}`, isD1ErrorRetryable(errorMessage));\n}\n\n/**\n * Run a D1 operation, retrying transient failures with exponential backoff.\n *\n * Two failure shapes are handled, because D1 reports both:\n *\n * 1. **A result with `success: false`.** The operation resolved; the database\n * said no. Retried when the error classifies as transient.\n * 2. **A thrown error.** A transport-level rejection, which never carries a\n * `D1Result` at all. Classified from the message the same way.\n *\n * A `DatabaseError` we raised ourselves in (1) arrives back through the `catch`\n * on the retry attempt, so it must be recognised and re-thrown rather than\n * re-wrapped into a second layer of `Failed to …`.\n */\nasync function executeWithRetry<T extends D1Result>(operation: () => Promise<T>, context: string, options?: D1RetryOptions): Promise<T> {\n const maxRetries: number = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n const baseDelayMs: number = options?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const isLastAttempt = attempt === maxRetries;\n try {\n const result: T = await operation();\n // A result with **no** `success` member is a success, not a failed one. That\n // is not a hypothetical: `first()` answers `null` when there is no row, and\n // `null` is the platform's own \"no row, not an error\" — the convention this\n // package, `KvCache` and every layer above them share. Reading `.success`\n // off it threw `Cannot read properties of null`, which turned a missing row\n // into a `DatabaseError` and made every optional lookup look like a fault.\n //\n // So the test is for a result that *says* it failed, not for one that lacks\n // the word. `undefined` and `null` therefore pass straight through, and so\n // does a plain value a caller wrapped the statement in.\n if (result === null || result === undefined || typeof result !== 'object' || !('success' in result) || result.success) {\n return result;\n }\n const errorMessage: string = result.error ?? 'Unknown database error';\n const failure = toDatabaseError(errorMessage, context);\n if (!isLastAttempt && failure.retryable) {\n await sleep(backoffMs(baseDelayMs, attempt));\n continue;\n }\n throw failure;\n } catch (error: unknown) {\n // Already classified above, or raised by the operation itself. Either way\n // re-wrapping would bury the original context.\n if (error instanceof DatabaseError) {\n if (!isLastAttempt && error.retryable) {\n await sleep(backoffMs(baseDelayMs, attempt));\n continue;\n }\n throw error;\n }\n if (error instanceof Error) {\n const failure = toDatabaseError(error.message, context);\n if (!isLastAttempt && failure.retryable) {\n await sleep(backoffMs(baseDelayMs, attempt));\n continue;\n }\n throw failure;\n }\n throw error;\n }\n }\n\n // Unreachable: the loop either returns a result or throws on its final\n // iteration. Present only so the function is total for a reader who has not\n // traced the `continue` paths.\n throw new DatabaseError(`Failed to ${context} after ${maxRetries + 1} attempts`);\n}\n\nexport { backoffMs, D1_RETRY_DEFAULTS, executeWithRetry, sleep };\nexport type { D1RetryOptions };\n"],
5
+ "mappings": "+EAAA,OAAS,iBAAAA,MAAqB,mBAC9B,OAAS,sBAAAC,MAA0B,yBAcnC,MAAMC,EAAsB,EACtBC,EAAwB,IAOxBC,EAAoB,CAAE,WAAYF,EAAqB,YAAaC,CAAqB,EAO/F,SAASE,EAAMC,EAAU,CACvB,OAAO,IAAI,QAASC,GAA4C,WAAWA,EAASD,CAAE,CAAC,CACzF,CAFSE,EAAAH,EAAA,SAUT,SAASI,EAAUC,EAAqBC,EAAe,CACrD,OAAOD,EAAc,GAAKC,CAC5B,CAFSH,EAAAC,EAAA,aAIT,SAASG,EAAgBC,EAAsBC,EAAe,CAC5D,OAAO,IAAId,EAAc,aAAac,CAAO,KAAKD,CAAY,GAAIZ,EAAmBY,CAAY,CAAC,CACpG,CAFSL,EAAAI,EAAA,mBAkBT,eAAeG,EAAqCC,EAA6BF,EAAiBG,EAAwB,CACxH,MAAMC,EAAqBD,GAAS,YAAcf,EAC5CQ,EAAsBO,GAAS,aAAed,EAEpD,QAASQ,EAAU,EAAGA,GAAWO,EAAYP,IAAW,CACtD,MAAMQ,EAAgBR,IAAYO,EAClC,GAAI,CACF,MAAME,EAAY,MAAMJ,EAAS,EAWjC,GAAII,GAAW,MAAgC,OAAOA,GAAW,UAAY,EAAE,YAAaA,IAAWA,EAAO,QAC5G,OAAOA,EAET,MAAMP,EAAuBO,EAAO,OAAS,yBACvCC,EAAUT,EAAgBC,EAAcC,CAAO,EACrD,GAAI,CAACK,GAAiBE,EAAQ,UAAW,CACvC,MAAMhB,EAAMI,EAAUC,EAAaC,CAAO,CAAC,EAC3C,QACF,CACA,MAAMU,CACR,OAASC,EAAgB,CAGvB,GAAIA,aAAiBtB,EAAe,CAClC,GAAI,CAACmB,GAAiBG,EAAM,UAAW,CACrC,MAAMjB,EAAMI,EAAUC,EAAaC,CAAO,CAAC,EAC3C,QACF,CACA,MAAMW,CACR,CACA,GAAIA,aAAiB,MAAO,CAC1B,MAAMD,EAAUT,EAAgBU,EAAM,QAASR,CAAO,EACtD,GAAI,CAACK,GAAiBE,EAAQ,UAAW,CACvC,MAAMhB,EAAMI,EAAUC,EAAaC,CAAO,CAAC,EAC3C,QACF,CACA,MAAMU,CACR,CACA,MAAMC,CACR,CACF,CAKA,MAAM,IAAItB,EAAc,aAAac,CAAO,UAAUI,EAAa,CAAC,WAAW,CACjF,CAtDeV,EAAAO,EAAA",
6
6
  "names": ["DatabaseError", "isD1ErrorRetryable", "DEFAULT_MAX_RETRIES", "DEFAULT_BASE_DELAY_MS", "D1_RETRY_DEFAULTS", "sleep", "ms", "resolve", "__name", "backoffMs", "baseDelayMs", "attempt", "toDatabaseError", "errorMessage", "context", "executeWithRetry", "operation", "options", "maxRetries", "isLastAttempt", "result", "failure", "error"]
7
7
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
- export { BaseDAO, assertSqlIdentifier } from './BaseDAO.ts';
2
- export { isD1ErrorRetryable, RETRYABLE_PATTERNS, NON_RETRYABLE_PATTERNS } from './D1ErrorClassifier.ts';
1
+ export { BaseDAO, assertSqlIdentifier, statementTable } from './BaseDAO.ts';
2
+ export type { BilledRowsForTable, TrackedStatement, WriteResult } from './BaseDAO.ts';
3
+ export { BIND_CEILING_PATTERN, DAILY_LIMIT_PATTERN, isD1DailyLimitError, isD1ErrorRetryable, nextMidnightUtc, RETRYABLE_PATTERNS, NON_RETRYABLE_PATTERNS, } from './D1ErrorClassifier.ts';
4
+ export type { D1DailyLimit } from './D1ErrorClassifier.ts';
3
5
  export { isMissingSchemaError, MISSING_SCHEMA_PATTERN } from './isMissingSchemaError.ts';
4
6
  export { executableStatements, isExecutable, splitSql } from './splitSql.ts';
5
7
  export { backoffMs, D1_RETRY_DEFAULTS, executeWithRetry, sleep } from './D1Retry.ts';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACxG,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACzF,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrF,YAAY,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACnD,YAAY,EAAE,mBAAmB,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,eAAe,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAClH,YAAY,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC5E,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACtF,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,mBAAmB,EACnB,kBAAkB,EAClB,eAAe,EACf,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACzF,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrF,YAAY,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACnD,YAAY,EAAE,mBAAmB,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,eAAe,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAClH,YAAY,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{BaseDAO as t,assertSqlIdentifier as o}from"./BaseDAO.js";import{isD1ErrorRetryable as S,RETRYABLE_PATTERNS as s,NON_RETRYABLE_PATTERNS as T}from"./D1ErrorClassifier.js";import{isMissingSchemaError as p,MISSING_SCHEMA_PATTERN as R}from"./isMissingSchemaError.js";import{executableStatements as f,isExecutable as m,splitSql as x}from"./splitSql.js";import{backoffMs as _,D1_RETRY_DEFAULTS as a,executeWithRetry as l,sleep as N}from"./D1Retry.js";import{AesGcmKeyError as n,decryptSecret as y,encryptSecret as B,roundTripSecret as b,IV_BYTES as u,KEY_BYTES as D}from"./aes-gcm.js";export{n as AesGcmKeyError,t as BaseDAO,a as D1_RETRY_DEFAULTS,u as IV_BYTES,D as KEY_BYTES,R as MISSING_SCHEMA_PATTERN,T as NON_RETRYABLE_PATTERNS,s as RETRYABLE_PATTERNS,o as assertSqlIdentifier,_ as backoffMs,y as decryptSecret,B as encryptSecret,f as executableStatements,l as executeWithRetry,S as isD1ErrorRetryable,m as isExecutable,p as isMissingSchemaError,b as roundTripSecret,N as sleep,x as splitSql};
1
+ import{BaseDAO as t,assertSqlIdentifier as E,statementTable as T}from"./BaseDAO.js";import{BIND_CEILING_PATTERN as i,DAILY_LIMIT_PATTERN as s,isD1DailyLimitError as S,isD1ErrorRetryable as R,nextMidnightUtc as _,RETRYABLE_PATTERNS as c,NON_RETRYABLE_PATTERNS as A}from"./D1ErrorClassifier.js";import{isMissingSchemaError as m,MISSING_SCHEMA_PATTERN as p}from"./isMissingSchemaError.js";import{executableStatements as I,isExecutable as N,splitSql as f}from"./splitSql.js";import{backoffMs as n,D1_RETRY_DEFAULTS as D,executeWithRetry as L,sleep as Y}from"./D1Retry.js";import{AesGcmKeyError as B,decryptSecret as M,encryptSecret as b,roundTripSecret as P,IV_BYTES as d,KEY_BYTES as u}from"./aes-gcm.js";export{B as AesGcmKeyError,i as BIND_CEILING_PATTERN,t as BaseDAO,D as D1_RETRY_DEFAULTS,s as DAILY_LIMIT_PATTERN,d as IV_BYTES,u as KEY_BYTES,p as MISSING_SCHEMA_PATTERN,A as NON_RETRYABLE_PATTERNS,c as RETRYABLE_PATTERNS,E as assertSqlIdentifier,n as backoffMs,M as decryptSecret,b as encryptSecret,I as executableStatements,L as executeWithRetry,S as isD1DailyLimitError,R as isD1ErrorRetryable,N as isExecutable,m as isMissingSchemaError,_ as nextMidnightUtc,P as roundTripSecret,Y as sleep,f as splitSql,T as statementTable};
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["export { BaseDAO, assertSqlIdentifier } from './BaseDAO.ts';\nexport { isD1ErrorRetryable, RETRYABLE_PATTERNS, NON_RETRYABLE_PATTERNS } from './D1ErrorClassifier.ts';\nexport { isMissingSchemaError, MISSING_SCHEMA_PATTERN } from './isMissingSchemaError.ts';\nexport { executableStatements, isExecutable, splitSql } from './splitSql.ts';\nexport { backoffMs, D1_RETRY_DEFAULTS, executeWithRetry, sleep } from './D1Retry.ts';\nexport type { D1RetryOptions } from './D1Retry.ts';\nexport type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';\nexport { AesGcmKeyError, decryptSecret, encryptSecret, roundTripSecret, IV_BYTES, KEY_BYTES } from './aes-gcm.ts';\nexport type { EncryptedEnvelope } from './aes-gcm.ts';\n"],
5
- "mappings": "AAAA,OAAS,WAAAA,EAAS,uBAAAC,MAA2B,eAC7C,OAAS,sBAAAC,EAAoB,sBAAAC,EAAoB,0BAAAC,MAA8B,yBAC/E,OAAS,wBAAAC,EAAsB,0BAAAC,MAA8B,4BAC7D,OAAS,wBAAAC,EAAsB,gBAAAC,EAAc,YAAAC,MAAgB,gBAC7D,OAAS,aAAAC,EAAW,qBAAAC,EAAmB,oBAAAC,EAAkB,SAAAC,MAAa,eAGtE,OAAS,kBAAAC,EAAgB,iBAAAC,EAAe,iBAAAC,EAAe,mBAAAC,EAAiB,YAAAC,EAAU,aAAAC,MAAiB",
6
- "names": ["BaseDAO", "assertSqlIdentifier", "isD1ErrorRetryable", "RETRYABLE_PATTERNS", "NON_RETRYABLE_PATTERNS", "isMissingSchemaError", "MISSING_SCHEMA_PATTERN", "executableStatements", "isExecutable", "splitSql", "backoffMs", "D1_RETRY_DEFAULTS", "executeWithRetry", "sleep", "AesGcmKeyError", "decryptSecret", "encryptSecret", "roundTripSecret", "IV_BYTES", "KEY_BYTES"]
4
+ "sourcesContent": ["export { BaseDAO, assertSqlIdentifier, statementTable } from './BaseDAO.ts';\nexport type { BilledRowsForTable, TrackedStatement, WriteResult } from './BaseDAO.ts';\nexport {\n BIND_CEILING_PATTERN,\n DAILY_LIMIT_PATTERN,\n isD1DailyLimitError,\n isD1ErrorRetryable,\n nextMidnightUtc,\n RETRYABLE_PATTERNS,\n NON_RETRYABLE_PATTERNS,\n} from './D1ErrorClassifier.ts';\nexport type { D1DailyLimit } from './D1ErrorClassifier.ts';\nexport { isMissingSchemaError, MISSING_SCHEMA_PATTERN } from './isMissingSchemaError.ts';\nexport { executableStatements, isExecutable, splitSql } from './splitSql.ts';\nexport { backoffMs, D1_RETRY_DEFAULTS, executeWithRetry, sleep } from './D1Retry.ts';\nexport type { D1RetryOptions } from './D1Retry.ts';\nexport type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';\nexport { AesGcmKeyError, decryptSecret, encryptSecret, roundTripSecret, IV_BYTES, KEY_BYTES } from './aes-gcm.ts';\nexport type { EncryptedEnvelope } from './aes-gcm.ts';\n"],
5
+ "mappings": "AAAA,OAAS,WAAAA,EAAS,uBAAAC,EAAqB,kBAAAC,MAAsB,eAE7D,OACE,wBAAAC,EACA,uBAAAC,EACA,uBAAAC,EACA,sBAAAC,EACA,mBAAAC,EACA,sBAAAC,EACA,0BAAAC,MACK,yBAEP,OAAS,wBAAAC,EAAsB,0BAAAC,MAA8B,4BAC7D,OAAS,wBAAAC,EAAsB,gBAAAC,EAAc,YAAAC,MAAgB,gBAC7D,OAAS,aAAAC,EAAW,qBAAAC,EAAmB,oBAAAC,EAAkB,SAAAC,MAAa,eAGtE,OAAS,kBAAAC,EAAgB,iBAAAC,EAAe,iBAAAC,EAAe,mBAAAC,EAAiB,YAAAC,EAAU,aAAAC,MAAiB",
6
+ "names": ["BaseDAO", "assertSqlIdentifier", "statementTable", "BIND_CEILING_PATTERN", "DAILY_LIMIT_PATTERN", "isD1DailyLimitError", "isD1ErrorRetryable", "nextMidnightUtc", "RETRYABLE_PATTERNS", "NON_RETRYABLE_PATTERNS", "isMissingSchemaError", "MISSING_SCHEMA_PATTERN", "executableStatements", "isExecutable", "splitSql", "backoffMs", "D1_RETRY_DEFAULTS", "executeWithRetry", "sleep", "AesGcmKeyError", "decryptSecret", "encryptSecret", "roundTripSecret", "IV_BYTES", "KEY_BYTES"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexezuge/d1",
3
- "version": "1.6.1",
3
+ "version": "1.7.1",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,8 +25,8 @@
25
25
  "dist"
26
26
  ],
27
27
  "dependencies": {
28
- "@rexezuge/errors": "1.6.1",
29
- "@rexezuge/shared": "1.6.1"
28
+ "@rexezuge/errors": "1.7.1",
29
+ "@rexezuge/shared": "1.7.1"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "26.6.4",