@lpdjs/firestore-repo-service 3.0.16 → 3.0.18
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/dist/{actor-context-DQZgWqj3.d.cts → actor-context-zNobm6nG.d.cts} +17 -2
- package/dist/{actor-context-DQZgWqj3.d.ts → actor-context-zNobm6nG.d.ts} +17 -2
- package/dist/{create-servers-BMpE8oAc.d.cts → create-servers-DydjOOOS.d.cts} +3 -3
- package/dist/{create-servers-DSXdPM6o.d.ts → create-servers-bMJVVjPj.d.ts} +3 -3
- package/dist/effects-BYvL8JUK.d.ts +158 -0
- package/dist/effects-DcM19dy4.d.cts +158 -0
- package/dist/history/index.cjs +1 -1
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.d.cts +1 -1
- package/dist/history/index.d.ts +1 -1
- package/dist/history/index.js +1 -1
- package/dist/history/index.js.map +1 -1
- package/dist/index.cjs +95 -95
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +95 -95
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +139 -2
- package/dist/llms.txt +1 -1
- package/dist/servers/admin/index.d.cts +3 -3
- package/dist/servers/admin/index.d.ts +3 -3
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +6 -7
- package/dist/servers/crud/index.d.ts +6 -7
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/hono/index.cjs +12 -12
- package/dist/servers/hono/index.cjs.map +1 -1
- package/dist/servers/hono/index.d.cts +4 -4
- package/dist/servers/hono/index.d.ts +4 -4
- package/dist/servers/hono/index.js +12 -12
- package/dist/servers/hono/index.js.map +1 -1
- package/dist/servers/index.cjs +101 -101
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +6 -7
- package/dist/servers/index.d.ts +6 -7
- package/dist/servers/index.js +101 -101
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/index.cjs +44 -44
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.js +44 -44
- package/dist/sync/index.js.map +1 -1
- package/dist/{types-CaCBG76r.d.ts → types-5Q7JDDba.d.ts} +332 -3
- package/dist/{types-w1rEqs0Z.d.ts → types-BJ6MAavL.d.ts} +1 -1
- package/dist/{types-mKcJozu4.d.cts → types-BYPdlGSL.d.cts} +332 -3
- package/dist/{types-BDTx8VPg.d.cts → types-XvVG8_9J.d.cts} +1 -1
- package/package.json +1 -1
- package/dist/openapi-CKTuB2Yz.d.ts +0 -70
- package/dist/openapi-Cb3QMU0Q.d.cts +0 -70
- package/dist/rules-DY5f_wPw.d.ts +0 -30
- package/dist/rules-DhNUzbIl.d.cts +0 -30
package/dist/llms-full.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# @lpdjs/firestore-repo-service (v3.0.
|
|
1
|
+
# @lpdjs/firestore-repo-service (v3.0.18) — full documentation
|
|
2
2
|
|
|
3
3
|
> ⚡ Type-safe Firestore ORM with auto-generated repositories, advanced queries, relations with typed select, pagination with include, batch/bulk operations, aggregations and transactions.
|
|
4
4
|
|
|
@@ -1316,6 +1316,7 @@ Send complex filter conditions including `where` (AND), `orWhere` (simple OR), a
|
|
|
1316
1316
|
| `middlewares` | `MiddlewareHandler[]` | Custom Hono middleware array |
|
|
1317
1317
|
| `repos` | `Record<string, CrudRepoConfig>` | Per-repository configuration mapping |
|
|
1318
1318
|
| `indexesError` | `(err: { repoName, error, indexUrl, c }) => void` | Callback triggered when a Firestore missing-index error occurs |
|
|
1319
|
+
| `onHookError` | `(ctx: CrudHookErrorContext) => void \| Promise<void>` | Callback invoked when a post-write hook (or `changesNeeded` follow-up update) throws |
|
|
1319
1320
|
| `openapi` | `OpenAPISpecOptions` | OpenAPI 3.1 documentation settings |
|
|
1320
1321
|
| `verbose` | `boolean` | Include detailed error messages in HTTP 500 responses |
|
|
1321
1322
|
|
|
@@ -1330,7 +1331,8 @@ Send complex filter conditions including `where` (AND), `orWhere` (simple OR), a
|
|
|
1330
1331
|
| `orderableFields` | `string[]` | List of allowed fields for ordering |
|
|
1331
1332
|
| `allowedIncludes` | `string[]` | List of relation keys allowed in `includes` |
|
|
1332
1333
|
| `allowDelete` | `boolean` | Whether `DELETE /:id` is enabled |
|
|
1333
|
-
| `rules` | `
|
|
1334
|
+
| `rules` | `CrudRules<TRepo>` | Per-operation authorization, before-rules & `preWrite` mutations |
|
|
1335
|
+
| `hooks` | `CrudHooks<TRepo>` | Post-write lifecycle hooks (`afterCreate`, `afterUpdate`, `afterDelete`, `afterBatch`) |
|
|
1334
1336
|
| `pageSize` | `number` | Default page size for list requests |
|
|
1335
1337
|
|
|
1336
1338
|
---
|
|
@@ -1372,6 +1374,141 @@ If a rule returns `false` or a string error message, the mutation is rejected wi
|
|
|
1372
1374
|
|
|
1373
1375
|
---
|
|
1374
1376
|
|
|
1377
|
+
## Lifecycle Hooks, Mutations & Effects (`hooks`)
|
|
1378
|
+
|
|
1379
|
+
While `rules` govern authorization and before-validation checks, `hooks` manage both **pre-write mutations** and **post-write reactive side effects** with full model type inference from each repository:
|
|
1380
|
+
|
|
1381
|
+
- **`beforeCreate`** (`POST /:repoName` & batch `create`): runs after validation and `rules.create`. Mutate `ctx.body` in place to normalize or inject server-derived fields.
|
|
1382
|
+
- **`beforeUpdate`** (`PUT/PATCH /:repoName/:id` & batch `update`): runs after validation and `rules.update`. Mutate `ctx.body` in place; `diff` is **recomputed afterward** so mutated fields are captured by `afterUpdate` / `afterBatch`.
|
|
1383
|
+
- **`afterCreate`** (`POST /:repoName`): receives `{ user, doc, id, pathArgs, params, c }`. May optionally return a non-empty `Partial<T>` to patch the newly created document via `repo.update(...pathArgs, changes)` and return the patched document in the HTTP 201 response.
|
|
1384
|
+
- **`afterUpdate`** (`PUT/PATCH /:repoName/:id`): receives `{ user, before, after, body, diff, id, pathArgs, params, c }`. The `diff` is **recomputed after `rules.update` and `beforeUpdate`**, so fields added or modified during pre-write are present in `diff.changes` and `diff.after`. May optionally return a non-empty `Partial<T>` to apply follow-up changes to the current document and return the final document in the HTTP 200 response.
|
|
1385
|
+
- **`afterDelete`** (`DELETE /:repoName/:id`): receives `{ user, doc, id, pathArgs, params, c }` where `doc` is the snapshot captured prior to deletion.
|
|
1386
|
+
- **`afterBatch`** (`POST /:repoName/batch`): called **once after `batch.commit()`** with `{ user, created, updated, deleted, params, c }` (each `updated` item carries its `diff` recomputed after pre-write mutations). If `afterBatch` is omitted, the server automatically falls back to invoking `afterCreate` / `afterUpdate` / `afterDelete` sequentially on each committed item.
|
|
1387
|
+
- **`onAfterError`**: per-repo error callback `(err, phase) => void` invoked when any `after*` hook fails (in addition to server-wide `onHookError`).
|
|
1388
|
+
|
|
1389
|
+
### Built-in helpers (`mutations` & `effects`)
|
|
1390
|
+
|
|
1391
|
+
Aligned with `createRules` / `applyRules` / `createBeforeRules`, the package exports declarative builders ready to plug into `hooks`:
|
|
1392
|
+
|
|
1393
|
+
- **Pre-write mutations**: `createMutations`, `applyMutations`, `createBeforeCreateMutations`, `createBeforeUpdateMutations` (indexed by model field key plus `"*"` wildcard, with optional `operations: ["create"] | ["update"]` filter).
|
|
1394
|
+
- **Post-write effects**: `createEffects`, `applyEffects`, `createAfterUpdateEffects` (indexed by model field key plus `"*"` wildcard, with isolated per-rule error capture via `onRuleError` and automatic `changesNeeded` aggregation).
|
|
1395
|
+
|
|
1396
|
+
```typescript
|
|
1397
|
+
import {
|
|
1398
|
+
createAfterUpdateEffects,
|
|
1399
|
+
createBeforeCreateMutations,
|
|
1400
|
+
createBeforeUpdateMutations,
|
|
1401
|
+
createEffects,
|
|
1402
|
+
createMutations,
|
|
1403
|
+
withActor,
|
|
1404
|
+
} from "@lpdjs/firestore-repo-service";
|
|
1405
|
+
|
|
1406
|
+
const eventMutations = createMutations<PreventionEvent>({
|
|
1407
|
+
proId: [
|
|
1408
|
+
{
|
|
1409
|
+
description: "Auto-accept when a pro is assigned",
|
|
1410
|
+
operations: ["update"],
|
|
1411
|
+
mutation: ({ body, diff }) => {
|
|
1412
|
+
if (diff.changes.proId) {
|
|
1413
|
+
body.status = "accepted";
|
|
1414
|
+
body.publicationStatus = "toRepublish";
|
|
1415
|
+
}
|
|
1416
|
+
},
|
|
1417
|
+
},
|
|
1418
|
+
],
|
|
1419
|
+
"*": [
|
|
1420
|
+
({ body }) => {
|
|
1421
|
+
if (typeof body.title === "string") body.title = body.title.trim();
|
|
1422
|
+
},
|
|
1423
|
+
],
|
|
1424
|
+
});
|
|
1425
|
+
|
|
1426
|
+
const eventEffects = createEffects<PreventionEvent, { after: PreventionEvent }>({
|
|
1427
|
+
status: [
|
|
1428
|
+
{
|
|
1429
|
+
description: "Notify when accepted",
|
|
1430
|
+
rule: ({ diff }) => diff.changes.status === "accepted",
|
|
1431
|
+
handler: async ({ after }) => {
|
|
1432
|
+
await notifyAssignment(after);
|
|
1433
|
+
return { notifiedAt: new Date() }; // optional follow-up patch
|
|
1434
|
+
},
|
|
1435
|
+
},
|
|
1436
|
+
],
|
|
1437
|
+
});
|
|
1438
|
+
|
|
1439
|
+
export const api = servers.crud({
|
|
1440
|
+
basePath: "/api",
|
|
1441
|
+
onHookError: ({ hook, repoName, id, error }) => {
|
|
1442
|
+
logger.error(`[CRUD ${hook}] failed on ${repoName}/${id ?? "batch"}`, error);
|
|
1443
|
+
},
|
|
1444
|
+
repos: {
|
|
1445
|
+
preventionEvents: {
|
|
1446
|
+
path: "prevention/prev_rules/prev_workshops/{workshopId}/prev_events",
|
|
1447
|
+
hooks: {
|
|
1448
|
+
beforeCreate: createBeforeCreateMutations(eventMutations),
|
|
1449
|
+
beforeUpdate: createBeforeUpdateMutations(eventMutations),
|
|
1450
|
+
afterUpdate: createAfterUpdateEffects(
|
|
1451
|
+
eventEffects,
|
|
1452
|
+
(ctx) => ({ after: ctx.after }),
|
|
1453
|
+
{
|
|
1454
|
+
onRuleError: (r) =>
|
|
1455
|
+
logger.error(`[afterUpdate] Effect failed: ${r.description}`, r.error),
|
|
1456
|
+
},
|
|
1457
|
+
),
|
|
1458
|
+
afterBatch: async ({ updated }) => {
|
|
1459
|
+
// Runs ONCE after batch.commit() — ideal for deduplicating recalculations
|
|
1460
|
+
const workshopIds = new Set(updated.map((u) => u.pathArgs[0]));
|
|
1461
|
+
await withActor({ userId: "system" }, async () => {
|
|
1462
|
+
for (const wid of workshopIds) {
|
|
1463
|
+
await recalculateWorkshop(wid);
|
|
1464
|
+
}
|
|
1465
|
+
});
|
|
1466
|
+
},
|
|
1467
|
+
onAfterError: (err, phase) => {
|
|
1468
|
+
logger.error(`[preventionEvents:${phase}]`, err);
|
|
1469
|
+
},
|
|
1470
|
+
},
|
|
1471
|
+
},
|
|
1472
|
+
},
|
|
1473
|
+
});
|
|
1474
|
+
```
|
|
1475
|
+
|
|
1476
|
+
**Execution guarantees:**
|
|
1477
|
+
- Every hook is **`await`ed before sending the HTTP response** (safe on Cloud Functions v2, where CPU is throttled once the response finishes).
|
|
1478
|
+
- Post-write hook errors (and errors from follow-up `changesNeeded` patches) are **caught and routed to `hooks.onAfterError` / `onHookError`** (falling back to the Hono `logger` or `console.error`) so a committed write never returns a misleading HTTP 500.
|
|
1479
|
+
- The `actorResolver` `AsyncLocalStorage` scope remains active during hook execution: cascading repository writes automatically inherit the HTTP actor's `_historyMeta`, or can override it with `withActor({ userId: "system" }, ...)`.
|
|
1480
|
+
|
|
1481
|
+
---
|
|
1482
|
+
|
|
1483
|
+
## Automatic History Audit Headers in OpenAPI (`historyHeaders`)
|
|
1484
|
+
|
|
1485
|
+
When a repository has shadow history enabled (`history: { enabled: true }` with `autoInjectMeta !== false`), the CRUD OpenAPI 3.1 generator automatically exposes the optional audit headers (`X-History-Reason`, `X-History-Comment`, or the custom header names configured in `actorResolver` / `createActorResolver`) as `in: "header"` parameters on write endpoints (`POST /:repo`, `PUT /:repo/:id`, `PATCH /:repo/:id`, `POST /:repo/batch`).
|
|
1486
|
+
|
|
1487
|
+
- Repositories without active shadow history (and read/delete endpoints) remain untouched.
|
|
1488
|
+
- Disabled shadow fields (e.g. `history.shadow.fields.comment = false`) or disabled resolver headers (`commentHeader: false`) are automatically omitted.
|
|
1489
|
+
- CORS `Access-Control-Allow-Headers` is automatically kept in sync with any custom `actorResolver` header names and `extraHeaders`.
|
|
1490
|
+
- Customize or opt out via `openapi.historyHeaders`:
|
|
1491
|
+
|
|
1492
|
+
```typescript
|
|
1493
|
+
export const api = servers.crud({
|
|
1494
|
+
basePath: "/api",
|
|
1495
|
+
openapi: {
|
|
1496
|
+
title: "My CRUD API",
|
|
1497
|
+
historyHeaders: {
|
|
1498
|
+
// Optional extra headers (string shorthand or full descriptor)
|
|
1499
|
+
extraHeaders: [
|
|
1500
|
+
"X-App-Source",
|
|
1501
|
+
{ name: "X-Correlation-Id", description: "Client trace identifier" },
|
|
1502
|
+
],
|
|
1503
|
+
},
|
|
1504
|
+
// Or set `historyHeaders: false` to omit history headers from OpenAPI
|
|
1505
|
+
},
|
|
1506
|
+
repos: { ... },
|
|
1507
|
+
});
|
|
1508
|
+
```
|
|
1509
|
+
|
|
1510
|
+
---
|
|
1511
|
+
|
|
1375
1512
|
## Missing Index Detection (`indexesError` & HTTP 424)
|
|
1376
1513
|
|
|
1377
1514
|
When a complex filter or compound query requires a composite index that has not yet been built in Firestore, the CRUD server automatically catches the Firestore `FAILED_PRECONDITION` error:
|
package/dist/llms.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# @lpdjs/firestore-repo-service (v3.0.
|
|
1
|
+
# @lpdjs/firestore-repo-service (v3.0.18)
|
|
2
2
|
|
|
3
3
|
> ⚡ Type-safe Firestore ORM with auto-generated repositories, advanced queries, relations with typed select, pagination with include, batch/bulk operations, aggregations and transactions.
|
|
4
4
|
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
3
|
-
import {
|
|
3
|
+
import { X as RelationalFieldMeta } from '../../types-BYPdlGSL.cjs';
|
|
4
4
|
import { ConfiguredRepository, FieldRole } from '../../index.cjs';
|
|
5
5
|
import { SecurityHeadersOptions } from '../index.cjs';
|
|
6
6
|
import { RepositoryConfig, FieldPath } from '../../index.cjs';
|
|
7
7
|
import { M as Middleware } from '../../firebase-auth-nG3prKoj.cjs';
|
|
8
8
|
import { AuthExtension } from '../auth/index.cjs';
|
|
9
9
|
export { h as MiniRouter, R as RouteHandler } from '../../firebase-auth-nG3prKoj.cjs';
|
|
10
|
-
import '../../types-
|
|
10
|
+
import '../../types-XvVG8_9J.cjs';
|
|
11
11
|
import 'hono';
|
|
12
|
-
import '../../actor-context-
|
|
12
|
+
import '../../actor-context-zNobm6nG.cjs';
|
|
13
13
|
import '../../read-Dfah1PPl.cjs';
|
|
14
14
|
import 'firebase-admin/firestore';
|
|
15
15
|
import '../../types-D6zvWzRt.cjs';
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
3
|
-
import {
|
|
3
|
+
import { X as RelationalFieldMeta } from '../../types-5Q7JDDba.js';
|
|
4
4
|
import { ConfiguredRepository, FieldRole } from '../../index.js';
|
|
5
5
|
import { SecurityHeadersOptions } from '../index.js';
|
|
6
6
|
import { RepositoryConfig, FieldPath } from '../../index.js';
|
|
7
7
|
import { M as Middleware } from '../../firebase-auth-nG3prKoj.js';
|
|
8
8
|
import { AuthExtension } from '../auth/index.js';
|
|
9
9
|
export { h as MiniRouter, R as RouteHandler } from '../../firebase-auth-nG3prKoj.js';
|
|
10
|
-
import '../../types-
|
|
10
|
+
import '../../types-BJ6MAavL.js';
|
|
11
11
|
import 'hono';
|
|
12
|
-
import '../../actor-context-
|
|
12
|
+
import '../../actor-context-zNobm6nG.js';
|
|
13
13
|
import '../../read-BPov7lws.js';
|
|
14
14
|
import 'firebase-admin/firestore';
|
|
15
15
|
import '../../types-D6zvWzRt.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var zod=require('zod'),firestore=require('firebase-admin/firestore'),crypto=require('crypto'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var he=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var Ot=Object.prototype.hasOwnProperty;var Ct=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Et=(e,t)=>{for(var n in t)he(e,n,{get:t[n],enumerable:true});},It=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of kt(t))!Ot.call(e,o)&&o!==n&&he(e,o,{get:()=>t[o],enumerable:!(r=vt(t,o))||r.enumerable});return e};var Pt=e=>It(he({},"__esModule",{value:true}),e);var St={};Et(St,{DEFAULT_HTML_CSP:()=>Rt,securityHeaders:()=>On});function On(e={}){let t=e.csp===void 0?Rt:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,r=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(i,c,u)=>{typeof c?.setHeader=="function"&&(c.setHeader("X-Content-Type-Options","nosniff"),n&&c.setHeader("X-Frame-Options",n),r&&c.setHeader("Referrer-Policy",r),o&&c.setHeader("Cache-Control",o),t&&c.setHeader("Content-Security-Policy",t)),await u();}}var bt,xt,Rt,At=Ct(()=>{"use strict";bt="https://cdn.jsdelivr.net",xt="https://www.gstatic.com",Rt=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${bt} ${xt}`,`style-src 'self' 'unsafe-inline' ${bt}`,`connect-src 'self' ${xt} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Fe="preserve";function be(){return Fe}function Dt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Ne(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(Dt(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function $e(e){return e}var xe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Re(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=xe.length*4||(e+=xe.charAt(r%xe.length));}}return e}function Ze(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function He(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(y=>y.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let y=r[0];return {rawPath:e,collectionId:y,collectionPath:y,parentKeys:[],documentPathTemplate:n?null:`${y}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,i=o?r.slice(0,-1):r,c=i[i.length-1],u=i.join("/"),p=i.slice(0,-1).map(Ze).filter(y=>y!==null),m=o?r.join("/"):`${u}/{${t}}`;return {rawPath:e,collectionId:c,collectionPath:u,parentKeys:p,documentPathTemplate:m,hasTemplate:true}}function Me(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:i,isGroup:c}=t,u=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(u&&i){let d=u.split("/").filter(Boolean),p=i.split("/").filter(Boolean);if(d.length===p.length){let m=[];for(let y=0;y<p.length;y++)Ze(p[y])!==null&&m.push(d[y]);if(m.length>0)return m}}if(o&&o.length>0){let d=o.length+1;if(u){let m=u.split("/").filter(Boolean),y=[];for(let b=1;b<m.length;b+=2)y.push(m[b]);if(y.length>=d)return y.slice(y.length-d)}let p=r?e[r]:void 0;if(typeof p=="string"&&p.trim()!==""){let m=[],y=true;for(let b of o){let O=e[b];if(typeof O=="string"&&O.trim()!=="")m.push(O);else {y=false;break}}if(y)return [...m,p]}}if(u){let d=u.split("/").filter(Boolean),p=[];for(let m=1;m<d.length;m+=2)p.push(d[m]);if(p.length>0)return !c&&(!o||o.length===0)?[p[p.length-1]]:p}}function Be(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var _t=new Set(["<","<=",">",">=","!="]),qt=new Set(["array-contains","array-contains-any"]);function Se(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Ft(e){return He(e).collectionId||e}function Nt(e,t,n,r,o){let i=[],c=new Set;for(let d of r)if(d.op==="=="||d.op==="in"||d.op==="not-in"){if(c.has(d.field))continue;c.add(d.field),i.push({fieldPath:d.field,order:"ASCENDING"});}for(let d of r)if(qt.has(d.op)){if(c.has(d.field))continue;c.add(d.field),i.push({fieldPath:d.field,arrayConfig:"CONTAINS"});}for(let d of r)if(_t.has(d.op)){if(c.has(d.field))continue;c.add(d.field);let p=o?.field===d.field?Se(o.dir):"ASCENDING";i.push({fieldPath:d.field,order:p});}if(o&&!c.has(o.field)&&i.push({fieldPath:o.field,order:Se(o.dir)}),i.length===1&&n)return Ht(e,t,i[0]);let u=o&&i.some(d=>d.fieldPath===o.field)?Se(o.dir):"ASCENDING";return i.push({fieldPath:"__name__",order:u}),$t(e,t,n,i)}function $t(e,t,n,r,o="(default)"){let i=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,c=[...ve(1,i),...ce(2,n?2:1)];for(let p of r)c.push(...Ue(3,Ke(p)));let u=o==="(default)"?"-default-":o,d=encodeURIComponent(Le(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${u}/indexes?create_composite=${d}`}function Zt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Ae(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Te(e,t){return e<<3|t}function ve(e,t){let n=Array.from(new TextEncoder().encode(t));return [Te(e,2),...Ae(n.length),...n]}function ce(e,t){return [Te(e,0),...Ae(t)]}function Ue(e,t){return [Te(e,2),...Ae(t.length),...t]}function Ke(e){let t=[...ve(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ce(3,1)):t.push(...ce(2,e.order==="DESCENDING"?2:1)),t}function Le(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function Ht(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,i=[...ve(1,o),...ce(2,2),...Ue(3,Ke(n))],c=r==="(default)"?"-default-":r,u=encodeURIComponent(Le(i));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes/automatic?create_exemption=${u}`}function Mt(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function Bt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ge(e,t){let n=e??{},r=Bt(e),o;if(r&&(o=n.message?Zt(n.message):void 0,!o)){let i=Mt(t.ref);if(i){let c=Ft(t.path);o=Nt(i,c,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}function de(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!de(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof firestore.Timestamp||t instanceof firestore.Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return false;for(let i of r)if(!Object.prototype.hasOwnProperty.call(t,i)||!de(e[i],t[i],n))return false;return true}return false}function le(e,t){let n=e||{},r={},o={...n};for(let[i,c]of Object.entries(t||{})){let u=n[i];de(u,c)||(r[i]=c,o[i]=c);}return {before:n,after:o,changes:r}}function Ut(e){return e}async function We(e,t,n){let r=e.changes||{};for(let o of Object.keys(r)){let i=t[o];if(i&&i.length>0){for(let c of i)if(await c.rule({diff:e,key:o,user:n,authenticatedUser:n})===false)return {allowed:false,reason:c.description}}}return {allowed:true}}function Kt(e){return async t=>We(t.diff,e,t.user)}var ke=1e3;function Ve(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),ke)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>ke?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${ke}`}:{success:true,value:n}}function Ee(e,t,n=200){let r=$e(t);return e.json(r,n)}function V(e,t,n,r=200){return Ee(e,{success:true,data:t,meta:n},r)}function x(e,t,n=400){return Ee(e,{success:false,error:t},n)}async function Oe(e,t,n,r,o,i){let c=Ge(t,n),u=c.type==="index",d=u?424:500,m={success:false,error:u?c.message:o&&t instanceof Error?t.message:r};if(u&&(m.errorType="index",c.indexUrl&&(m.indexUrl=c.indexUrl,i)))try{let y=i({indexUrl:c.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});y instanceof Promise&&await y;}catch(y){o&&console.error("[crudServer] Error in indexesError callback:",y);}return Ee(e,m,d)}function J(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>Ne(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[i,c]of Object.entries(r))o[i]=J(c);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(J(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return J(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return J(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let i=J(r);return typeof o=="function"?i.default(o()):i.default(o)}}return e}function Lt(e,t,n=[]){let r=e.shape,o={},i=t&&t.length>0?t:Object.keys(r);for(let c of i){if(n.includes(c))continue;let u=c.split(".")[0];u&&r[u]&&(o[u]=r[u]);}return zod.z.object(o)}function Ce(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function Xe(e,t){let n=t.split("."),r=Ce(e);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let c=r?.shape;if(!c||!c[i])return;let u=c[i];if(o===n.length-1)return u;r=Ce(u);}return r}function Q(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[i,c]of Object.entries(r))o[i]=Q(c);return zod.z.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=Q(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=Q(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?Q(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(c=>Q(c));return o.some((c,u)=>c!==r[u])?zod.z.union(o):e}return e}function pe(e,t,n,r=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let i=t,c={},u={};for(let[d,p]of Object.entries(i))if(d.includes(".")){let m=d.split(".")[0];if(o.includes(d)||o.includes(m))continue;if(n&&n.length>0&&!n.includes(d)&&!n.includes(m))return {success:!1,error:`Field '${d}' is not allowed for this operation`};let y=Xe(e,d);if(!y)return {success:!1,error:`Field '${d}' does not exist in schema`};let b=r?Q(y):y,N=(be()==="normalize"?J(b):b).parse(p);c[d]=N;}else u[d]=p;if(Object.keys(u).length>0||Object.keys(c).length===0){let d=Lt(e,n,o),p=r?Q(d):d,y=(be()==="normalize"?J(p):p).parse(u);Object.assign(c,y);}return {success:!0,data:c}}catch(i){return i instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${i.issues.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var Ye={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function re(e){return Ye[e]??e}function Gt(e){return e in Ye}function fe(e,t,n,r){let o=Xe(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let i=r?re(r):void 0,c=Ce(o),u=Be(c);if(i==="array-contains"){let m=u??o;if(typeof m.safeParse=="function"){let y=m.safeParse(n);return y.success?{success:true,data:y.data}:{success:false,error:y.error.issues.map(O=>O.message).join(", ")}}return {success:true,data:n}}if(i==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let m=u??o,y=[];for(let b of n)if(typeof m.safeParse=="function"){let O=m.safeParse(b);if(O.success)y.push(O.data);else return {success:false,error:O.error.issues.map(C=>C.message).join(", ")}}else y.push(b);return {success:true,data:y}}let d=o.safeParse(n);if(d.success)return {success:true,data:d.data};if(Array.isArray(n)){let m=u??o,y=[];for(let b of n)if(typeof m.safeParse=="function"){let O=m.safeParse(b);if(O.success)y.push(O.data);else return {success:false,error:O.error.issues.map(C=>C.message).join(", ")}}else y.push(b);return {success:true,data:y}}return {success:false,error:d.error.issues.map(m=>m.message).join(", ")}}function Wt(e,t){let n=[],r=t?new Set(t):null;for(let[o,i]of Object.entries(e)){if(i===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let c=Array.isArray(i)?i[0]:i;if(c===void 0||c==="")continue;let u=o.lastIndexOf("__"),d,p="==";if(u!==-1){let y=o.slice(0,u),b=o.slice(u+2);Gt(b)?(d=y,p=re(b)):(d=o,p="==");}else d=o;if(r&&!r.has(d))continue;let m=c;p==="in"||p==="not-in"||p==="array-contains-any"?m=c.split(",").map(y=>Je(y.trim())):m=Je(c),n.push({field:d,op:p,value:m});}return n}function Je(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function ye(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Qe(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let i=e.repo.ref,c=i?.firestore;if(r&&c&&typeof c.doc=="function"){let u=await c.doc(r).get();if(u.exists)return u}if(o&&o.includes("/")&&c&&typeof c.doc=="function"){let u=await c.doc(o).get();if(u.exists)return u}if(o&&typeof i.doc=="function"){let u=await i.doc(o).get();if(u.exists)return u}return}catch{return}}function et(e,t,n,r){async function o(f,s,g,a){if(!s.rules)return {allowed:true};let w=s.rules?.[g];if(!w)return {allowed:false,errorResponse:x(f,`Operation "${g}" is not allowed for this repository`,403)};try{let h=await w(a);return h===!1?{allowed:!1,errorResponse:x(f,"Forbidden",403)}:typeof h=="string"?{allowed:!1,errorResponse:x(f,h,403)}:typeof h=="object"&&h!==null&&!h.allowed?{allowed:!1,errorResponse:x(f,h.reason||"Forbidden",403)}:{allowed:!0}}catch(h){let R=n&&h instanceof Error?h.message:"Forbidden";return {allowed:false,errorResponse:x(f,R,403)}}}async function i(f,s,g,a){if(!f.rules)return a;let w=f.rules?.filter;if(!w)return a;let h=[];for(let R of a)try{await w({user:s,doc:R,params:g})&&h.push(R);}catch{}return h}function c(f){return f.get("user")??f.get("docsUser")??null}function u(f,s){if(!f){let g=s.req.path.split("/");for(let a of g)if(e[a]){f=a;break}}return !f||!e[f]?null:e[f]??null}function d(f,s){return Me(f,{pathKey:s.pathKey,documentKey:s.documentKey,parentKeys:s.parentKeys,documentPathTemplate:s.documentPathTemplate,isGroup:s.isGroup})}async function p(f,s){let g=`by${f.documentKey.charAt(0).toUpperCase()}${f.documentKey.slice(1)}`,a=f.repo.get[g];if(typeof a=="function")try{let h=await a(s);if(h)return h}catch{}return (await f.repo.query.by({where:[[f.documentKey,"==",s]],limit:1}))[0]??null}async function m(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);let w=c(s),h=await o(s,a,"list",{user:w,query:s.req.query(),params:g});if(!h.allowed)return h.errorResponse;let R=[],v;try{let l=s.req.query(),T=Ve(l.pageSize,a.pageSize);if(!T.success)return x(s,T.error,400);let P=T.value,D=l.cursor,_=l.direction?.toLowerCase()==="prev"?"prev":"next",E=l.orderBy,A=l.orderDir?.toLowerCase()==="desc"?"desc":"asc",$=l.select,L=$?$.split(",").map(M=>M.trim()):void 0,I=l.withTotal,k=I==="true"||I==="1"||I===!0,j;a.allowedIncludes&&l.includes&&(j=(typeof l.includes=="string"?l.includes.split(",").map(G=>G.trim()):Array.isArray(l.includes)?l.includes:[]).filter(G=>typeof G=="string"&&a.allowedIncludes.includes(G)),j?.length===0&&(j=void 0));let q=Wt(l,a.filterableFields);R=q.map(M=>({field:M.field,op:M.op,value:String(M.value??"")})),E&&(v={field:E,dir:A});let U={pageSize:P,direction:_,...k?{withTotal:!0}:{}};if(D)try{let M=typeof D=="string"?JSON.parse(D):D;U.cursor=await Qe(a,M);}catch{}if(E){if(a.orderableFields&&!a.orderableFields.includes(E))return x(s,`Field not orderable: ${E}`,400);U.orderBy=[{field:E,direction:A}];}if(q.length>0){U.where=[];for(let M of q){let G=fe(a.schema,M.field,M.value,M.op);if(!G.success)return x(s,`Invalid filter value for '${M.field}': ${G.error}`,400);U.where.push([M.field,M.op,G.data]);}}L&&(U.select=L),j&&(U.include=j);let Z=await a.repo.query.paginate(U),Tt={items:await i(a,c(s),g,Z.data),hasNextPage:Z.hasNextPage,hasPrevPage:Z.hasPrevPage,nextCursor:ye(Z.nextCursor),prevCursor:ye(Z.prevCursor),...Z.totalCount!==void 0?{totalCount:Z.totalCount,totalCountIsExact:Z.totalCountIsExact}:{}};return V(s,Tt,{pageSize:P,hasMore:Z.hasNextPage,...Z.totalCount!==void 0?{totalCount:Z.totalCount,totalCountIsExact:Z.totalCountIsExact}:{}})}catch(l){return await Oe(s,l,{repoName:g.repoName||a.name,ref:a.repo.ref,path:a.path,isGroup:!!a.isGroup,filters:R,sort:v},"Failed to fetch documents",n,r)}}async function y(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);let w=c(s),h=await o(s,a,"list",{user:w,query:f.input||{},params:g});if(!h.allowed)return h.errorResponse;let R=[],v;try{let l=f.input||{},T=Ve(l.pageSize,a.pageSize);if(!T.success)return x(s,T.error,400);let P=T.value,D=l.direction==="prev"?"prev":"next";l.where&&(R=l.where.map(I=>({field:String(I[0]),op:I[1],value:String(I[2]??"")}))),l.orderBy&&l.orderBy[0]&&(v={field:l.orderBy[0].field,dir:l.orderBy[0].direction==="desc"?"desc":"asc"});let _=l.withTotal===!0||String(l.withTotal)==="true",E={pageSize:P,direction:D,..._?{withTotal:!0}:{}};if(l.cursor)try{let I=typeof l.cursor=="string"?JSON.parse(l.cursor):l.cursor;E.cursor=await Qe(a,I);}catch{}if(a.allowedIncludes&&l.includes&&l.includes.length>0){let I=l.includes.filter(k=>typeof k=="string"?a.allowedIncludes.includes(k):typeof k=="object"&&k!==null&&"relation"in k&&typeof k.relation=="string"?a.allowedIncludes.includes(k.relation):!1);I.length>0&&(E.include=I);}if(l.where&&l.where.length>0){if(a.filterableFields){let k=new Set(a.filterableFields),j=l.where.filter(q=>!k.has(q[0]));if(j.length>0){x(s,`Fields not filterable: ${j.map(q=>q[0]).join(", ")}`,400);return}}let I=[];for(let k of l.where){let j=re(k[1]),q=fe(a.schema,k[0],k[2],j);if(!q.success){x(s,`Invalid filter value for '${k[0]}': ${q.error}`,400);return}I.push([k[0],j,q.data]);}E.where=I;}if(l.orWhere&&l.orWhere.length>0){if(a.filterableFields){let k=new Set(a.filterableFields),j=l.orWhere.filter(q=>!k.has(q[0]));if(j.length>0){x(s,`Fields not filterable: ${j.map(q=>q[0]).join(", ")}`,400);return}}let I=[];for(let k of l.orWhere){let j=re(k[1]),q=fe(a.schema,k[0],k[2],j);if(!q.success){x(s,`Invalid filter value for '${k[0]}': ${q.error}`,400);return}I.push([k[0],j,q.data]);}E.orWhere=I;}if(l.orWhereGroups&&l.orWhereGroups.length>0){if(a.filterableFields){let k=new Set(a.filterableFields);for(let j of l.orWhereGroups){let q=j.filter(U=>!k.has(U[0]));if(q.length>0){x(s,`Fields not filterable: ${q.map(U=>U[0]).join(", ")}`,400);return}}}let I=[];for(let k of l.orWhereGroups){let j=[];for(let q of k){let U=re(q[1]),Z=fe(a.schema,q[0],q[2],U);if(!Z.success){x(s,`Invalid filter value for '${q[0]}': ${Z.error}`,400);return}j.push([q[0],U,Z.data]);}I.push(j);}E.orWhereGroups=I;}if(l.orderBy&&l.orderBy.length>0){if(a.orderableFields){let I=new Set(a.orderableFields),k=l.orderBy.filter(j=>!I.has(j.field));if(k.length>0){x(s,`Fields not orderable: ${k.map(j=>j.field).join(", ")}`,400);return}}E.orderBy=l.orderBy;}l.select&&l.select.length>0&&(E.select=l.select);let A=await a.repo.query.paginate(E),L={items:await i(a,c(s),g,A.data),hasNextPage:A.hasNextPage,hasPrevPage:A.hasPrevPage,nextCursor:ye(A.nextCursor),prevCursor:ye(A.prevCursor),...A.totalCount!==void 0?{totalCount:A.totalCount,totalCountIsExact:A.totalCountIsExact}:{}};return V(s,L,{pageSize:P,hasMore:A.hasNextPage,...A.totalCount!==void 0?{totalCount:A.totalCount,totalCountIsExact:A.totalCountIsExact}:{}})}catch(l){return await Oe(s,l,{repoName:g.repoName||a.name,ref:a.repo.ref,path:a.path,isGroup:!!a.isGroup,filters:R,sort:v},"Failed to query documents",n,r)}}async function b(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);let w=g.id;if(!w)return x(s,"Document ID required",400);try{let h=await p(a,w);if(!h)return x(s,"Document not found",404);let R=c(s),v=await o(s,a,"get",{user:R,doc:h,params:g});if(!v.allowed)return v.errorResponse;if(a.rules?.filter)try{if(!await a.rules.filter({user:R,doc:h,params:g}))return x(s,"Document not found",404)}catch{return x(s,"Document not found",404)}return V(s,h)}catch(h){return await Oe(s,h,{repoName:g.repoName||a.name,ref:a.repo.ref,path:a.path,isGroup:!!a.isGroup,filters:[{field:a.documentKey,op:"==",value:w}]},"Failed to fetch document",n,r)}}async function O(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);try{let w=f.input||{},h=c(s),R=await o(s,a,"create",{user:h,body:w,params:g});if(!R.allowed)return R.errorResponse;let v=pe(a.schema,w,a.createFields,!1,a.systemKeys);if(!v.success)return x(s,v.error,400);if(a.validate){let T=await a.validate(v.data,"create");if(T)return x(s,T,400)}let l;if(a.isGroup&&a.parentKeys&&a.parentKeys.length>0){let T={...v.data},P=a.parentKeys.filter(D=>T[D]===void 0||T[D]===null||typeof T[D]=="string"&&T[D].trim()==="");if(P.length>0){x(s,`Missing parent key(s) for subcollection create: ${P.join(", ")}`,400);return}if(typeof a.repo.create=="function")l=await a.repo.create(T);else {let D=a.parentKeys.map(E=>String(T[E])),_=T[a.documentKey]||Re();l=await a.repo.set(...D,_,T);}}else l=await a.repo.create(v.data);return V(s,l,void 0,201)}catch(w){let h=n&&w instanceof Error?w.message:"Failed to create document";return x(s,h,500)}}async function N(f,s){let g=f.c,a=g.req.param(),w=u(a.repoName,g);if(!w)return x(g,"Repository not found",404);let h=a.id;if(!h)return x(g,"Document ID required",400);try{let R=f.input||{},v=await p(w,h);if(!v)return x(g,"Document not found",404);let l=pe(w.schema,R,w.mutableFields,s,w.systemKeys);if(!l.success)return x(g,l.error,400);if(w.validate){let A=await w.validate(l.data,"update");if(A)return x(g,A,400)}let T=le(v,l.data),P=c(g),D=await o(g,w,"update",{user:P,doc:v,body:l.data,diff:T,params:a});if(!D.allowed)return D.errorResponse;let _=d(v,w)??[h],E=await w.repo.update(..._,l.data);return V(g,E)}catch(R){let v=n&&R instanceof Error?R.message:"Failed to update document";return x(g,v,500)}}async function C(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);if(!a.allowDelete)return x(s,"Delete not allowed for this repository",403);let w=g.id;if(!w)return x(s,"Document ID required",400);try{let h=await p(a,w);if(!h)return x(s,"Document not found",404);let R=c(s),v=await o(s,a,"delete",{user:R,doc:h,params:g});if(!v.allowed)return v.errorResponse;let l=d(h,a)??[w];return await a.repo.delete(...l),V(s,{deleted:!0})}catch(h){let R=n&&h instanceof Error?h.message:"Failed to delete document";return x(s,R,500)}}function S(f){return f.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400"})}async function z(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);try{let w=f.input||{};if(!Array.isArray(w.operations))return x(s,"operations array is required",400);let h=c(s),R=a.repo.batch.create(),v=[];for(let l of w.operations){if(!l.type||!["create","update","delete"].includes(l.type))return x(s,"Invalid operation type",400);if(l.type==="create"){let T=await o(s,a,"create",{user:h,body:l.data,params:g});if(!T.allowed)return T.errorResponse;let P=pe(a.schema,l.data,a.createFields,!1,a.systemKeys);if(!P.success)return x(s,P.error,400);let D=l.data[a.documentKey]||Re(),_={...P.data};if(a.createdKey&&_[a.createdKey]===void 0&&(_[a.createdKey]=new Date),a.isGroup&&a.parentKeys){let E=a.parentKeys.map(A=>_[A]);R.set(...E,D,_);}else R.set(D,_);v.push({op:"create",id:D});}else if(l.type==="update"){if(!l.id)return x(s,"id required for update",400);let T=await p(a,l.id);if(!T)return x(s,`Document ${l.id} not found`,404);let P=pe(a.schema,l.data,a.mutableFields,!0,a.systemKeys);if(!P.success)return x(s,P.error,400);if(a.validate){let A=await a.validate(P.data,"update");if(A)return x(s,A,400)}let D=le(T,P.data),_=await o(s,a,"update",{user:h,doc:T,body:P.data,diff:D,params:g});if(!_.allowed)return _.errorResponse;let E=d(T,a)??[l.id];R.update(...E,P.data),v.push({op:"update",id:l.id});}else if(l.type==="delete"){if(!a.allowDelete)return x(s,"Delete not allowed",403);if(!l.id)return x(s,"id required for delete",400);let T=await p(a,l.id);if(!T)return x(s,`Document ${l.id} not found`,404);let P=await o(s,a,"delete",{user:h,doc:T,params:g});if(!P.allowed)return P.errorResponse;let D=d(T,a)??[l.id];R.delete(...D),v.push({op:"delete",id:l.id});}}return await R.commit(),V(s,{results:v})}catch(w){let h=n&&w instanceof Error?w.message:"Batch operation failed";return x(s,h,500)}}return {handleList:m,handleQuery:y,handleGet:b,handleCreate:O,handleUpdate:N,handleDelete:C,handleBatch:z,handleOptions:S}}function te(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function H(e){return {$ref:`#/components/schemas/${e}`}}function F(e){return {description:e,content:{"application/json":{schema:H("ErrorResponse")}}}}function ee(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Vt(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated due to OR conditions (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function se(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function Jt(e,t){let n=t.split("."),r=se(e);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let c=r?.shape;if(!c||!c[i])return;let u=c[i];if(o===n.length-1)return u;r=se(u);}return r}function Y(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=o=>{let i=zodToOpenapi.getOpenApiMetadata(e);return i&&typeof o.openapi=="function"?o.openapi(i):o};if(n==="ZodObject"||n==="object"){let o=e.shape,i={};for(let[c,u]of Object.entries(o))i[c]=Y(u);return r(zod.z.object(i).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let i=Y(o);return i===o?e:r(i.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let i=Y(o);return i===o?e:r(i.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(Y(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let i=o.map(u=>Y(u));return i.some((u,d)=>u!==o[d])?r(zod.z.union(i)):e}return e}function Ie(e,t="",n=0){if(n>5)return [];let o=se(e)?.shape;if(!o)return [];let i=[];for(let[c,u]of Object.entries(o)){let d=t?`${t}.${c}`:c,p=se(u);p?.shape&&typeof p.shape=="object"?(i.push({path:d,zodSchema:u}),i.push(...Ie(p,d,n+1))):i.push({path:d,zodSchema:u});}return i}function Qt(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Jt(e.schema,t)})):Ie(e.schema)}function tt(e){if(!e)return {type:"string"};let t=te(e);return delete t.$schema,delete t.title,t}function rt(){return {type:"object",properties:{where:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3}},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string"},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string"},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function Xt(e){let t=Qt(e),n=e.orderableFields??t.map(c=>c.path),r=t.map(c=>c.path);if(t.length===0)return rt();let o=[];for(let{path:c,zodSchema:u}of t){let d=tt(u),p=se(u),y=p?._zod?.def?.type==="array"||p?._def?.typeName==="ZodArray"||p?._def?.type==="array"?tt(p?._zod?.def?.element??p?._def?.type??p?._def?.element):d;o.push({type:"array",description:`Condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},d],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${c}' (in, not-in)`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:d}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains","contains"]},y],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:y}],minItems:3,maxItems:3});}let i={oneOf:o};return {type:"object",properties:{where:{type:"array",items:i,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:i,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:i},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:r},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function Yt(e,t,n,r,o,i=null,c="QueryRequestBody"){let u={},d=e.name,p=`${t}/${e.name}`,m=`${p}/{${e.documentKey}}`,y={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};u[p]={post:{operationId:`create${W(e.name)}`,summary:`Create a ${K(e.name)}`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:H(r??n)}}},responses:{201:ee("Document created",H(n)),400:F("Validation error"),403:F("Forbidden"),500:F("Internal server error")}}},u[`${p}/query`]={post:{operationId:`query${W(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:H(c)}}},responses:{200:Vt(H(n)),400:F("Invalid query"),403:F("Forbidden"),424:F("Missing composite index (includes indexUrl in response)"),500:F("Internal server error")}}},u[`${p}/batch`]={post:{operationId:`batch${W(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:H(`${n}BatchRequest`)}}},responses:{200:ee("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}}};let b={};return b.get={operationId:`get${W(K(e.name))}`,summary:`Get a single ${K(e.name)}`,tags:[d],parameters:[y],responses:{200:ee("Document found",H(n)),400:F("Document ID required"),403:F("Forbidden"),404:F("Document not found"),424:F("Missing composite index (includes indexUrl in response)"),500:F("Internal server error")}},b.put={operationId:`update${W(K(e.name))}`,summary:`Update a ${K(e.name)} (full replace)`,tags:[d],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:H(o??n)}}},responses:{200:ee("Document updated",H(n)),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}},b.patch={operationId:`patch${W(K(e.name))}`,summary:`Partially update a ${K(e.name)}`,tags:[d],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:H(i??o??n)}}},responses:{200:ee("Document patched",H(n)),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}},e.allowDelete&&(b.delete={operationId:`delete${W(K(e.name))}`,summary:`Delete a ${K(e.name)}`,tags:[d],parameters:[y],responses:{200:ee("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:F("Document ID required"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}}),u[m]=b,u}function Pe(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:i,servers:c,auth:u=false}=n,d=t==="/"?"":t.replace(/\/$/,""),p={},m={},y=[];p.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},p.QueryRequestBody=rt();for(let[C,S]of Object.entries(e)){let z=W(K(C)),f=`${z}Create`,s=`${z}Update`,g=`${z}Patch`,a=`${z}QueryRequestBody`;p[z]=te(S.schema),p[a]=Xt(S);let w=A=>{let $={},L=Ie(S.schema);for(let{path:I,zodSchema:k}of L){let j=I.split(".")[0];S.systemKeys.includes(j)||S.systemKeys.includes(I)||A&&A.length>0&&!A.includes(I)&&!A.includes(j)||(I.includes(".")?$[I]=k.optional():$[I]=k);}return $},h=null,R=w(S.createFields);if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let A=S.schema?.shape??{};for(let $ of S.parentKeys)!R[$]&&A[$]&&(R[$]=A[$]);}if(Object.keys(R).length>0){let A=te(zod.z.object(R));if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let $=new Set(Array.isArray(A.required)?A.required:[]);for(let L of S.parentKeys)A.properties?.[L]&&$.add(L);$.size>0&&(A.required=Array.from($));}p[f]=A,h=f;}let v=null,l=null,T=w(S.mutableFields);if(Object.keys(T).length>0){let A=zod.z.object(T);p[s]=te(A),v=s,p[g]=te(Y(A)),l=g;}else p[g]=te(Y(S.schema)),l=g;let P=`${z}BatchCreateOperation`,D=`${z}BatchUpdateOperation`,_=`${z}BatchDeleteOperation`;p[P]={type:"object",title:`${z} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:H(h??z)},required:["type","data"]},p[D]={type:"object",title:`${z} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:H(l??v??z)},required:["type","id","data"]},S.allowDelete&&(p[_]={type:"object",title:`${z} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),p[`${z}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[H(P),H(D),...S.allowDelete?[H(_)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let E=Yt(S,d,z,h,v,l,a);Object.assign(m,E),y.push({name:C,description:`Operations on ${C} (collection: ${S.path})`});}let b={},O;return u==="basic"?(b.basicAuth={type:"http",scheme:"basic"},O=[{basicAuth:[]}]):u==="bearer"&&(b.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},O=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...i?{description:i}:{}},...c&&c.length>0?{servers:c}:{},paths:m,components:{schemas:p,...Object.keys(b).length>0?{securitySchemes:b}:{}},...O?{security:O}:{},tags:y}}function W(e){return e.charAt(0).toUpperCase()+e.slice(1)}function K(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var ne=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var ie=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},ae=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function ot(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function st(e,t){return t instanceof ne?e.json({success:false,error:"Validation failed",issues:ot(t.zodError)},400):t instanceof ie?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof ae?e.json({success:false,error:"Output validation failed",issues:ot(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var it="Successful response",at="Error response";function B(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,r=n._zod?.def??n.def;if(!r)return;if(r.type==="custom"){let i=zodToOpenapi.getOpenApiMetadata(n);i?.type||zod.z.globalRegistry.add(n,{...i??{},type:"object"});return}if(r.innerType&&B(r.innerType,t),r.element&&B(r.element,t),r.valueType&&B(r.valueType,t),r.keyType&&B(r.keyType,t),r.left&&B(r.left,t),r.right&&B(r.right,t),r.in&&B(r.in,t),r.out&&B(r.out,t),typeof r.getter=="function")try{B(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let i of r.options)B(i,t);if(Array.isArray(r.items))for(let i of r.items)B(i,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let i of Object.values(o))B(i,t);}function De(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)De(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))De(n);}function on(e){return e==="get"?"query":"json"}function sn(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function an(e){if(typeof e.safeParse=="function")return {description:at,schema:e};let t=e;return {description:t.description??at,schema:t.schema}}function dt(e,t,n,r){let o=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[u,d]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",u,d);for(let u of e){let d=u.method,p=u.source??on(d),m=dn(t,u.path??"/"),y=u.status??200;u.input&&B(u.input);let b=cn(d,p,u.input),O=ct(p,u.input,"query"),N=ct(p,u.input,"param"),C=ln(d,m),S=sn(u.output,r);S&&B(S);let z={[y]:S?{description:it,content:{"application/json":{schema:S}}}:{description:it}};if(r?.errors)for(let[f,s]of Object.entries(r.errors)){let{description:g,schema:a}=an(s);a&&B(a),z[f]=a?{description:g,content:{"application/json":{schema:a}}}:{description:g};}o.registerPath({method:d,path:un(m),operationId:C,summary:u.summary,description:u.description,tags:u.tags,deprecated:u.deprecated,security:u.security,request:{...O?{query:O}:{},...N?{params:N}:{},...b?{body:b}:{}},responses:z});}let c=new zodToOpenapi.OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return De(c),c}function cn(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function ct(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function un(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function dn(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function ln(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function lt(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
1
|
+
'use strict';var async_hooks=require('async_hooks'),zod=require('zod'),firestore=require('firebase-admin/firestore'),crypto=require('crypto'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server');var Ae=Object.defineProperty;var Nt=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Mt=Object.prototype.hasOwnProperty;var $t=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Zt=(e,t)=>{for(var n in t)Ae(e,n,{get:t[n],enumerable:true});},Bt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of qt(t))!Mt.call(e,o)&&o!==n&&Ae(e,o,{get:()=>t[o],enumerable:!(r=Nt(t,o))||r.enumerable});return e};var Ut=e=>Bt(Ae({},"__esModule",{value:true}),e);var _t={};Zt(_t,{DEFAULT_HTML_CSP:()=>jt,securityHeaders:()=>Wn});function Wn(e={}){let t=e.csp===void 0?jt:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,r=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(i,c,d)=>{typeof c?.setHeader=="function"&&(c.setHeader("X-Content-Type-Options","nosniff"),n&&c.setHeader("X-Frame-Options",n),r&&c.setHeader("Referrer-Policy",r),o&&c.setHeader("Cache-Control",o),t&&c.setHeader("Content-Security-Policy",t)),await d();}}var Ht,Dt,jt,zt=$t(()=>{"use strict";Ht="https://cdn.jsdelivr.net",Dt="https://www.gstatic.com",jt=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Ht} ${Dt}`,`style-src 'self' 'unsafe-inline' ${Ht}`,`connect-src 'self' ${Dt} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var re="X-History-Reason",oe="X-History-Comment",Ke=Symbol.for("@lpdjs/firestore-repo-service:actorResolverHeaders"),ke=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),Ce=globalThis,Lt=Ce[ke]??(Ce[ke]=new async_hooks.AsyncLocalStorage);function Wt(e,t){if(!t.includes("."))return e[t];let n=e;for(let r of t.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function Be(e,t){for(let n of t){let r=Wt(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function Ue(e,t){if(t===false)return;let n=e?.req?.header;if(typeof n!="function")return;let r=n.call(e.req,t);return typeof r=="string"&&r.length>0?r:void 0}function Le(e={}){let t=e.contextKeys??["user","docsUser"],n=e.userIdFields??["uid","id","sub"],r=e.userEmailFields??["email"],o=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,i=e.commentHeader===void 0?"x-history-comment":e.commentHeader,c=e.reasonHeader===void 0?re:e.reasonHeader,d=e.commentHeader===void 0?oe:e.commentHeader,u=e.extras,p=w=>{let h=null,R=w?.get;if(typeof R=="function")for(let C of t){let z=R.call(w,C);if(z&&typeof z=="object"){h=z;break}}let E=Ue(w,o),$=Ue(w,i),D=u?u(w,h):void 0;return h?{userId:Be(h,n),userEmail:Be(h,r),...E!==void 0?{reason:E}:{},...$!==void 0?{comment:$}:{},...D?{extras:D}:{}}:E===void 0&&$===void 0&&!D?null:{...E!==void 0?{reason:E}:{},...$!==void 0?{comment:$}:{},...D?{extras:D}:{}}};return Object.defineProperty(p,Ke,{value:{reasonHeader:c,commentHeader:d},enumerable:false,configurable:false}),p}function We(e){if(!e)return {reasonHeader:re,commentHeader:oe};if(typeof e=="function"){let t=e[Ke];return t?{...t}:{reasonHeader:re,commentHeader:oe}}return {reasonHeader:e.reasonHeader===void 0?re:e.reasonHeader,commentHeader:e.commentHeader===void 0?oe:e.commentHeader}}Le();function Gt(e){if(e)return typeof e=="function"?e:Le(e)}function Ge(e){let t=Gt(e);return async(n,r)=>{await Lt.run({c:n,resolver:t},async()=>{await r();});}}var Ve="_historyMeta";function fe(e){if(!e?.enabled||e.shadow===false||e.meta&&e.shadow===void 0)return null;let t=e.shadow,n=typeof t=="string"&&t.trim().length>0?t.trim():typeof t=="object"&&t!==null&&typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():Ve,r=typeof t=="object"&&t!==null?t.fields:void 0;return {key:n,fields:{userId:r?.userId??"userId",userEmail:r?.userEmail??"userEmail",reason:r?.reason??"reason",comment:r?.comment??"comment",extras:r?.extras??"extras"}}}var Qe="preserve";function ve(){return Qe}function Vt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Ye(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(Vt(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Xe(e){return e}var Ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Oe(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=Ee.length*4||(e+=Ee.charAt(r%Ee.length));}}return e}function et(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function tt(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(h=>h.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let h=r[0];return {rawPath:e,collectionId:h,collectionPath:h,parentKeys:[],documentPathTemplate:n?null:`${h}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,i=o?r.slice(0,-1):r,c=i[i.length-1],d=i.join("/"),p=i.slice(0,-1).map(et).filter(h=>h!==null),w=o?r.join("/"):`${d}/{${t}}`;return {rawPath:e,collectionId:c,collectionPath:d,parentKeys:p,documentPathTemplate:w,hasTemplate:true}}function nt(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:i,isGroup:c}=t,d=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(d&&i){let u=d.split("/").filter(Boolean),p=i.split("/").filter(Boolean);if(u.length===p.length){let w=[];for(let h=0;h<p.length;h++)et(p[h])!==null&&w.push(u[h]);if(w.length>0)return w}}if(o&&o.length>0){let u=o.length+1;if(d){let w=d.split("/").filter(Boolean),h=[];for(let R=1;R<w.length;R+=2)h.push(w[R]);if(h.length>=u)return h.slice(h.length-u)}let p=r?e[r]:void 0;if(typeof p=="string"&&p.trim()!==""){let w=[],h=true;for(let R of o){let E=e[R];if(typeof E=="string"&&E.trim()!=="")w.push(E);else {h=false;break}}if(h)return [...w,p]}}if(d){let u=d.split("/").filter(Boolean),p=[];for(let w=1;w<u.length;w+=2)p.push(u[w]);if(p.length>0)return !c&&(!o||o.length===0)?[p[p.length-1]]:p}}function rt(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var Yt=new Set(["<","<=",">",">=","!="]),Xt=new Set(["array-contains","array-contains-any"]);function Ie(e){return e==="desc"?"DESCENDING":"ASCENDING"}function en(e){return tt(e).collectionId||e}function tn(e,t,n,r,o){let i=[],c=new Set;for(let u of r)if(u.op==="=="||u.op==="in"||u.op==="not-in"){if(c.has(u.field))continue;c.add(u.field),i.push({fieldPath:u.field,order:"ASCENDING"});}for(let u of r)if(Xt.has(u.op)){if(c.has(u.field))continue;c.add(u.field),i.push({fieldPath:u.field,arrayConfig:"CONTAINS"});}for(let u of r)if(Yt.has(u.op)){if(c.has(u.field))continue;c.add(u.field);let p=o?.field===u.field?Ie(o.dir):"ASCENDING";i.push({fieldPath:u.field,order:p});}if(o&&!c.has(o.field)&&i.push({fieldPath:o.field,order:Ie(o.dir)}),i.length===1&&n)return on(e,t,i[0]);let d=o&&i.some(u=>u.fieldPath===o.field)?Ie(o.dir):"ASCENDING";return i.push({fieldPath:"__name__",order:d}),nn(e,t,n,i)}function nn(e,t,n,r,o="(default)"){let i=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,c=[...De(1,i),...ye(2,n?2:1)];for(let p of r)c.push(...ot(3,st(p)));let d=o==="(default)"?"-default-":o,u=encodeURIComponent(it(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${d}/indexes?create_composite=${u}`}function rn(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Pe(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function He(e,t){return e<<3|t}function De(e,t){let n=Array.from(new TextEncoder().encode(t));return [He(e,2),...Pe(n.length),...n]}function ye(e,t){return [He(e,0),...Pe(t)]}function ot(e,t){return [He(e,2),...Pe(t.length),...t]}function st(e){let t=[...De(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ye(3,1)):t.push(...ye(2,e.order==="DESCENDING"?2:1)),t}function it(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function on(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,i=[...De(1,o),...ye(2,2),...ot(3,st(n))],c=r==="(default)"?"-default-":r,d=encodeURIComponent(it(i));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes/automatic?create_exemption=${d}`}function sn(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function an(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function at(e,t){let n=e??{},r=an(e),o;if(r&&(o=n.message?rn(n.message):void 0,!o)){let i=sn(t.ref);if(i){let c=en(t.path);o=tn(i,c,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}function he(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!he(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof firestore.Timestamp||t instanceof firestore.Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return false;for(let i of r)if(!Object.prototype.hasOwnProperty.call(t,i)||!he(e[i],t[i],n))return false;return true}return false}function G(e,t){let n=e||{},r={},o={...n};for(let[i,c]of Object.entries(t||{})){let d=n[i];he(d,c)||(r[i]=c,o[i]=c);}return {before:n,after:o,changes:r}}function cn(e){return e}async function ct(e,t,n){let r=e.changes||{};for(let o of Object.keys(r)){let i=t[o];if(i&&i.length>0){for(let c of i)if(await c.rule({diff:e,key:o,user:n,authenticatedUser:n})===false)return {allowed:false,reason:c.description}}}return {allowed:true}}function dn(e){return async t=>ct(t.diff,e,t.user)}var je=1e3;function dt(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),je)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>je?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${je}`}:{success:true,value:n}}function Fe(e,t,n=200){let r=Xe(t);return e.json(r,n)}function Y(e,t,n,r=200){return Fe(e,{success:true,data:t,meta:n},r)}function T(e,t,n=400){return Fe(e,{success:false,error:t},n)}async function _e(e,t,n,r,o,i){let c=at(t,n),d=c.type==="index",u=d?424:500,w={success:false,error:d?c.message:o&&t instanceof Error?t.message:r};if(d&&(w.errorType="index",c.indexUrl&&(w.indexUrl=c.indexUrl,i)))try{let h=i({indexUrl:c.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});h instanceof Promise&&await h;}catch(h){o&&console.error("[crudServer] Error in indexesError callback:",h);}return Fe(e,w,u)}function X(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>Ye(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[i,c]of Object.entries(r))o[i]=X(c);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(X(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return X(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return X(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let i=X(r);return typeof o=="function"?i.default(o()):i.default(o)}}return e}function un(e,t,n=[]){let r=e.shape,o={},i=t&&t.length>0?t:Object.keys(r);for(let c of i){if(n.includes(c))continue;let d=c.split(".")[0];d&&r[d]&&(o[d]=r[d]);}return zod.z.object(o)}function ze(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function pt(e,t){let n=t.split("."),r=ze(e);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let c=r?.shape;if(!c||!c[i])return;let d=c[i];if(o===n.length-1)return d;r=ze(d);}return r}function ee(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[i,c]of Object.entries(r))o[i]=ee(c);return zod.z.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=ee(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=ee(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?ee(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(c=>ee(c));return o.some((c,d)=>c!==r[d])?zod.z.union(o):e}return e}function ge(e,t,n,r=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let i=t,c={},d={};for(let[u,p]of Object.entries(i))if(u.includes(".")){let w=u.split(".")[0];if(o.includes(u)||o.includes(w))continue;if(n&&n.length>0&&!n.includes(u)&&!n.includes(w))return {success:!1,error:`Field '${u}' is not allowed for this operation`};let h=pt(e,u);if(!h)return {success:!1,error:`Field '${u}' does not exist in schema`};let R=r?ee(h):h,$=(ve()==="normalize"?X(R):R).parse(p);c[u]=$;}else d[u]=p;if(Object.keys(d).length>0||Object.keys(c).length===0){let u=un(e,n,o),p=r?ee(u):u,h=(ve()==="normalize"?X(p):p).parse(d);Object.assign(c,h);}return {success:!0,data:c}}catch(i){return i instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${i.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var ft={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function ce(e){return ft[e]??e}function ln(e){return e in ft}function we(e,t,n,r){let o=pt(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let i=r?ce(r):void 0,c=ze(o),d=rt(c);if(i==="array-contains"){let w=d??o;if(typeof w.safeParse=="function"){let h=w.safeParse(n);return h.success?{success:true,data:h.data}:{success:false,error:h.error.issues.map(E=>E.message).join(", ")}}return {success:true,data:n}}if(i==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let w=d??o,h=[];for(let R of n)if(typeof w.safeParse=="function"){let E=w.safeParse(R);if(E.success)h.push(E.data);else return {success:false,error:E.error.issues.map(D=>D.message).join(", ")}}else h.push(R);return {success:true,data:h}}let u=o.safeParse(n);if(u.success)return {success:true,data:u.data};if(Array.isArray(n)){let w=d??o,h=[];for(let R of n)if(typeof w.safeParse=="function"){let E=w.safeParse(R);if(E.success)h.push(E.data);else return {success:false,error:E.error.issues.map(D=>D.message).join(", ")}}else h.push(R);return {success:true,data:h}}return {success:false,error:u.error.issues.map(w=>w.message).join(", ")}}function pn(e,t){let n=[],r=t?new Set(t):null;for(let[o,i]of Object.entries(e)){if(i===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let c=Array.isArray(i)?i[0]:i;if(c===void 0||c==="")continue;let d=o.lastIndexOf("__"),u,p="==";if(d!==-1){let h=o.slice(0,d),R=o.slice(d+2);ln(R)?(u=h,p=ce(R)):(u=o,p="==");}else u=o;if(r&&!r.has(u))continue;let w=c;p==="in"||p==="not-in"||p==="array-contains-any"?w=c.split(",").map(h=>ut(h.trim())):w=ut(c),n.push({field:u,op:p,value:w});}return n}function ut(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function be(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function lt(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let i=e.repo.ref,c=i?.firestore;if(r&&c&&typeof c.doc=="function"){let d=await c.doc(r).get();if(d.exists)return d}if(o&&o.includes("/")&&c&&typeof c.doc=="function"){let d=await c.doc(o).get();if(d.exists)return d}if(o&&typeof i.doc=="function"){let d=await i.doc(o).get();if(d.exists)return d}return}catch{return}}function xe(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t={},n=0;for(let[r,o]of Object.entries(e))o!==void 0&&(t[r]=o,n++);return n>0?t:null}function yt(e,t,n,r,o){async function i(x,a,l,s){let g=false;if(x.hooks?.onAfterError){g=true;try{let y=x.hooks.onAfterError(s,l.hook);y instanceof Promise&&await y;}catch(y){console.error("[crudServer] Error in hooks.onAfterError callback:",y);}}if(o){g=true;try{let y=o({...l,error:s});y instanceof Promise&&await y;}catch(y){console.error("[crudServer] Error in onHookError callback:",y);}}if(!g){if(a&&typeof a.error=="function"){a.error(s,{hook:l.hook,repoName:l.repoName,path:l.path,...l.id!==void 0?{id:l.id}:{},...l.pathArgs!==void 0?{pathArgs:l.pathArgs}:{}});return}console.error(`[crudServer] Hook "${l.hook}" failed on repo "${l.repoName}":`,{hook:l.hook,repoName:l.repoName,path:l.path,...l.id!==void 0?{id:l.id}:{},...l.pathArgs!==void 0?{pathArgs:l.pathArgs}:{},error:s});}}async function c(x,a,l,s){if(!a.rules)return {allowed:true};let g=a.rules?.[l];if(!g)return {allowed:false,errorResponse:T(x,`Operation "${l}" is not allowed for this repository`,403)};try{let y=await g(s);return y===!1?{allowed:!1,errorResponse:T(x,"Forbidden",403)}:typeof y=="string"?{allowed:!1,errorResponse:T(x,y,403)}:typeof y=="object"&&y!==null&&!y.allowed?{allowed:!1,errorResponse:T(x,y.reason||"Forbidden",403)}:{allowed:!0}}catch(y){let v=n&&y instanceof Error?y.message:"Forbidden";return {allowed:false,errorResponse:T(x,v,403)}}}async function d(x,a,l,s){if(!x.rules)return s;let g=x.rules?.filter;if(!g)return s;let y=[];for(let v of s)try{await g({user:a,doc:v,params:l})&&y.push(v);}catch{}return y}function u(x){return x.get("user")??x.get("docsUser")??null}function p(x,a){if(!x){let l=a.req.path.split("/");for(let s of l)if(e[s]){x=s;break}}return !x||!e[x]?null:e[x]??null}function w(x,a){return nt(x,{pathKey:a.pathKey,documentKey:a.documentKey,parentKeys:a.parentKeys,documentPathTemplate:a.documentPathTemplate,isGroup:a.isGroup})}async function h(x,a){let l=`by${x.documentKey.charAt(0).toUpperCase()}${x.documentKey.slice(1)}`,s=x.repo.get[l];if(typeof s=="function")try{let y=await s(a);if(y)return y}catch{}return (await x.repo.query.by({where:[[x.documentKey,"==",a]],limit:1}))[0]??null}async function R(x){let a=x.c,l=a.req.param(),s=p(l.repoName,a);if(!s)return T(a,"Repository not found",404);let g=u(a),y=await c(a,s,"list",{user:g,query:a.req.query(),params:l});if(!y.allowed)return y.errorResponse;let v=[],k;try{let m=a.req.query(),j=dt(m.pageSize,s.pageSize);if(!j.success)return T(a,j.error,400);let q=j.value,_=m.cursor,M=m.direction?.toLowerCase()==="prev"?"prev":"next",f=m.orderBy,b=m.orderDir?.toLowerCase()==="desc"?"desc":"asc",O=m.select,P=O?O.split(",").map(K=>K.trim()):void 0,A=m.withTotal,S=A==="true"||A==="1"||A===!0,I;s.allowedIncludes&&m.includes&&(I=(typeof m.includes=="string"?m.includes.split(",").map(J=>J.trim()):Array.isArray(m.includes)?m.includes:[]).filter(J=>typeof J=="string"&&s.allowedIncludes.includes(J)),I?.length===0&&(I=void 0));let H=pn(m,s.filterableFields);v=H.map(K=>({field:K.field,op:K.op,value:String(K.value??"")})),f&&(k={field:f,dir:b});let Z={pageSize:q,direction:M,...S?{withTotal:!0}:{}};if(_)try{let K=typeof _=="string"?JSON.parse(_):_;Z.cursor=await lt(s,K);}catch{}if(f){if(s.orderableFields&&!s.orderableFields.includes(f))return T(a,`Field not orderable: ${f}`,400);Z.orderBy=[{field:f,direction:b}];}if(H.length>0){Z.where=[];for(let K of H){let J=we(s.schema,K.field,K.value,K.op);if(!J.success)return T(a,`Invalid filter value for '${K.field}': ${J.error}`,400);Z.where.push([K.field,K.op,J.data]);}}P&&(Z.select=P),I&&(Z.include=I);let B=await s.repo.query.paginate(Z),Ft={items:await d(s,u(a),l,B.data),hasNextPage:B.hasNextPage,hasPrevPage:B.hasPrevPage,nextCursor:be(B.nextCursor),prevCursor:be(B.prevCursor),...B.totalCount!==void 0?{totalCount:B.totalCount,totalCountIsExact:B.totalCountIsExact}:{}};return Y(a,Ft,{pageSize:q,hasMore:B.hasNextPage,...B.totalCount!==void 0?{totalCount:B.totalCount,totalCountIsExact:B.totalCountIsExact}:{}})}catch(m){return await _e(a,m,{repoName:l.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:v,sort:k},"Failed to fetch documents",n,r)}}async function E(x){let a=x.c,l=a.req.param(),s=p(l.repoName,a);if(!s)return T(a,"Repository not found",404);let g=u(a),y=await c(a,s,"list",{user:g,query:x.input||{},params:l});if(!y.allowed)return y.errorResponse;let v=[],k;try{let m=x.input||{},j=dt(m.pageSize,s.pageSize);if(!j.success)return T(a,j.error,400);let q=j.value,_=m.direction==="prev"?"prev":"next";m.where&&(v=m.where.map(A=>({field:String(A[0]),op:A[1],value:String(A[2]??"")}))),m.orderBy&&m.orderBy[0]&&(k={field:m.orderBy[0].field,dir:m.orderBy[0].direction==="desc"?"desc":"asc"});let M=m.withTotal===!0||String(m.withTotal)==="true",f={pageSize:q,direction:_,...M?{withTotal:!0}:{}};if(m.cursor)try{let A=typeof m.cursor=="string"?JSON.parse(m.cursor):m.cursor;f.cursor=await lt(s,A);}catch{}if(s.allowedIncludes&&m.includes&&m.includes.length>0){let A=m.includes.filter(S=>typeof S=="string"?s.allowedIncludes.includes(S):typeof S=="object"&&S!==null&&"relation"in S&&typeof S.relation=="string"?s.allowedIncludes.includes(S.relation):!1);A.length>0&&(f.include=A);}if(m.where&&m.where.length>0){if(s.filterableFields){let S=new Set(s.filterableFields),I=m.where.filter(H=>!S.has(H[0]));if(I.length>0){T(a,`Fields not filterable: ${I.map(H=>H[0]).join(", ")}`,400);return}}let A=[];for(let S of m.where){let I=ce(S[1]),H=we(s.schema,S[0],S[2],I);if(!H.success){T(a,`Invalid filter value for '${S[0]}': ${H.error}`,400);return}A.push([S[0],I,H.data]);}f.where=A;}if(m.orWhere&&m.orWhere.length>0){if(s.filterableFields){let S=new Set(s.filterableFields),I=m.orWhere.filter(H=>!S.has(H[0]));if(I.length>0){T(a,`Fields not filterable: ${I.map(H=>H[0]).join(", ")}`,400);return}}let A=[];for(let S of m.orWhere){let I=ce(S[1]),H=we(s.schema,S[0],S[2],I);if(!H.success){T(a,`Invalid filter value for '${S[0]}': ${H.error}`,400);return}A.push([S[0],I,H.data]);}f.orWhere=A;}if(m.orWhereGroups&&m.orWhereGroups.length>0){if(s.filterableFields){let S=new Set(s.filterableFields);for(let I of m.orWhereGroups){let H=I.filter(Z=>!S.has(Z[0]));if(H.length>0){T(a,`Fields not filterable: ${H.map(Z=>Z[0]).join(", ")}`,400);return}}}let A=[];for(let S of m.orWhereGroups){let I=[];for(let H of S){let Z=ce(H[1]),B=we(s.schema,H[0],H[2],Z);if(!B.success){T(a,`Invalid filter value for '${H[0]}': ${B.error}`,400);return}I.push([H[0],Z,B.data]);}A.push(I);}f.orWhereGroups=A;}if(m.orderBy&&m.orderBy.length>0){if(s.orderableFields){let A=new Set(s.orderableFields),S=m.orderBy.filter(I=>!A.has(I.field));if(S.length>0){T(a,`Fields not orderable: ${S.map(I=>I.field).join(", ")}`,400);return}}f.orderBy=m.orderBy;}m.select&&m.select.length>0&&(f.select=m.select);let b=await s.repo.query.paginate(f),P={items:await d(s,u(a),l,b.data),hasNextPage:b.hasNextPage,hasPrevPage:b.hasPrevPage,nextCursor:be(b.nextCursor),prevCursor:be(b.prevCursor),...b.totalCount!==void 0?{totalCount:b.totalCount,totalCountIsExact:b.totalCountIsExact}:{}};return Y(a,P,{pageSize:q,hasMore:b.hasNextPage,...b.totalCount!==void 0?{totalCount:b.totalCount,totalCountIsExact:b.totalCountIsExact}:{}})}catch(m){return await _e(a,m,{repoName:l.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:v,sort:k},"Failed to query documents",n,r)}}async function $(x){let a=x.c,l=a.req.param(),s=p(l.repoName,a);if(!s)return T(a,"Repository not found",404);let g=l.id;if(!g)return T(a,"Document ID required",400);try{let y=await h(s,g);if(!y)return T(a,"Document not found",404);let v=u(a),k=await c(a,s,"get",{user:v,doc:y,params:l});if(!k.allowed)return k.errorResponse;if(s.rules?.filter)try{if(!await s.rules.filter({user:v,doc:y,params:l}))return T(a,"Document not found",404)}catch{return T(a,"Document not found",404)}return Y(a,y)}catch(y){return await _e(a,y,{repoName:l.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:[{field:s.documentKey,op:"==",value:g}]},"Failed to fetch document",n,r)}}async function D(x){let a=x.c,l=a.req.param(),s=p(l.repoName,a);if(!s)return T(a,"Repository not found",404);try{let g=x.input||{},y=u(a),v=await c(a,s,"create",{user:y,body:g,params:l});if(!v.allowed)return v.errorResponse;let k=ge(s.schema,g,s.createFields,!1,s.systemKeys);if(!k.success)return T(a,k.error,400);if(s.validate){let _=await s.validate(k.data,"create");if(_)return T(a,_,400)}s.hooks?.beforeCreate&&await s.hooks.beforeCreate({user:y,body:k.data,params:l,c:a});let m,j;if(s.isGroup&&s.parentKeys&&s.parentKeys.length>0){let _={...k.data},M=s.parentKeys.filter(f=>_[f]===void 0||_[f]===null||typeof _[f]=="string"&&_[f].trim()==="");if(M.length>0)return T(a,`Missing parent key(s) for subcollection create: ${M.join(", ")}`,400);if(typeof s.repo.create=="function")m=await s.repo.create(_);else {let f=s.parentKeys.map(O=>String(_[O])),b=_[s.documentKey]||Oe();j=[...f,b],m=await s.repo.set(...f,b,_);}}else m=await s.repo.create(k.data);let q=m;if(s.hooks?.afterCreate){let _=m?.[s.documentKey]??j?.[j.length-1]??"",M=String(_),f=j??w(m,s)??w({...k.data,...M?{[s.documentKey]:M}:{}},s)??(M?[M]:[]);try{let b=await s.hooks.afterCreate({user:y,doc:m,id:M,pathArgs:f,params:l,c:a}),O=xe(b);O&&f.length>0&&(q=await s.repo.update(...f,O));}catch(b){await i(s,x.logger,{hook:"afterCreate",repoName:s.name,path:s.path,id:M,pathArgs:f,user:y,c:a},b);}}return Y(a,q,void 0,201)}catch(g){let y=n&&g instanceof Error?g.message:"Failed to create document";return T(a,y,500)}}async function C(x,a){let l=x.c,s=l.req.param(),g=p(s.repoName,l);if(!g)return T(l,"Repository not found",404);let y=s.id;if(!y)return T(l,"Document ID required",400);try{let v=x.input||{},k=await h(g,y);if(!k)return T(l,"Document not found",404);let m=ge(g.schema,v,g.mutableFields,a,g.systemKeys);if(!m.success)return T(l,m.error,400);if(g.validate){let A=await g.validate(m.data,"update");if(A)return T(l,A,400)}let j=G(k,m.data),q=u(l),_=await c(l,g,"update",{user:q,doc:k,body:m.data,diff:j,params:s});if(!_.allowed)return _.errorResponse;if(g.hooks?.beforeUpdate){let A=g.rules?.update?G(k,m.data):j;await g.hooks.beforeUpdate({user:q,doc:k,body:m.data,diff:A,params:s,c:l});}let M={...m.data},f=g.hooks?.afterUpdate?G(k,M):j,b=w(k,g)??[y],O=await g.repo.update(...b,m.data),P=O;if(g.hooks?.afterUpdate)try{let A=await g.hooks.afterUpdate({user:q,before:k,after:O,body:M,diff:f,id:y,pathArgs:b,params:s,c:l}),S=xe(A);S&&(P=await g.repo.update(...b,S));}catch(A){await i(g,x.logger,{hook:"afterUpdate",repoName:g.name,path:g.path,id:y,pathArgs:b,user:q,c:l},A);}return Y(l,P)}catch(v){let k=n&&v instanceof Error?v.message:"Failed to update document";return T(l,k,500)}}async function z(x){let a=x.c,l=a.req.param(),s=p(l.repoName,a);if(!s)return T(a,"Repository not found",404);if(!s.allowDelete)return T(a,"Delete not allowed for this repository",403);let g=l.id;if(!g)return T(a,"Document ID required",400);try{let y=await h(s,g);if(!y)return T(a,"Document not found",404);let v=u(a),k=await c(a,s,"delete",{user:v,doc:y,params:l});if(!k.allowed)return k.errorResponse;let m=w(y,s)??[g];if(await s.repo.delete(...m),s.hooks?.afterDelete)try{await s.hooks.afterDelete({user:v,doc:y,id:g,pathArgs:m,params:l,c:a});}catch(j){await i(s,x.logger,{hook:"afterDelete",repoName:s.name,path:s.path,id:g,pathArgs:m,user:v,c:a},j);}return Y(a,{deleted:!0})}catch(y){let v=n&&y instanceof Error?y.message:"Failed to delete document";return T(a,v,500)}}function N(x){return x.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400"})}async function W(x){let a=x.c,l=a.req.param(),s=p(l.repoName,a);if(!s)return T(a,"Repository not found",404);try{let g=x.input||{};if(!Array.isArray(g.operations))return T(a,"operations array is required",400);let y=u(a),v=s.repo.batch.create(),k=[],m=!!s.hooks,j=[],q=[],_=[];for(let f of g.operations){if(!f.type||!["create","update","delete"].includes(f.type))return T(a,"Invalid operation type",400);if(f.type==="create"){let b=await c(a,s,"create",{user:y,body:f.data,params:l});if(!b.allowed)return b.errorResponse;let O=ge(s.schema,f.data,s.createFields,!1,s.systemKeys);if(!O.success)return T(a,O.error,400);s.hooks?.beforeCreate&&await s.hooks.beforeCreate({user:y,body:O.data,params:l,c:a});let P=f.data[s.documentKey]||O.data[s.documentKey]||Oe(),A={...O.data};s.createdKey&&A[s.createdKey]===void 0&&(A[s.createdKey]=new Date);let S;if(s.isGroup&&s.parentKeys){let I=s.parentKeys.map(H=>String(A[H]));S=[...I,P],v.set(...I,P,A);}else S=[P],v.set(P,A);if(k.push({op:"create",id:P}),m){let I={...A,[s.documentKey]:P};if(s.pathKey&&typeof s.repo.documentRef=="function")try{let H=s.repo.documentRef(...S);H?.path&&(I[s.pathKey]=H.path);}catch{}j.push({id:P,pathArgs:S,doc:I});}}else if(f.type==="update"){if(!f.id)return T(a,"id required for update",400);let b=await h(s,f.id);if(!b)return T(a,`Document ${f.id} not found`,404);let O=ge(s.schema,f.data,s.mutableFields,!0,s.systemKeys);if(!O.success)return T(a,O.error,400);if(s.validate){let Z=await s.validate(O.data,"update");if(Z)return T(a,Z,400)}let P=G(b,O.data),A=await c(a,s,"update",{user:y,doc:b,body:O.data,diff:P,params:l});if(!A.allowed)return A.errorResponse;if(s.hooks?.beforeUpdate){let Z=s.rules?.update?G(b,O.data):P;await s.hooks.beforeUpdate({user:y,doc:b,body:O.data,diff:Z,params:l,c:a});}let S={...O.data},I=m?G(b,S):P,H=w(b,s)??[f.id];v.update(...H,O.data),k.push({op:"update",id:f.id}),m&&q.push({id:f.id,pathArgs:H,before:b,after:I.after,body:S,diff:I});}else if(f.type==="delete"){if(!s.allowDelete)return T(a,"Delete not allowed",403);if(!f.id)return T(a,"id required for delete",400);let b=await h(s,f.id);if(!b)return T(a,`Document ${f.id} not found`,404);let O=await c(a,s,"delete",{user:y,doc:b,params:l});if(!O.allowed)return O.errorResponse;let P=w(b,s)??[f.id];v.delete(...P),k.push({op:"delete",id:f.id}),m&&_.push({id:f.id,pathArgs:P,doc:b});}}await v.commit();let M=j.length>0||q.length>0||_.length>0;if(s.hooks&&M)if(s.hooks.afterBatch)try{await s.hooks.afterBatch({user:y,created:j,updated:q,deleted:_,params:l,c:a});}catch(f){await i(s,x.logger,{hook:"afterBatch",repoName:s.name,path:s.path,user:y,c:a},f);}else {if(s.hooks.afterCreate)for(let f of j)try{let b=await s.hooks.afterCreate({user:y,doc:f.doc,id:f.id,pathArgs:f.pathArgs,params:l,c:a}),O=xe(b);O&&f.pathArgs.length>0&&await s.repo.update(...f.pathArgs,O);}catch(b){await i(s,x.logger,{hook:"afterCreate",repoName:s.name,path:s.path,id:f.id,pathArgs:f.pathArgs,user:y,c:a},b);}if(s.hooks.afterUpdate)for(let f of q)try{let b=await s.hooks.afterUpdate({user:y,before:f.before,after:f.after,body:f.body,diff:f.diff,id:f.id,pathArgs:f.pathArgs,params:l,c:a}),O=xe(b);O&&f.pathArgs.length>0&&await s.repo.update(...f.pathArgs,O);}catch(b){await i(s,x.logger,{hook:"afterUpdate",repoName:s.name,path:s.path,id:f.id,pathArgs:f.pathArgs,user:y,c:a},b);}if(s.hooks.afterDelete)for(let f of _)try{await s.hooks.afterDelete({user:y,doc:f.doc,id:f.id,pathArgs:f.pathArgs,params:l,c:a});}catch(b){await i(s,x.logger,{hook:"afterDelete",repoName:s.name,path:s.path,id:f.id,pathArgs:f.pathArgs,user:y,c:a},b);}}return Y(a,{results:k})}catch(g){let y=n&&g instanceof Error?g.message:"Batch operation failed";return T(a,y,500)}}return {handleList:R,handleQuery:E,handleGet:$,handleCreate:D,handleUpdate:C,handleDelete:z,handleBatch:W,handleOptions:N}}function ie(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function U(e){return {$ref:`#/components/schemas/${e}`}}function F(e){return {description:e,content:{"application/json":{schema:U("ErrorResponse")}}}}function se(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function fn(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated due to OR conditions (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function ue(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function yn(e,t){let n=t.split("."),r=ue(e);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let c=r?.shape;if(!c||!c[i])return;let d=c[i];if(o===n.length-1)return d;r=ue(d);}return r}function ne(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=o=>{let i=zodToOpenapi.getOpenApiMetadata(e);return i&&typeof o.openapi=="function"?o.openapi(i):o};if(n==="ZodObject"||n==="object"){let o=e.shape,i={};for(let[c,d]of Object.entries(o))i[c]=ne(d);return r(zod.z.object(i).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let i=ne(o);return i===o?e:r(i.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let i=ne(o);return i===o?e:r(i.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(ne(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let i=o.map(d=>ne(d));return i.some((d,u)=>d!==o[u])?r(zod.z.union(i)):e}return e}function Ne(e,t="",n=0){if(n>5)return [];let o=ue(e)?.shape;if(!o)return [];let i=[];for(let[c,d]of Object.entries(o)){let u=t?`${t}.${c}`:c,p=ue(d);p?.shape&&typeof p.shape=="object"?(i.push({path:u,zodSchema:d}),i.push(...Ne(p,u,n+1))):i.push({path:u,zodSchema:d});}return i}function mn(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:yn(e.schema,t)})):Ne(e.schema)}function mt(e){if(!e)return {type:"string"};let t=ie(e);return delete t.$schema,delete t.title,t}function gt(){return {type:"object",properties:{where:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3}},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string"},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string"},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function hn(e){let t=mn(e),n=e.orderableFields??t.map(c=>c.path),r=t.map(c=>c.path);if(t.length===0)return gt();let o=[];for(let{path:c,zodSchema:d}of t){let u=mt(d),p=ue(d),h=p?._zod?.def?.type==="array"||p?._def?.typeName==="ZodArray"||p?._def?.type==="array"?mt(p?._zod?.def?.element??p?._def?.type??p?._def?.element):u;o.push({type:"array",description:`Condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},u],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${c}' (in, not-in)`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:u}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains","contains"]},h],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:h}],minItems:3,maxItems:3});}let i={oneOf:o};return {type:"object",properties:{where:{type:"array",items:i,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:i,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:i},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:r},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function gn(e){if(e.historyHeaders)return e.historyHeaders;let t=e.repo?._historyConfig;if(!t?.enabled||t.autoInjectMeta===false)return null;let n=fe(t);return n?{reason:n.fields.reason!==false,comment:n.fields.comment!==false}:null}function wn(e,t){if(t===false)return [];let n=gn(e);if(!n)return [];let r=t?.reasonHeader===void 0?re:t.reasonHeader,o=t?.commentHeader===void 0?oe:t.commentHeader,i=[],c=new Set;if(n.reason&&typeof r=="string"&&r.trim()){let d=r.trim();c.add(d.toLowerCase()),i.push({name:d,in:"header",required:false,schema:{type:"string"},description:"Optional reason recorded in the document's change history"});}if(n.comment&&typeof o=="string"&&o.trim()){let d=o.trim();c.has(d.toLowerCase())||(c.add(d.toLowerCase()),i.push({name:d,in:"header",required:false,schema:{type:"string"},description:"Optional comment recorded in the document's change history"}));}if(t?.extraHeaders?.length)for(let d of t.extraHeaders){let u=typeof d=="string"?{name:d}:d,p=u?.name?.trim();!p||c.has(p.toLowerCase())||(c.add(p.toLowerCase()),i.push({name:p,in:"header",required:u.required??false,schema:u.schema??{type:"string"},...u.description?{description:u.description}:{}}));}return i}function bn(e,t,n,r,o,i=null,c="QueryRequestBody",d=[]){let u={},p=e.name,w=`${t}/${e.name}`,h=`${w}/{${e.documentKey}}`,R={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};u[w]={post:{operationId:`create${Q(e.name)}`,summary:`Create a ${V(e.name)}`,tags:[p],...d.length>0?{parameters:[...d]}:{},requestBody:{required:true,content:{"application/json":{schema:U(r??n)}}},responses:{201:se("Document created",U(n)),400:F("Validation error"),403:F("Forbidden"),500:F("Internal server error")}}},u[`${w}/query`]={post:{operationId:`query${Q(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[p],requestBody:{required:true,content:{"application/json":{schema:U(c)}}},responses:{200:fn(U(n)),400:F("Invalid query"),403:F("Forbidden"),424:F("Missing composite index (includes indexUrl in response)"),500:F("Internal server error")}}},u[`${w}/batch`]={post:{operationId:`batch${Q(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[p],...d.length>0?{parameters:[...d]}:{},requestBody:{required:true,content:{"application/json":{schema:U(`${n}BatchRequest`)}}},responses:{200:se("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}}};let E={};return E.get={operationId:`get${Q(V(e.name))}`,summary:`Get a single ${V(e.name)}`,tags:[p],parameters:[R],responses:{200:se("Document found",U(n)),400:F("Document ID required"),403:F("Forbidden"),404:F("Document not found"),424:F("Missing composite index (includes indexUrl in response)"),500:F("Internal server error")}},E.put={operationId:`update${Q(V(e.name))}`,summary:`Update a ${V(e.name)} (full replace)`,tags:[p],parameters:[R,...d],requestBody:{required:true,content:{"application/json":{schema:U(o??n)}}},responses:{200:se("Document updated",U(n)),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}},E.patch={operationId:`patch${Q(V(e.name))}`,summary:`Partially update a ${V(e.name)}`,tags:[p],parameters:[R,...d],requestBody:{required:true,content:{"application/json":{schema:U(i??o??n)}}},responses:{200:se("Document patched",U(n)),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}},e.allowDelete&&(E.delete={operationId:`delete${Q(V(e.name))}`,summary:`Delete a ${V(e.name)}`,tags:[p],parameters:[R],responses:{200:se("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:F("Document ID required"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}}),u[h]=E,u}function qe(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:i,servers:c,auth:d=false}=n,u=t==="/"?"":t.replace(/\/$/,""),p={},w={},h=[];p.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},p.QueryRequestBody=gt();for(let[D,C]of Object.entries(e)){let z=Q(V(D)),N=`${z}Create`,W=`${z}Update`,x=`${z}Patch`,a=`${z}QueryRequestBody`;p[z]=ie(C.schema),p[a]=hn(C);let l=f=>{let b={},O=Ne(C.schema);for(let{path:P,zodSchema:A}of O){let S=P.split(".")[0];C.systemKeys.includes(S)||C.systemKeys.includes(P)||f&&f.length>0&&!f.includes(P)&&!f.includes(S)||(P.includes(".")?b[P]=A.optional():b[P]=A);}return b},s=null,g=l(C.createFields);if(C.isGroup&&C.parentKeys&&C.parentKeys.length>0){let f=C.schema?.shape??{};for(let b of C.parentKeys)!g[b]&&f[b]&&(g[b]=f[b]);}if(Object.keys(g).length>0){let f=ie(zod.z.object(g));if(C.isGroup&&C.parentKeys&&C.parentKeys.length>0){let b=new Set(Array.isArray(f.required)?f.required:[]);for(let O of C.parentKeys)f.properties?.[O]&&b.add(O);b.size>0&&(f.required=Array.from(b));}p[N]=f,s=N;}let y=null,v=null,k=l(C.mutableFields);if(Object.keys(k).length>0){let f=zod.z.object(k);p[W]=ie(f),y=W,p[x]=ie(ne(f)),v=x;}else p[x]=ie(ne(C.schema)),v=x;let m=`${z}BatchCreateOperation`,j=`${z}BatchUpdateOperation`,q=`${z}BatchDeleteOperation`;p[m]={type:"object",title:`${z} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:U(s??z)},required:["type","data"]},p[j]={type:"object",title:`${z} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:U(v??y??z)},required:["type","id","data"]},C.allowDelete&&(p[q]={type:"object",title:`${z} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),p[`${z}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[U(m),U(j),...C.allowDelete?[U(q)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let _=wn(C,n.historyHeaders),M=bn(C,u,z,s,y,v,a,_);Object.assign(w,M),h.push({name:D,description:`Operations on ${D} (collection: ${C.path})`});}let R={},E;return d==="basic"?(R.basicAuth={type:"http",scheme:"basic"},E=[{basicAuth:[]}]):d==="bearer"&&(R.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},E=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...i?{description:i}:{}},...c&&c.length>0?{servers:c}:{},paths:w,components:{schemas:p,...Object.keys(R).length>0?{securitySchemes:R}:{}},...E?{security:E}:{},tags:h}}function Q(e){return e.charAt(0).toUpperCase()+e.slice(1)}function V(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var ae=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var le=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},pe=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function wt(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function bt(e,t){return t instanceof ae?e.json({success:false,error:"Validation failed",issues:wt(t.zodError)},400):t instanceof le?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof pe?e.json({success:false,error:"Output validation failed",issues:wt(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var xt="Successful response",Rt="Error response";function L(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,r=n._zod?.def??n.def;if(!r)return;if(r.type==="custom"){let i=zodToOpenapi.getOpenApiMetadata(n);i?.type||zod.z.globalRegistry.add(n,{...i??{},type:"object"});return}if(r.innerType&&L(r.innerType,t),r.element&&L(r.element,t),r.valueType&&L(r.valueType,t),r.keyType&&L(r.keyType,t),r.left&&L(r.left,t),r.right&&L(r.right,t),r.in&&L(r.in,t),r.out&&L(r.out,t),typeof r.getter=="function")try{L(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let i of r.options)L(i,t);if(Array.isArray(r.items))for(let i of r.items)L(i,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let i of Object.values(o))L(i,t);}function Me(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)Me(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))Me(n);}function kn(e){return e==="get"?"query":"json"}function Cn(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Sn(e){if(typeof e.safeParse=="function")return {description:Rt,schema:e};let t=e;return {description:t.description??Rt,schema:t.schema}}function kt(e,t,n,r){let o=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[d,u]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",d,u);for(let d of e){let u=d.method,p=d.source??kn(u),w=On(t,d.path??"/"),h=d.status??200;d.input&&L(d.input);let R=vn(u,p,d.input),E=Tt(p,d.input,"query"),$=Tt(p,d.input,"param"),D=In(u,w),C=Cn(d.output,r);C&&L(C);let z={[h]:C?{description:xt,content:{"application/json":{schema:C}}}:{description:xt}};if(r?.errors)for(let[N,W]of Object.entries(r.errors)){let{description:x,schema:a}=Sn(W);a&&L(a),z[N]=a?{description:x,content:{"application/json":{schema:a}}}:{description:x};}o.registerPath({method:u,path:En(w),operationId:D,summary:d.summary,description:d.description,tags:d.tags,deprecated:d.deprecated,security:d.security,request:{...E?{query:E}:{},...$?{params:$}:{},...R?{body:R}:{}},responses:z});}let c=new zodToOpenapi.OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return Me(c),c}function vn(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function Tt(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function En(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function On(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function In(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Ct(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8" />
|
|
@@ -9,5 +9,5 @@
|
|
|
9
9
|
<script id="api-reference" data-url="${n}"></script>
|
|
10
10
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
11
11
|
</body>
|
|
12
|
-
</html>`}function pt(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var je=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),ze=globalThis,fn=ze[je]??(ze[je]=new async_hooks.AsyncLocalStorage);function yn(e,t){if(!t.includes("."))return e[t];let n=e;for(let r of t.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function ft(e,t){for(let n of t){let r=yn(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function yt(e,t){if(t===false)return;let n=e?.req?.header;if(typeof n!="function")return;let r=n.call(e.req,t);return typeof r=="string"&&r.length>0?r:void 0}function mt(e={}){let t=e.contextKeys??["user","docsUser"],n=e.userIdFields??["uid","id","sub"],r=e.userEmailFields??["email"],o=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,i=e.commentHeader===void 0?"x-history-comment":e.commentHeader,c=e.extras;return u=>{let d=null,p=u?.get;if(typeof p=="function")for(let O of t){let N=p.call(u,O);if(N&&typeof N=="object"){d=N;break}}let m=yt(u,o),y=yt(u,i),b=c?c(u,d):void 0;return d?{userId:ft(d,n),userEmail:ft(d,r),...m!==void 0?{reason:m}:{},...y!==void 0?{comment:y}:{},...b?{extras:b}:{}}:m===void 0&&y===void 0&&!b?null:{...m!==void 0?{reason:m}:{},...y!==void 0?{comment:y}:{},...b?{extras:b}:{}}}}mt();function mn(e){if(e)return typeof e=="function"?e:mt(e)}function gt(e){let t=mn(e);return async(n,r)=>{await fn.run({c:n,resolver:t},async()=>{await r();});}}var _e=new async_hooks.AsyncLocalStorage;function ht(){return async(e,t)=>{await _e.run({c:e},async()=>{await t();});}}var bn=Object.freeze({}),ge=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=Sn(t.routes,t.api),this.app.use("*",gt(t.actorResolver)),t.services&&this.app.use("*",ht());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return nodeServer.getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=dt(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Rn(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,r=this.options.verbose??false;for(let o of this.mountedRoutes){if(!o.path)throw new Error(`[HonoServer] route "${o.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let i=me(t,o.path),c=o.middlewares??[],u=o.source??(o.method==="get"?"query":"json"),d=vn(o,u,n,xn(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),p=o.method.toUpperCase();this.app.on(p,[i],...c,d),r&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${i}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,o=me(this.options.basePath??"",n),i=r===false?null:me(this.options.basePath??"",r),c;if(pt(t.docsAuth)){let u=t.docsAuth;c=[u.middleware];let d=An(i??o);for(let p of u.routes)this.app.on(p.method,[me(d,p.name)],p.handler);}else c=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...c,u=>u.json(this.buildOpenApiSpec())),i){let u=Tn(i,o);this.app.on("GET",[i],...c,d=>d.html(lt(u,t.info.title)));}}};function wt(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function xn(e){if(e)return wt(e)?e.handler:e}function Rn(e){return wt(e)?e:void 0}function Sn(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function me(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function An(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Tn(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);n.pop();let o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let i=n.length-o;return [...Array(i).fill(".."),...r.slice(o)].join("/")||"./"}function vn(e,t,n,r,o,i,c){let u=e.input,d=e.output,p=e.status??200,m=o??bn;return async y=>{let b=async C=>{if(i){let S=await i.handle({error:C,c:y,route:e,services:m,logger:c});if(S)return S}return st(y,C)},O=async()=>{let C,S;try{S=await kn(y,t,e.method);}catch(f){throw new ie(f instanceof Error?f.message:String(f))}if(u){let f=u.safeParse(S);if(!f.success)throw new ne(f.error,t);C=f.data;}else C=S;let z=await e.handler({input:C,c:y,services:m,errorHandler:i,logger:c});if(n&&d&&!(z instanceof Response)){let f=d.safeParse(z);if(!f.success)throw new ae(f.error);return f.data}return z},N;if(r)try{N=await r({next:O,route:e,c:y,services:m,errorHandler:i,logger:c});}catch(C){let S=await b(C);if(S)return S;throw C}else try{N=await O();}catch(C){let S=await b(C);if(S)return S;throw C}return N instanceof Response?N:y.json(N,p)}}async function kn(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let r=await e.req.text();if(!r)return {};try{return JSON.parse(r)}catch(o){throw new Error(`Invalid JSON body: ${o instanceof Error?o.message:String(o)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function Cr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:i=false,httpsOptions:c}=e,u=t==="/"?"":t.replace(/\/$/,""),d={};for(let[f,s]of Object.entries(n)){if(!s.repo)throw new Error(`[createCrudServer] Repository "${f}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let g=s.schema??s.repo.schema??null;if(!g)throw new Error(`[createCrudServer] Repository "${f}" has no Zod schema.`);let a,w,h,R;if(s.fieldsConfig){let _=s.fieldsConfig;a=[],w=[],h=[],R=[];for(let[E,A]of Object.entries(_))for(let $ of A)$==="filterable"?a.push(E):$==="orderable"?w.push(E):$==="mutable"?h.push(E):$==="create"&&R.push(E);w.length===0&&(w=a),a.length===0&&(a=void 0),w&&w.length===0&&(w=void 0),h.length===0&&(h=void 0),R.length===0&&(R=void 0);}let v=(()=>{let _=s.repo._parentKeys;return _&&_.length>0?_:void 0})();if(v&&R)for(let _ of v)R.includes(_)||R.push(_);let l=s.repo._systemKeys??[s.documentKey??"docId"],T=s.repo._historyIdentityKeys??[],P=Array.from(new Set([...l,...T])),D={name:f,path:s.path,repo:s.repo,schema:g,systemKeys:P,documentKey:s.documentKey??"docId",pathKey:s.repo._pathKey??void 0,isGroup:!!s.repo._isGroup,parentKeys:v,documentPathTemplate:s.repo._documentPathTemplate??void 0,createdKey:s.repo._createdKey??void 0,pageSize:s.pageSize??25,filterableFields:a,orderableFields:w,mutableFields:h,createFields:R,allowDelete:s.allowDelete??false,allowedIncludes:s.allowedIncludes,validate:s.validate,rules:s.rules};d[f]=D;}let p=e.indexesError??e.onIndexError,m=et(d,u,i,p),y=e.openapi,b=y&&typeof y=="object"?y:{},O=null;function N(){return O||(O=Pe(d,u,{...b,auth:b.auth??false})),O}let C=[];for(let f of Object.keys(d))C.push({api:"crud",method:"post",path:`/${f}/query`,source:"json",handler:m.handleQuery}),C.push({api:"crud",method:"get",path:`/${f}/:id`,source:"query",handler:m.handleGet}),C.push({api:"crud",method:"post",path:`/${f}`,source:"json",handler:m.handleCreate}),C.push({api:"crud",method:"put",path:`/${f}/:id`,source:"json",handler:s=>m.handleUpdate(s,false)}),C.push({api:"crud",method:"patch",path:`/${f}/:id`,source:"json",handler:s=>m.handleUpdate(s,true)}),C.push({api:"crud",method:"delete",path:`/${f}/:id`,source:"query",handler:m.handleDelete}),C.push({api:"crud",method:"post",path:`/${f}/batch`,source:"json",handler:m.handleBatch});let S=new ge({...e,openapi:y!==false?{path:b.path??"/openapi.json",docsPath:b.docsPath??"/docs",info:{title:b.title??"CRUD API",version:b.version??"1.0.0"},docsAuth:b.docsAuth}:void 0,basePath:t,api:"crud",routes:C,middlewares:[async(f,s)=>{if(f.req.method==="OPTIONS")return f.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});f.header("Access-Control-Allow-Origin","*"),f.header("Access-Control-Allow-Credentials","true"),await s();},...e.middlewares||[]]});if(y!==false&&(S.buildOpenApiSpec=N),o!==false){let{securityHeaders:f}=(At(),Pt(St)),s=o===void 0?{csp:false}:o;S.hono.use("*",async(g,a)=>{let w=f(s);await new Promise(h=>{let R=g.req.raw;w(R,{setHeader:(l,T)=>g.header(l,T),removeHeader:l=>g.res.headers.delete(l)},()=>h());}),await a();});}let z=S.nodeHandler;return z.spec=N,c&&(z.httpsOptions=c),z}exports.applyRules=We;exports.computeDeepDiff=le;exports.createBeforeRules=Kt;exports.createCrudServer=Cr;exports.createRules=Ut;exports.generateOpenAPISpec=Pe;//# sourceMappingURL=index.cjs.map
|
|
12
|
+
</html>`}function St(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var $e=new async_hooks.AsyncLocalStorage;function vt(){return async(e,t)=>{await $e.run({c:e},async()=>{await t();});}}var jn=Object.freeze({}),Te=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=Fn(t.routes,t.api),this.app.use("*",Ge(t.actorResolver)),t.services&&this.app.use("*",vt());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return nodeServer.getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=kt(this.mountedRoutes,this.options.basePath??"",this.options.openapi,zn(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,r=this.options.verbose??false;for(let o of this.mountedRoutes){if(!o.path)throw new Error(`[HonoServer] route "${o.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let i=Re(t,o.path),c=o.middlewares??[],d=o.source??(o.method==="get"?"query":"json"),u=Mn(o,d,n,_n(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),p=o.method.toUpperCase();this.app.on(p,[i],...c,u),r&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${i}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,o=Re(this.options.basePath??"",n),i=r===false?null:Re(this.options.basePath??"",r),c;if(St(t.docsAuth)){let d=t.docsAuth;c=[d.middleware];let u=Nn(i??o);for(let p of d.routes)this.app.on(p.method,[Re(u,p.name)],p.handler);}else c=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...c,d=>d.json(this.buildOpenApiSpec())),i){let d=qn(i,o);this.app.on("GET",[i],...c,u=>u.html(Ct(d,t.info.title)));}}};function Et(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function _n(e){if(e)return Et(e)?e.handler:e}function zn(e){return Et(e)?e:void 0}function Fn(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function Re(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function Nn(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function qn(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);n.pop();let o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let i=n.length-o;return [...Array(i).fill(".."),...r.slice(o)].join("/")||"./"}function Mn(e,t,n,r,o,i,c){let d=e.input,u=e.output,p=e.status??200,w=o??jn;return async h=>{let R=async D=>{if(i){let C=await i.handle({error:D,c:h,route:e,services:w,logger:c});if(C)return C}return bt(h,D)},E=async()=>{let D,C;try{C=await $n(h,t,e.method);}catch(N){throw new le(N instanceof Error?N.message:String(N))}if(d){let N=d.safeParse(C);if(!N.success)throw new ae(N.error,t);D=N.data;}else D=C;let z=await e.handler({input:D,c:h,services:w,errorHandler:i,logger:c});if(n&&u&&!(z instanceof Response)){let N=u.safeParse(z);if(!N.success)throw new pe(N.error);return N.data}return z},$;if(r)try{$=await r({next:E,route:e,c:h,services:w,errorHandler:i,logger:c});}catch(D){let C=await R(D);if(C)return C;throw D}else try{$=await E();}catch(D){let C=await R(D);if(C)return C;throw D}return $ instanceof Response?$:h.json($,p)}}async function $n(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let r=await e.req.text();if(!r)return {};try{return JSON.parse(r)}catch(o){throw new Error(`Invalid JSON body: ${o instanceof Error?o.message:String(o)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function Zn(e){return e}async function Ot(e,t){if(e?.length){for(let n of e)if(typeof n=="function")await n(t);else if(n&&typeof n.mutation=="function"){if(n.operations&&!n.operations.includes(t.operation))continue;await n.mutation(t);}}}async function Ze(e,t,n,r,o,i=t?"update":"create"){for(let c of Object.keys(n.changes))await Ot(r[c],{body:e,doc:t,diff:n,key:c,operation:i,user:o});await Ot(r["*"],{body:e,doc:t,diff:n,key:"*",operation:i,user:o});}function Bn(e){return async t=>{await Ze(t.body,t.doc,t.diff,e,t.user,"update");}}function Un(e){return async t=>{let n=G({},t.body);await Ze(t.body,null,n,e,t.user,"create");}}function Kn(e){return e}async function It(e,t,n,r,o,i,c,d){if(!e?.length)return i;let u=i;for(let p of e){let w=null,h=false;try{if(h=!!await p.rule({diff:n,key:t,user:c,operation:d}),h){let R=await p.handler(r);R&&(u={...u,...R});}}catch(R){w=R;}o.push({key:String(t),description:p.description,isCalled:h,error:w});}return u}async function Pt(e,t,n,r,o="update"){let i=[],c={};for(let d of Object.keys(e.changes))c=await It(t[d],d,e,n,i,c,r,o);return c=await It(t["*"],"*",e,n,i,c,r,o),{results:i,changesNeeded:c,hasErrors:i.some(d=>d.error!==null)}}function Ln(e,t,n){return async r=>{let o=t(r),{results:i,changesNeeded:c}=await Pt(r.diff,e,o,r.user,"update");if(n?.onRuleError)for(let d of i)d.error&&await n.onRuleError(d,r);return Object.keys(c).length>0?c:void 0}}function io(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:i=false,httpsOptions:c}=e,d=t==="/"?"":t.replace(/\/$/,""),u={};for(let[a,l]of Object.entries(n)){if(!l.repo)throw new Error(`[createCrudServer] Repository "${a}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let s=l.schema??l.repo.schema??null;if(!s)throw new Error(`[createCrudServer] Repository "${a}" has no Zod schema.`);let g,y,v,k;if(l.fieldsConfig){let P=l.fieldsConfig;g=[],y=[],v=[],k=[];for(let[A,S]of Object.entries(P))for(let I of S)I==="filterable"?g.push(A):I==="orderable"?y.push(A):I==="mutable"?v.push(A):I==="create"&&k.push(A);y.length===0&&(y=g),g.length===0&&(g=void 0),y&&y.length===0&&(y=void 0),v.length===0&&(v=void 0),k.length===0&&(k=void 0);}let m=(()=>{let P=l.repo._parentKeys;return P&&P.length>0?P:void 0})();if(m&&k)for(let P of m)k.includes(P)||k.push(P);let j=l.repo._systemKeys??[l.documentKey??"docId"],q=l.repo._historyIdentityKeys??[],_=Array.from(new Set([...j,...q])),M=l.repo._historyConfig,f=M?.enabled&&M.autoInjectMeta!==false?fe(M):null,b=f?{reason:f.fields.reason!==false,comment:f.fields.comment!==false}:void 0,O={name:a,path:l.path,repo:l.repo,schema:s,systemKeys:_,documentKey:l.documentKey??"docId",pathKey:l.repo._pathKey??void 0,isGroup:!!l.repo._isGroup,parentKeys:m,documentPathTemplate:l.repo._documentPathTemplate??void 0,createdKey:l.repo._createdKey??void 0,pageSize:l.pageSize??25,filterableFields:g,orderableFields:y,mutableFields:v,createFields:k,allowDelete:l.allowDelete??false,allowedIncludes:l.allowedIncludes,validate:l.validate,rules:l.rules,hooks:l.hooks,...b?{historyHeaders:b}:{}};u[a]=O;}let p=e.indexesError??e.onIndexError,w=yt(u,d,i,p,e.onHookError),h=e.openapi,R=h&&typeof h=="object"?h:{},E=We(e.actorResolver),$=R.historyHeaders===false?false:{reasonHeader:R.historyHeaders?.reasonHeader!==void 0?R.historyHeaders.reasonHeader:E.reasonHeader,commentHeader:R.historyHeaders?.commentHeader!==void 0?R.historyHeaders.commentHeader:E.commentHeader,...R.historyHeaders?.extraHeaders?{extraHeaders:R.historyHeaders.extraHeaders}:{}},D=(()=>{let a=["Content-Type","Authorization"],l=new Set(a.map(g=>g.toLowerCase())),s=g=>{if(typeof g!="string")return;let y=g.trim();!y||l.has(y.toLowerCase())||(l.add(y.toLowerCase()),a.push(y));};if(s(E.reasonHeader),s(E.commentHeader),R.historyHeaders&&typeof R.historyHeaders=="object"&&(s(R.historyHeaders.reasonHeader),s(R.historyHeaders.commentHeader),R.historyHeaders.extraHeaders))for(let g of R.historyHeaders.extraHeaders)s(typeof g=="string"?g:g?.name);return a.join(", ")})(),C=null;function z(){return C||(C=qe(u,d,{...R,auth:R.auth??false,historyHeaders:$})),C}let N=[];for(let a of Object.keys(u))N.push({api:"crud",method:"post",path:`/${a}/query`,source:"json",handler:w.handleQuery}),N.push({api:"crud",method:"get",path:`/${a}/:id`,source:"query",handler:w.handleGet}),N.push({api:"crud",method:"post",path:`/${a}`,source:"json",handler:w.handleCreate}),N.push({api:"crud",method:"put",path:`/${a}/:id`,source:"json",handler:l=>w.handleUpdate(l,false)}),N.push({api:"crud",method:"patch",path:`/${a}/:id`,source:"json",handler:l=>w.handleUpdate(l,true)}),N.push({api:"crud",method:"delete",path:`/${a}/:id`,source:"query",handler:w.handleDelete}),N.push({api:"crud",method:"post",path:`/${a}/batch`,source:"json",handler:w.handleBatch});let W=new Te({...e,openapi:h!==false?{path:R.path??"/openapi.json",docsPath:R.docsPath??"/docs",info:{title:R.title??"CRUD API",version:R.version??"1.0.0"},docsAuth:R.docsAuth}:void 0,basePath:t,api:"crud",routes:N,middlewares:[async(a,l)=>{if(a.req.method==="OPTIONS")return a.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":D,"Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});a.header("Access-Control-Allow-Origin","*"),a.header("Access-Control-Allow-Credentials","true"),await l();},...e.middlewares||[]]});if(h!==false&&(W.buildOpenApiSpec=z),o!==false){let{securityHeaders:a}=(zt(),Ut(_t)),l=o===void 0?{csp:false}:o;W.hono.use("*",async(s,g)=>{let y=a(l);await new Promise(v=>{let k=s.req.raw;y(k,{setHeader:(j,q)=>s.header(j,q),removeHeader:j=>s.res.headers.delete(j)},()=>v());}),await g();});}let x=W.nodeHandler;return x.spec=z,c&&(x.httpsOptions=c),x}exports.applyEffects=Pt;exports.applyMutations=Ze;exports.applyRules=ct;exports.computeDeepDiff=G;exports.createAfterUpdateEffects=Ln;exports.createBeforeCreateMutations=Un;exports.createBeforeRules=dn;exports.createBeforeUpdateMutations=Bn;exports.createCrudServer=io;exports.createEffects=Kn;exports.createMutations=Zn;exports.createRules=cn;exports.generateOpenAPISpec=qe;//# sourceMappingURL=index.cjs.map
|
|
13
13
|
//# sourceMappingURL=index.cjs.map
|