@gusto/baerly-storage 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +97 -0
- package/dist/API.md +850 -0
- package/dist/app-config-Cb5dO2s9.d.ts +480 -0
- package/dist/app-config.d.ts +2 -0
- package/dist/app-config.js +8 -0
- package/dist/app-config.js.map +1 -0
- package/dist/auth.d.ts +237 -0
- package/dist/auth.js +1335 -0
- package/dist/auth.js.map +1 -0
- package/dist/baerly.js +761 -0
- package/dist/baerly.js.map +1 -0
- package/dist/bucket-uri-BrDEYvzy.js +4922 -0
- package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
- package/dist/chunk-EAsCxrDo.js +14 -0
- package/dist/client-BLf3Ae5s.d.ts +233 -0
- package/dist/client-react.d.ts +131 -0
- package/dist/client-react.js +559 -0
- package/dist/client-react.js.map +1 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.js +160 -0
- package/dist/client.js.map +1 -0
- package/dist/cloudflare-CINJPKCW.js +911 -0
- package/dist/cloudflare-CINJPKCW.js.map +1 -0
- package/dist/cloudflare.d.ts +211 -0
- package/dist/cloudflare.js +445 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/config-Bsg8wgwo.js +198 -0
- package/dist/config-Bsg8wgwo.js.map +1 -0
- package/dist/context-Oj7ffwD-.js +187 -0
- package/dist/context-Oj7ffwD-.js.map +1 -0
- package/dist/cost-B1WiZxlf.js +203 -0
- package/dist/cost-B1WiZxlf.js.map +1 -0
- package/dist/current-json-BkatBzF7.js +252 -0
- package/dist/current-json-BkatBzF7.js.map +1 -0
- package/dist/db-D62JguBc.d.ts +336 -0
- package/dist/deploy-BB-wqbhf.js +83 -0
- package/dist/deploy-BB-wqbhf.js.map +1 -0
- package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
- package/dist/dev-vite.d.ts +146 -0
- package/dist/dev-vite.js +223 -0
- package/dist/dev-vite.js.map +1 -0
- package/dist/dev.d.ts +3 -0
- package/dist/dev.js +2 -0
- package/dist/doctor-B8h9GCN9.js +331 -0
- package/dist/doctor-B8h9GCN9.js.map +1 -0
- package/dist/dump-BHo_sIMZ.js +116 -0
- package/dist/dump-BHo_sIMZ.js.map +1 -0
- package/dist/errors-DOdL95kK.js +58 -0
- package/dist/errors-DOdL95kK.js.map +1 -0
- package/dist/export-Dz2PZKSR.js +423 -0
- package/dist/export-Dz2PZKSR.js.map +1 -0
- package/dist/fsck-DEz9lyCy.js +293 -0
- package/dist/fsck-DEz9lyCy.js.map +1 -0
- package/dist/http-CjUO1Bec.js +1756 -0
- package/dist/http-CjUO1Bec.js.map +1 -0
- package/dist/http.d.ts +1619 -0
- package/dist/http.js +2 -0
- package/dist/index-BGC-ENnj.d.ts +1065 -0
- package/dist/index-BYv0hb8M.d.ts +1457 -0
- package/dist/index-BquQkhJi.d.ts +112 -0
- package/dist/index-COsQ-Mlz.d.ts +146 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/indexes-BXn7a06a.js +297 -0
- package/dist/indexes-BXn7a06a.js.map +1 -0
- package/dist/indexes-DwOXkn1Y.d.ts +22 -0
- package/dist/inspect-x02aFWnh.js +149 -0
- package/dist/inspect-x02aFWnh.js.map +1 -0
- package/dist/log-walk-DIru96UT.js +260 -0
- package/dist/log-walk-DIru96UT.js.map +1 -0
- package/dist/maintenance-Bn6ul9aV.js +758 -0
- package/dist/maintenance-Bn6ul9aV.js.map +1 -0
- package/dist/maintenance.d.ts +323 -0
- package/dist/maintenance.js +2 -0
- package/dist/node.d.ts +422 -0
- package/dist/node.js +2 -0
- package/dist/normalize-XWY25_sG.js +133 -0
- package/dist/normalize-XWY25_sG.js.map +1 -0
- package/dist/observability-2IDYRuZK.js +2333 -0
- package/dist/observability-2IDYRuZK.js.map +1 -0
- package/dist/observability.d.ts +3 -0
- package/dist/observability.js +3 -0
- package/dist/plan-Cs17VqjU.js +224 -0
- package/dist/plan-Cs17VqjU.js.map +1 -0
- package/dist/query-DcSbFLJt.js +1880 -0
- package/dist/query-DcSbFLJt.js.map +1 -0
- package/dist/rebuild-index-C5gTXryd.js +119 -0
- package/dist/rebuild-index-C5gTXryd.js.map +1 -0
- package/dist/rebuild-index-DwXM0WfA.js +104 -0
- package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
- package/dist/request-BEF_OvMh.js +72 -0
- package/dist/request-BEF_OvMh.js.map +1 -0
- package/dist/restore-CbKVMMpm.js +847 -0
- package/dist/restore-CbKVMMpm.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js +71 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -0
- package/dist/snapshot-D7C4_FSl.js +71 -0
- package/dist/snapshot-D7C4_FSl.js.map +1 -0
- package/dist/snapshot-z_N9hpTe.js +917 -0
- package/dist/snapshot-z_N9hpTe.js.map +1 -0
- package/dist/src-Chafbw8r.js +522 -0
- package/dist/src-Chafbw8r.js.map +1 -0
- package/dist/src-DyET_VPP.js +6199 -0
- package/dist/src-DyET_VPP.js.map +1 -0
- package/dist/src-n0Te1r98.js +352 -0
- package/dist/src-n0Te1r98.js.map +1 -0
- package/dist/subcommand-BWs6K7zb.js +110 -0
- package/dist/subcommand-BWs6K7zb.js.map +1 -0
- package/dist/usage-RVUQMLop.js +339 -0
- package/dist/usage-RVUQMLop.js.map +1 -0
- package/dist/validate-DhH1lO8I.js +377 -0
- package/dist/validate-DhH1lO8I.js.map +1 -0
- package/dist/wire-izfGZDvr.js +7 -0
- package/dist/wire-izfGZDvr.js.map +1 -0
- package/package.json +189 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { _ as StorageListEntry, g as StorageGetResult, h as StorageGetOptions, m as Storage, v as StoragePutOptions, y as StoragePutResult } from "./index-BGC-ENnj.js";
|
|
2
|
+
|
|
3
|
+
//#region packages/dev/src/dev-landing.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Dev landing page for the API root (`GET /`).
|
|
6
|
+
*
|
|
7
|
+
* The HTTP surface is API-only: every path outside `/v1/*`
|
|
8
|
+
* returns the {@link HttpErrorEnvelope} 404 shape. That's correct for
|
|
9
|
+
* production but confusing in local dev — a user who clicks the
|
|
10
|
+
* `http://localhost:3000` link in their terminal sees a JSON 404 and
|
|
11
|
+
* assumes the server is broken.
|
|
12
|
+
*
|
|
13
|
+
* Adapters that wire the {@link DevLandingOptions} opt-in surface a
|
|
14
|
+
* small HTML page on `GET /` instead: app label, a clickable link to
|
|
15
|
+
* the UI, a `/v1/healthz` probe link, and a note that `/v1/c/*` is
|
|
16
|
+
* auth-gated. `GET /favicon.ico` answers 204 so browsers don't pin a
|
|
17
|
+
* second JSON 404 next to the landing page.
|
|
18
|
+
*
|
|
19
|
+
* Production deployments leave the option unset; the 404 falls
|
|
20
|
+
* through to the existing envelope.
|
|
21
|
+
*/
|
|
22
|
+
/** Options for {@link renderDevLanding}. */
|
|
23
|
+
interface DevLandingOptions {
|
|
24
|
+
/** Bucket-prefix / app name (typically passed through from the adapter's `app` option). */
|
|
25
|
+
readonly app: string;
|
|
26
|
+
/** URL of the human-facing UI (e.g., `"http://localhost:5173"`). */
|
|
27
|
+
readonly uiUrl: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Render the dev landing page HTML. Dependency-free; system fonts
|
|
31
|
+
* only; no JS. All substitutions are HTML-escaped to keep the page
|
|
32
|
+
* inert even when `app` / `uiUrl` come from env vars.
|
|
33
|
+
*/
|
|
34
|
+
declare const renderDevLanding: (opts: DevLandingOptions) => string;
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region packages/dev/src/ensure-table.d.ts
|
|
37
|
+
/**
|
|
38
|
+
* Optional pre-warm: idempotently create the `current.json` manifest
|
|
39
|
+
* for a single `(app, tenant, table)` triple. The kernel auto-creates
|
|
40
|
+
* this manifest on the first commit anyway (see `Db.create` and
|
|
41
|
+
* `Writer.commit`), so calling `ensureTable` is **not required** for
|
|
42
|
+
* correctness — it's a one-Class-A-PUT optimization for callers that
|
|
43
|
+
* want the manifest in place before the first request lands (seed
|
|
44
|
+
* scripts, deploy-time provisioning, CI fixtures that snapshot the
|
|
45
|
+
* bucket between phases, etc.).
|
|
46
|
+
*
|
|
47
|
+
* Wraps {@link createCurrentJson} with the canonical key shape
|
|
48
|
+
* (`app/<app>/tenant/<tenant>/manifests/<table>/current.json`) and
|
|
49
|
+
* swallows `BaerlyError{code:"Conflict"}` so re-runs are safe. An
|
|
50
|
+
* existing manifest is preserved verbatim — this function never
|
|
51
|
+
* overwrites a populated manifest. The seed shape matches the
|
|
52
|
+
* kernel's auto-create exactly, so a pre-warm and an
|
|
53
|
+
* auto-provisioned bucket are byte-identical.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```ts
|
|
57
|
+
* import { LocalFsStorage, ensureTable } from "@gusto/baerly-storage/dev";
|
|
58
|
+
*
|
|
59
|
+
* const storage = new LocalFsStorage({ root: "./.baerly-data" });
|
|
60
|
+
* // Pre-warm so the first request doesn't pay the bootstrap PUT.
|
|
61
|
+
* await ensureTable(storage, { app: "helpdesk", tenant: "demo", table: "tickets" });
|
|
62
|
+
* // …then `baerlyNode({ config, storage, verifier })`.
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
declare const ensureTable: (storage: Storage, args: {
|
|
66
|
+
app: string;
|
|
67
|
+
tenant: string;
|
|
68
|
+
table: string;
|
|
69
|
+
}) => Promise<void>;
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region packages/dev/src/local-fs.d.ts
|
|
72
|
+
interface LocalFsStorageOptions {
|
|
73
|
+
/** Root directory; treated as "the bucket". */
|
|
74
|
+
root: string;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* `Storage` backed by a directory tree. Keys may contain `/` and map
|
|
78
|
+
* to nested directories on disk so `ls`/`cat` work as expected.
|
|
79
|
+
*
|
|
80
|
+
* ETags are content-addressed: `"<sha-256-hex>"` (the surrounding
|
|
81
|
+
* double-quotes match S3's wire format for non-multipart objects).
|
|
82
|
+
* Identical bodies share an ETag across runs — the property that
|
|
83
|
+
* makes this adapter useful for fixture-based tests.
|
|
84
|
+
*
|
|
85
|
+
* Writes are atomic via `writeFile(temp) + rename(final)`; readers
|
|
86
|
+
* never see a partially-written file. The adapter does NOT coordinate
|
|
87
|
+
* cross-process `ifMatch`/`ifNoneMatch` checks (a TOCTOU race is
|
|
88
|
+
* possible if two processes write the same key concurrently).
|
|
89
|
+
* Single-process `baerlyDev()` is the design center; multi-process
|
|
90
|
+
* scenarios use the S3 / Minio path.
|
|
91
|
+
*
|
|
92
|
+
* Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in
|
|
93
|
+
* `@baerly/dev` because the protocol kernel is pure-modules / no I/O
|
|
94
|
+
* and must remain Worker-bundleable.
|
|
95
|
+
*/
|
|
96
|
+
declare class LocalFsStorage implements Storage {
|
|
97
|
+
#private;
|
|
98
|
+
constructor(opts: LocalFsStorageOptions);
|
|
99
|
+
get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null>;
|
|
100
|
+
put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult>;
|
|
101
|
+
delete(key: string, opts?: {
|
|
102
|
+
signal?: AbortSignal;
|
|
103
|
+
}): Promise<void>;
|
|
104
|
+
list(prefix: string, opts?: {
|
|
105
|
+
startAfter?: string;
|
|
106
|
+
maxKeys?: number;
|
|
107
|
+
signal?: AbortSignal;
|
|
108
|
+
}): AsyncIterable<StorageListEntry>;
|
|
109
|
+
}
|
|
110
|
+
//#endregion
|
|
111
|
+
export { renderDevLanding as a, DevLandingOptions as i, LocalFsStorageOptions as n, ensureTable as r, LocalFsStorage as t };
|
|
112
|
+
//# sourceMappingURL=index-BquQkhJi.d.ts.map
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { d as IndexDefinition, f as DocumentData, n as BaerlyAppConfig, r as BaerlyConfig, u as SchemaValidator } from "./app-config-Cb5dO2s9.js";
|
|
2
|
+
import { m as Storage, n as LogEntry, r as Verifier } from "./index-BGC-ENnj.js";
|
|
3
|
+
//#region packages/server/src/config.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Flatten `BaerlyConfig.collections` into the per-collection
|
|
6
|
+
* `schemas` and `indexes` maps that {@link Db.create} consumes at
|
|
7
|
+
* runtime. Used by the Cloudflare and Node adapters to pipe a
|
|
8
|
+
* single `config` object through to the writer/planner.
|
|
9
|
+
*
|
|
10
|
+
* Both adapters import this helper rather than inlining the loop
|
|
11
|
+
* so the projection rule (drop empty index arrays; omit absent
|
|
12
|
+
* schemas) stays in one place. Future `CollectionDefinition`
|
|
13
|
+
* fields (lifecycle hooks, replica_identity) land here too.
|
|
14
|
+
*/
|
|
15
|
+
declare const collectionsToMaps: (collections: BaerlyConfig["collections"] | undefined) => {
|
|
16
|
+
schemas: ReadonlyMap<string, SchemaValidator>;
|
|
17
|
+
indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>;
|
|
18
|
+
};
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region packages/server/src/auth/internal/resolve-verifier.d.ts
|
|
21
|
+
/**
|
|
22
|
+
* Read env var lazily via a host-supplied accessor so the same
|
|
23
|
+
* resolver works in CF Workers (env binding) and Node
|
|
24
|
+
* (`process.env`). Returns `undefined` for an unset OR empty string —
|
|
25
|
+
* both branches mean "operator forgot to set it".
|
|
26
|
+
*/
|
|
27
|
+
type EnvAccessor = (name: string) => string | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Inputs to {@link resolveVerifier}. `factoryVerifier` is the
|
|
30
|
+
* adapter-factory `verifier:` option (may be undefined). `config`
|
|
31
|
+
* carries the typed `auth` posture + the `tenant` pin. `readEnv`
|
|
32
|
+
* is the per-host env accessor.
|
|
33
|
+
*/
|
|
34
|
+
interface ResolveVerifierInput {
|
|
35
|
+
readonly factoryVerifier: Verifier | undefined;
|
|
36
|
+
readonly config: BaerlyAppConfig;
|
|
37
|
+
readonly readEnv: EnvAccessor;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Resolve the per-request `Verifier` for an adapter factory using the
|
|
41
|
+
* fixed order:
|
|
42
|
+
*
|
|
43
|
+
* 1. `factoryVerifier` set → use as-is (highest precedence; enables
|
|
44
|
+
* env-aware construction via `cloudflareAccess(env)` etc).
|
|
45
|
+
* 2. else `config.auth === "shared-secret"` → read `SHARED_SECRET`
|
|
46
|
+
* via `readEnv`; throw `BaerlyError("InvalidConfig",
|
|
47
|
+
* SHARED_SECRET_MISSING_MESSAGE)` when unset/empty; else build
|
|
48
|
+
* `sharedSecret({ secret, tenantPrefix: config.tenant })`.
|
|
49
|
+
* 3. else `config.auth === "none"` → `noAuthVerifier(config.tenant)`.
|
|
50
|
+
* 4. else → throw `BaerlyError("InvalidConfig",
|
|
51
|
+
* NO_AUTH_CONFIGURED_MESSAGE)`.
|
|
52
|
+
*
|
|
53
|
+
* Pure function — no I/O, no side effects beyond `sharedSecret`'s
|
|
54
|
+
* own validation. Caller invokes once at adapter init time (or on
|
|
55
|
+
* first fetch, depending on platform `await`-at-top-level
|
|
56
|
+
* constraints).
|
|
57
|
+
*
|
|
58
|
+
* @throws BaerlyError code="InvalidConfig" — branches 2 and 4 above.
|
|
59
|
+
*
|
|
60
|
+
* @internal
|
|
61
|
+
*/
|
|
62
|
+
declare const resolveVerifier: (input: ResolveVerifierInput) => Verifier;
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region packages/server/src/snapshot.d.ts
|
|
65
|
+
/**
|
|
66
|
+
* Build the on-bucket key for a snapshot file. `sha256` must be the
|
|
67
|
+
* lowercase hex digest of the canonical body
|
|
68
|
+
* ({@link encodeSnapshotBody}); the filename embeds it so a crashed
|
|
69
|
+
* mid-PUT body that doesn't match its own filename hash is rejected
|
|
70
|
+
* by readers as "missing."
|
|
71
|
+
*
|
|
72
|
+
* @throws BaerlyError code="InvalidConfig" — `minSeq`/`maxSeq` are
|
|
73
|
+
* out of range or `sha256` is not 64 hex chars.
|
|
74
|
+
*/
|
|
75
|
+
declare const snapshotKey: (collectionPrefix: string, minSeq: number, maxSeq: number, sha256: string) => string;
|
|
76
|
+
/**
|
|
77
|
+
* On-bucket body of a snapshot file. The reader recomputes the SHA-256
|
|
78
|
+
* over the canonical serialisation ({@link encodeSnapshotBody}) and
|
|
79
|
+
* rejects any mismatch with the filename hash.
|
|
80
|
+
*
|
|
81
|
+
* `docs` is sorted by `_id` for deterministic byte output — two
|
|
82
|
+
* compactions over the same fold produce byte-identical snapshots,
|
|
83
|
+
* which means same filename, which means an idempotent re-run never
|
|
84
|
+
* leaves an orphan.
|
|
85
|
+
*/
|
|
86
|
+
interface SnapshotBody {
|
|
87
|
+
readonly schema_version: 1;
|
|
88
|
+
readonly min_seq: number;
|
|
89
|
+
readonly max_seq: number;
|
|
90
|
+
readonly collection: string;
|
|
91
|
+
readonly docs: ReadonlyArray<{
|
|
92
|
+
readonly _id: string;
|
|
93
|
+
readonly body: DocumentData;
|
|
94
|
+
}>;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Canonical byte encoding of a {@link SnapshotBody}. Only the
|
|
98
|
+
* compactor produces snapshots, and only this function does the
|
|
99
|
+
* serialisation — so the byte output is deterministic for a given
|
|
100
|
+
* `SnapshotBody` (identical input ⇒ identical bytes ⇒ identical
|
|
101
|
+
* filename hash).
|
|
102
|
+
*/
|
|
103
|
+
declare const encodeSnapshotBody: (s: SnapshotBody) => Uint8Array;
|
|
104
|
+
/**
|
|
105
|
+
* Load a snapshot file as a `Map<_id, DocumentData>`. Verifies the
|
|
106
|
+
* body hash against the filename, checks the schema version, and
|
|
107
|
+
* cross-checks `body.collection` against the caller's expectation.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* import { loadSnapshotAsMap } from "@gusto/baerly-storage";
|
|
112
|
+
*
|
|
113
|
+
* const map =
|
|
114
|
+
* srcCurrent.snapshot === null
|
|
115
|
+
* ? new Map<string, DocumentData>()
|
|
116
|
+
* : await loadSnapshotAsMap(src.storage, srcCurrent.snapshot, "tickets");
|
|
117
|
+
* ```
|
|
118
|
+
*
|
|
119
|
+
* @throws BaerlyError code="Internal" — pointer resolves to no body,
|
|
120
|
+
* or the body's SHA-256 doesn't match the hash embedded in the
|
|
121
|
+
* filename. (Protocol invariant violation; a corrupted snapshot
|
|
122
|
+
* the reader cannot continue past.)
|
|
123
|
+
* @throws BaerlyError code="InvalidResponse" — body isn't valid JSON,
|
|
124
|
+
* isn't an object, has an unsupported `schema_version`, or carries a
|
|
125
|
+
* `collection` that doesn't match `expectedCollection`.
|
|
126
|
+
*/
|
|
127
|
+
declare const loadSnapshotAsMap: (storage: Storage, key: string, expectedCollection: string, signal?: AbortSignal) => Promise<Map<string, DocumentData>>;
|
|
128
|
+
//#endregion
|
|
129
|
+
//#region packages/server/src/log-walk.d.ts
|
|
130
|
+
/**
|
|
131
|
+
* Walk `[fromSeq, toSeqExclusive)` of `${logPrefix}/log/<seq>.json`
|
|
132
|
+
* in chunks of {@link MAX_PARALLEL_LOG_READS} concurrent GETs.
|
|
133
|
+
* Returns the materialised entries in seq order.
|
|
134
|
+
*
|
|
135
|
+
* Empty range (`fromSeq >= toSeqExclusive`) returns `[]` and issues
|
|
136
|
+
* zero GETs.
|
|
137
|
+
*
|
|
138
|
+
* Same error semantics as {@link readLogEntry}: a missing entry
|
|
139
|
+
* throws `Internal`, a malformed body throws `InvalidResponse`.
|
|
140
|
+
*/
|
|
141
|
+
declare const walkLogRange: (storage: Storage, logPrefix: string, fromSeq: number, toSeqExclusive: number, opts?: {
|
|
142
|
+
signal?: AbortSignal;
|
|
143
|
+
}) => Promise<LogEntry[]>;
|
|
144
|
+
//#endregion
|
|
145
|
+
export { snapshotKey as a, loadSnapshotAsMap as i, SnapshotBody as n, resolveVerifier as o, encodeSnapshotBody as r, collectionsToMaps as s, walkLogRange as t };
|
|
146
|
+
//# sourceMappingURL=index-COsQ-Mlz.d.ts.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { a as CollectionNames, c as defineConfig, d as IndexDefinition, f as DocumentData, i as CollectionDefinition, l as SchemaIssue, n as BaerlyAppConfig, o as RowOf, r as BaerlyConfig, s as UnboundConfig, u as SchemaValidator } from "./app-config-Cb5dO2s9.js";
|
|
2
|
+
import { _ as StorageListEntry, a as MemoryStorage, c as Collection, d as Query, g as StorageGetResult, i as VerifierResult, m as Storage, o as BaerlyError, r as Verifier, s as BaerlyErrorCode, y as StoragePutResult } from "./index-BGC-ENnj.js";
|
|
3
|
+
import { a as snapshotKey, i as loadSnapshotAsMap, n as SnapshotBody, o as resolveVerifier, r as encodeSnapshotBody, s as collectionsToMaps, t as walkLogRange } from "./index-COsQ-Mlz.js";
|
|
4
|
+
import { t as allIndexKeysFor } from "./indexes-DwOXkn1Y.js";
|
|
5
|
+
import { n as validateOrThrow, t as Db } from "./db-D62JguBc.js";
|
|
6
|
+
export { type BaerlyAppConfig, type BaerlyConfig, BaerlyError, type BaerlyErrorCode, type Collection, type CollectionDefinition, type CollectionNames, Db, type DocumentData, type IndexDefinition, MemoryStorage, type Query, type RowOf, type SchemaIssue, type SchemaValidator, type SnapshotBody, type Storage, type StorageGetResult, type StorageListEntry, type StoragePutResult, type UnboundConfig, type Verifier, type VerifierResult, allIndexKeysFor, collectionsToMaps, defineConfig, encodeSnapshotBody, loadSnapshotAsMap, resolveVerifier, snapshotKey, validateOrThrow, walkLogRange };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { defineConfig } from "./app-config.js";
|
|
2
|
+
import { t as BaerlyError } from "./errors-DOdL95kK.js";
|
|
3
|
+
import { o as validateOrThrow } from "./query-DcSbFLJt.js";
|
|
4
|
+
import { n as loadSnapshotAsMap, o as walkLogRange, r as snapshotKey, s as allIndexKeysFor, t as encodeSnapshotBody } from "./snapshot-z_N9hpTe.js";
|
|
5
|
+
import { i as MemoryStorage, n as resolveVerifier, r as collectionsToMaps, t as Db } from "./src-Chafbw8r.js";
|
|
6
|
+
export { BaerlyError, Db, MemoryStorage, allIndexKeysFor, collectionsToMaps, defineConfig, encodeSnapshotBody, loadSnapshotAsMap, resolveVerifier, snapshotKey, validateOrThrow, walkLogRange };
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { o as encodeJsonBytes } from "./bucket-uri-BrDEYvzy.js";
|
|
2
|
+
import { n as matchesWire, t as validateWire } from "./validate-DhH1lO8I.js";
|
|
3
|
+
import { o as BaerlyError } from "./baerly.js";
|
|
4
|
+
//#region ../server/src/indexes.ts
|
|
5
|
+
/**
|
|
6
|
+
* Secondary indexes — declarative collection-config-driven
|
|
7
|
+
* index entries that the writer emits inside the same CAS fence as
|
|
8
|
+
* the log entry and content body.
|
|
9
|
+
*
|
|
10
|
+
* The {@link IndexDefinition} TYPE lives in `@baerly/protocol`
|
|
11
|
+
* (cross-platform). This module owns the runtime helpers that
|
|
12
|
+
* operate on that shape:
|
|
13
|
+
*
|
|
14
|
+
* - {@link validateIndexDefinition} — synchronous schema check
|
|
15
|
+
* for path-segment safety; thrown at `Writer` construction.
|
|
16
|
+
* - {@link encodeIndexValue} — value-order-preserving base-32 of a
|
|
17
|
+
* type-tagged byte stream (null/bool tag-only, numbers as sortable
|
|
18
|
+
* IEEE 754, strings as raw UTF-8, objects as `JSON.stringify`
|
|
19
|
+
* bytes for equality only).
|
|
20
|
+
* - {@link indexKeyFor} / {@link indexKeyPrefix} — the wire-key
|
|
21
|
+
* shape consumed by the writer's index PUTs and the rebuild
|
|
22
|
+
* command's idempotent reconciliation.
|
|
23
|
+
* - {@link projectIndexValues} / {@link allIndexKeysFor} — pure
|
|
24
|
+
* projections from a doc body to the set of index keys it
|
|
25
|
+
* produces under a collection's declared indexes.
|
|
26
|
+
*
|
|
27
|
+
* Wire shape (single-field):
|
|
28
|
+
*
|
|
29
|
+
* `<logPrefix>/index/<indexName>/<value-b32>/<docId>.json`
|
|
30
|
+
*
|
|
31
|
+
* Wire shape (composite — accepted by the encoder, not consulted by
|
|
32
|
+
* the read path today):
|
|
33
|
+
*
|
|
34
|
+
* `<logPrefix>/index/<indexName>/<a-b32>/<b-b32>/<docId>.json`
|
|
35
|
+
*
|
|
36
|
+
* Body is zero bytes. Each entry is a fact ("doc `<docId>` has
|
|
37
|
+
* `<field> = <value>`"), not data. Readers list the prefix, extract
|
|
38
|
+
* the doc id from each key, then issue a content GET on each.
|
|
39
|
+
*
|
|
40
|
+
* Encoding is RFC-4648 base-32 (lowercase alphabet `[0-9a-v]`,
|
|
41
|
+
* matching `packages/protocol/src/log.ts:str2uintDesc` style) on a
|
|
42
|
+
* type-tagged byte stream (see {@link encodeIndexValue}) so that:
|
|
43
|
+
*
|
|
44
|
+
* - String "5" and number 5 produce distinct encodings
|
|
45
|
+
* (type-tag prefix keeps the slots disjoint).
|
|
46
|
+
* - Equal-by-value inputs produce byte-equal segments.
|
|
47
|
+
* - Lex order under storage `list(prefix)` matches value order:
|
|
48
|
+
* `null < false < true < number < string < object`, with
|
|
49
|
+
* numeric values ordered by IEEE 754 magnitude (range walks
|
|
50
|
+
* and `$in` walks over numeric fields are first-class — no
|
|
51
|
+
* planner fall-back to full-scan).
|
|
52
|
+
*
|
|
53
|
+
* Locked: single-field indexes only on the read path. Composite
|
|
54
|
+
* shape is documented and reserved (the path encoder accepts it).
|
|
55
|
+
*
|
|
56
|
+
* @see docs/spec/sync-protocol.md — fence model these PUTs land
|
|
57
|
+
* inside (between log PUT and `current.json` CAS-advance).
|
|
58
|
+
*/
|
|
59
|
+
/** Path-safe segment name. */
|
|
60
|
+
const INDEX_NAME_RE = /^[a-z_][a-z0-9_]*$/;
|
|
61
|
+
/**
|
|
62
|
+
* Lowercase base-32 alphabet, RFC 4648 variant matching the
|
|
63
|
+
* `packages/protocol/src/log.ts:str2uintDesc` style (`[0-9a-v]`).
|
|
64
|
+
* Lex-order-preserving under storage `list(prefix)` semantics.
|
|
65
|
+
*/
|
|
66
|
+
const B32_ALPHABET = "0123456789abcdefghijklmnopqrstuv";
|
|
67
|
+
/**
|
|
68
|
+
* Reject malformed {@link IndexDefinition} shapes synchronously.
|
|
69
|
+
* Thrown at writer construction so a config typo trips before any
|
|
70
|
+
* write lands.
|
|
71
|
+
*
|
|
72
|
+
* @throws BaerlyError code="SchemaError" — `name` doesn't match
|
|
73
|
+
* `/^[a-z_][a-z0-9_]*$/`; `on` is the empty string or empty
|
|
74
|
+
* array.
|
|
75
|
+
*/
|
|
76
|
+
const validateIndexDefinition = (def) => {
|
|
77
|
+
if (!INDEX_NAME_RE.test(def.name)) throw new BaerlyError("SchemaError", `index.name must match /^[a-z_][a-z0-9_]*$/; got ${JSON.stringify(def.name)}`);
|
|
78
|
+
if (typeof def.on === "string") {
|
|
79
|
+
if (def.on.length === 0) throw new BaerlyError("SchemaError", `index ${def.name}.on must be non-empty`);
|
|
80
|
+
} else if (def.on.length === 0) throw new BaerlyError("SchemaError", `index ${def.name}.on must be non-empty array`);
|
|
81
|
+
if (def.predicate !== void 0) try {
|
|
82
|
+
validateWire(def.predicate);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error instanceof BaerlyError) throw new BaerlyError("SchemaError", `index ${def.name}.predicate is invalid: ${error.message}`, error);
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Type-tag bytes for the value-order-preserving wire format. The
|
|
90
|
+
* tag is the LEADING byte of the encoded payload; the values are
|
|
91
|
+
* picked so the type order under byte-wise lex is
|
|
92
|
+
* `null < false < true < number < string < object`.
|
|
93
|
+
*
|
|
94
|
+
* | Type | Byte-prefix | Payload |
|
|
95
|
+
* |---------|-------------|----------------------------------------------------|
|
|
96
|
+
* | null | 0x10 | (none) |
|
|
97
|
+
* | false | 0x20 | (none) |
|
|
98
|
+
* | true | 0x21 | (none) |
|
|
99
|
+
* | number | 0x30 | 8-byte sortable big-endian IEEE 754 |
|
|
100
|
+
* | string | 0x40 | UTF-8 bytes of the string (no quotes, no escapes) |
|
|
101
|
+
* | object | 0x50 | UTF-8 bytes of `JSON.stringify(v)` |
|
|
102
|
+
*
|
|
103
|
+
* Local to the encoder by design — these are wire shape, not
|
|
104
|
+
* cross-package protocol constants (see `CLAUDE.md` § "Magic
|
|
105
|
+
* values").
|
|
106
|
+
*/
|
|
107
|
+
const TYPE_NULL = 16;
|
|
108
|
+
const TYPE_FALSE = 32;
|
|
109
|
+
const TYPE_TRUE = 33;
|
|
110
|
+
const TYPE_NUMBER = 48;
|
|
111
|
+
const TYPE_STRING = 64;
|
|
112
|
+
const TYPE_OBJECT = 80;
|
|
113
|
+
/**
|
|
114
|
+
* Encode a JS double as an 8-byte big-endian sortable IEEE 754
|
|
115
|
+
* payload. Byte-wise lex order on the result matches numeric order
|
|
116
|
+
* across all finite doubles plus `±Infinity`:
|
|
117
|
+
*
|
|
118
|
+
* 1. Get the 8-byte big-endian view of the double.
|
|
119
|
+
* 2. If the sign bit is `0` (zero or positive), flip the sign bit
|
|
120
|
+
* (XOR `0x80` on byte 0) so positives sort above negatives.
|
|
121
|
+
* 3. If the sign bit is `1` (negative), flip every bit in all 8
|
|
122
|
+
* bytes so more-negative sorts lower.
|
|
123
|
+
*
|
|
124
|
+
* `NaN` has no order-preserving slot and is rejected — see the
|
|
125
|
+
* `encodeIndexValue` JSDoc for the wire-contract rationale.
|
|
126
|
+
* `-0` and `+0` collapse because the `n === 0 ? 0 : n` coercion below
|
|
127
|
+
* forces both into the positive-zero branch before `setFloat64`.
|
|
128
|
+
*/
|
|
129
|
+
const encodeNumberPayload = (n) => {
|
|
130
|
+
if (Number.isNaN(n)) throw new BaerlyError("SchemaError", `encodeIndexValue: NaN is not indexable (the byte encoding has no order-preserving slot for it)`);
|
|
131
|
+
const buf = /* @__PURE__ */ new ArrayBuffer(8);
|
|
132
|
+
new DataView(buf).setFloat64(0, n === 0 ? 0 : n, false);
|
|
133
|
+
const bytes = new Uint8Array(buf);
|
|
134
|
+
if ((bytes[0] & 128) === 0) bytes[0] = bytes[0] ^ 128;
|
|
135
|
+
else for (let i = 0; i < 8; i++) bytes[i] = bytes[i] ^ 255;
|
|
136
|
+
return bytes;
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Compose the typed byte stream for one value. The leading byte is
|
|
140
|
+
* the type tag (see {@link TYPE_NULL} et al.); the payload shape is
|
|
141
|
+
* type-dependent. Strings are emitted as their raw UTF-8 bytes (no
|
|
142
|
+
* JSON quoting / escaping) so byte-wise lex order on encoded strings
|
|
143
|
+
* matches byte-wise lex order on the source UTF-8. Objects fall back
|
|
144
|
+
* to `JSON.stringify` for equality only.
|
|
145
|
+
*/
|
|
146
|
+
const encodeBytes = (v) => {
|
|
147
|
+
if (v === null || v === void 0) return new Uint8Array([TYPE_NULL]);
|
|
148
|
+
if (v === false) return new Uint8Array([TYPE_FALSE]);
|
|
149
|
+
if (v === true) return new Uint8Array([TYPE_TRUE]);
|
|
150
|
+
if (typeof v === "number") {
|
|
151
|
+
const payload = encodeNumberPayload(v);
|
|
152
|
+
const out = new Uint8Array(1 + payload.length);
|
|
153
|
+
out[0] = TYPE_NUMBER;
|
|
154
|
+
out.set(payload, 1);
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
if (typeof v === "string") {
|
|
158
|
+
const utf8 = new TextEncoder().encode(v);
|
|
159
|
+
const out = new Uint8Array(1 + utf8.length);
|
|
160
|
+
out[0] = TYPE_STRING;
|
|
161
|
+
out.set(utf8, 1);
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
const utf8 = encodeJsonBytes(v);
|
|
165
|
+
const out = new Uint8Array(1 + utf8.length);
|
|
166
|
+
out[0] = TYPE_OBJECT;
|
|
167
|
+
out.set(utf8, 1);
|
|
168
|
+
return out;
|
|
169
|
+
};
|
|
170
|
+
/**
|
|
171
|
+
* Encode an arbitrary `DocumentValue` value as a path-safe segment.
|
|
172
|
+
*
|
|
173
|
+
* Type-tagged byte stream, base-32-encoded for path safety. Lex
|
|
174
|
+
* order on encoded bytes matches:
|
|
175
|
+
*
|
|
176
|
+
* - **Type order**: `null < false < true < number < string < object`.
|
|
177
|
+
* - **Within numbers**: IEEE 754 numeric order (sortable
|
|
178
|
+
* big-endian payload, sign-bit-flipped or all-bits-flipped).
|
|
179
|
+
* `-Infinity` sorts lowest, `+Infinity` highest.
|
|
180
|
+
* - **Within strings**: UTF-8 byte order.
|
|
181
|
+
* - **Within objects**: byte-equality only (still
|
|
182
|
+
* `JSON.stringify`-insertion-order dependent).
|
|
183
|
+
*
|
|
184
|
+
* Numbers ARE range-safe under this encoder — `9` sorts below `10`
|
|
185
|
+
* as expected. The query planner's old
|
|
186
|
+
* `numeric-range-on-byte-encoder` guard has been removed; range
|
|
187
|
+
* walks and `$in` walks over numeric fields are routed normally.
|
|
188
|
+
*
|
|
189
|
+
* `NaN` throws `BaerlyError{code:"SchemaError"}` at write time —
|
|
190
|
+
* the byte encoding has no order-preserving slot for it, and a
|
|
191
|
+
* silent collapse to the `null` key (as the prior
|
|
192
|
+
* `JSON.stringify`-based encoder did, since
|
|
193
|
+
* `JSON.stringify(NaN) === "null"`) is a worse failure mode than
|
|
194
|
+
* a loud reject.
|
|
195
|
+
*
|
|
196
|
+
* `-0` and `+0` collapse to the same encoding.
|
|
197
|
+
*
|
|
198
|
+
* Equal-by-value inputs (e.g. two `{a:1, b:2}` objects with the
|
|
199
|
+
* same key insertion order) produce byte-equal segments;
|
|
200
|
+
* structurally-different but visually-similar inputs (`"5"` vs `5`)
|
|
201
|
+
* are kept apart by the type-tag prefix.
|
|
202
|
+
*
|
|
203
|
+
* String ranges remain safe: `"2026-05-13" < "2026-05-14"`
|
|
204
|
+
* byte-wise matches semantic order. ISO 8601 timestamps,
|
|
205
|
+
* alphabetical priorities like `"p1"/"p2"/"p3"`, and any
|
|
206
|
+
* fixed-width string encoding are usable as range-walked indexed
|
|
207
|
+
* fields.
|
|
208
|
+
*/
|
|
209
|
+
const encodeIndexValue = (v) => {
|
|
210
|
+
const bytes = encodeBytes(v);
|
|
211
|
+
let out = "";
|
|
212
|
+
let bits = 0;
|
|
213
|
+
let value = 0;
|
|
214
|
+
for (const b of bytes) {
|
|
215
|
+
value = value << 8 | b;
|
|
216
|
+
bits += 8;
|
|
217
|
+
while (bits >= 5) {
|
|
218
|
+
bits -= 5;
|
|
219
|
+
out += B32_ALPHABET[value >> bits & 31];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (bits > 0) out += B32_ALPHABET[value << 5 - bits & 31];
|
|
223
|
+
return out;
|
|
224
|
+
};
|
|
225
|
+
/**
|
|
226
|
+
* Storage `list(prefix)` boundary for every entry under one index
|
|
227
|
+
* of a collection: `<logPrefix>/index/<name>/`. Used by the rebuild
|
|
228
|
+
* command's reconciliation walk and by the read-path index hint.
|
|
229
|
+
*/
|
|
230
|
+
const indexKeyPrefix = (logPrefix, indexName) => `${logPrefix}/index/${indexName}/`;
|
|
231
|
+
/**
|
|
232
|
+
* Build the per-doc index key for one `(def, values, docId)`.
|
|
233
|
+
*
|
|
234
|
+
* Single-field: `<logPrefix>/index/<name>/<v0-b32>/<docId>.json`.
|
|
235
|
+
* Composite: `<logPrefix>/index/<name>/<v0-b32>/<v1-b32>/.../<docId>.json`.
|
|
236
|
+
*
|
|
237
|
+
* Composite shape is accepted but the read path today only
|
|
238
|
+
* consults single-field entries.
|
|
239
|
+
*/
|
|
240
|
+
const indexKeyFor = (logPrefix, def, values, docId) => {
|
|
241
|
+
const segments = values.map(encodeIndexValue).join("/");
|
|
242
|
+
return `${logPrefix}/index/${def.name}/${segments}/${docId}.json`;
|
|
243
|
+
};
|
|
244
|
+
/**
|
|
245
|
+
* Project the value tuple a doc body produces under one index
|
|
246
|
+
* definition. Returns `undefined` when any indexed field is
|
|
247
|
+
* null / undefined / missing — no index entry for that doc under
|
|
248
|
+
* that index (SQL "NULL values don't enter the index" semantics).
|
|
249
|
+
*
|
|
250
|
+
* @throws BaerlyError code="SchemaError" — `on` contains a dotted
|
|
251
|
+
* path, or the indexed field's value is an array. Both restrictions
|
|
252
|
+
* are pre-launch; multi-value (array) indexes are a follow-up.
|
|
253
|
+
*/
|
|
254
|
+
const projectIndexValues = (def, body) => {
|
|
255
|
+
if (body === void 0) return;
|
|
256
|
+
const fields = typeof def.on === "string" ? [def.on] : def.on;
|
|
257
|
+
const values = [];
|
|
258
|
+
for (const field of fields) {
|
|
259
|
+
if (field.includes(".")) throw new BaerlyError("SchemaError", `index ${def.name}: dotted-path "on" fields not yet supported (got ${JSON.stringify(field)})`);
|
|
260
|
+
const v = body[field];
|
|
261
|
+
if (v === null || v === void 0) return;
|
|
262
|
+
if (Array.isArray(v)) throw new BaerlyError("SchemaError", `index ${def.name}: cannot index array field "${field}" — multi-value indexes are not supported yet`);
|
|
263
|
+
values.push(v);
|
|
264
|
+
}
|
|
265
|
+
return values;
|
|
266
|
+
};
|
|
267
|
+
/**
|
|
268
|
+
* Compute the full index-key set a single doc produces under every
|
|
269
|
+
* declared index of its collection. Skips indexes whose projection
|
|
270
|
+
* yields `undefined` (null/missing indexed field). Used by both
|
|
271
|
+
* the writer (to PUT new keys) and the rebuild command (to compute
|
|
272
|
+
* the expected key set across the live doc map).
|
|
273
|
+
*
|
|
274
|
+
* Filter-aware (T4): when `def.predicate !== undefined`, the doc
|
|
275
|
+
* must satisfy `matchesWire(def.predicate, body)` or the def contributes
|
|
276
|
+
* zero keys. The writer's diff `oldKeys` vs `newKeys` then covers
|
|
277
|
+
* all four U-quadrants automatically — see the JSDoc on
|
|
278
|
+
* `writer.ts` above the index-emission block. `body ===
|
|
279
|
+
* undefined` short-circuits ahead of the filter check (no keys for
|
|
280
|
+
* an unknown pre-image, regardless of filter), preserving the prior
|
|
281
|
+
* D-quadrant behaviour.
|
|
282
|
+
*/
|
|
283
|
+
const allIndexKeysFor = (logPrefix, defs, body, docId) => {
|
|
284
|
+
const keys = [];
|
|
285
|
+
for (const def of defs) {
|
|
286
|
+
if (def.predicate !== void 0 && body !== void 0) {
|
|
287
|
+
if (!matchesWire(def.predicate, body)) continue;
|
|
288
|
+
}
|
|
289
|
+
const values = projectIndexValues(def, body);
|
|
290
|
+
if (values !== void 0) keys.push(indexKeyFor(logPrefix, def, values, docId));
|
|
291
|
+
}
|
|
292
|
+
return keys;
|
|
293
|
+
};
|
|
294
|
+
//#endregion
|
|
295
|
+
export { indexKeyPrefix as n, validateIndexDefinition as r, allIndexKeysFor as t };
|
|
296
|
+
|
|
297
|
+
//# sourceMappingURL=indexes-BXn7a06a.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexes-BXn7a06a.js","names":[],"sources":["../packages/server/src/indexes.ts"],"sourcesContent":["/**\n * Secondary indexes — declarative collection-config-driven\n * index entries that the writer emits inside the same CAS fence as\n * the log entry and content body.\n *\n * The {@link IndexDefinition} TYPE lives in `@baerly/protocol`\n * (cross-platform). This module owns the runtime helpers that\n * operate on that shape:\n *\n * - {@link validateIndexDefinition} — synchronous schema check\n * for path-segment safety; thrown at `Writer` construction.\n * - {@link encodeIndexValue} — value-order-preserving base-32 of a\n * type-tagged byte stream (null/bool tag-only, numbers as sortable\n * IEEE 754, strings as raw UTF-8, objects as `JSON.stringify`\n * bytes for equality only).\n * - {@link indexKeyFor} / {@link indexKeyPrefix} — the wire-key\n * shape consumed by the writer's index PUTs and the rebuild\n * command's idempotent reconciliation.\n * - {@link projectIndexValues} / {@link allIndexKeysFor} — pure\n * projections from a doc body to the set of index keys it\n * produces under a collection's declared indexes.\n *\n * Wire shape (single-field):\n *\n * `<logPrefix>/index/<indexName>/<value-b32>/<docId>.json`\n *\n * Wire shape (composite — accepted by the encoder, not consulted by\n * the read path today):\n *\n * `<logPrefix>/index/<indexName>/<a-b32>/<b-b32>/<docId>.json`\n *\n * Body is zero bytes. Each entry is a fact (\"doc `<docId>` has\n * `<field> = <value>`\"), not data. Readers list the prefix, extract\n * the doc id from each key, then issue a content GET on each.\n *\n * Encoding is RFC-4648 base-32 (lowercase alphabet `[0-9a-v]`,\n * matching `packages/protocol/src/log.ts:str2uintDesc` style) on a\n * type-tagged byte stream (see {@link encodeIndexValue}) so that:\n *\n * - String \"5\" and number 5 produce distinct encodings\n * (type-tag prefix keeps the slots disjoint).\n * - Equal-by-value inputs produce byte-equal segments.\n * - Lex order under storage `list(prefix)` matches value order:\n * `null < false < true < number < string < object`, with\n * numeric values ordered by IEEE 754 magnitude (range walks\n * and `$in` walks over numeric fields are first-class — no\n * planner fall-back to full-scan).\n *\n * Locked: single-field indexes only on the read path. Composite\n * shape is documented and reserved (the path encoder accepts it).\n *\n * @see docs/spec/sync-protocol.md — fence model these PUTs land\n * inside (between log PUT and `current.json` CAS-advance).\n */\n\nimport {\n BaerlyError,\n type DocumentData,\n encodeJsonBytes,\n type IndexDefinition,\n matchesWire,\n validateWire,\n} from \"@baerly/protocol\";\n\nexport type { IndexDefinition };\n\n/** Path-safe segment name. */\nconst INDEX_NAME_RE = /^[a-z_][a-z0-9_]*$/;\n\n/**\n * Lowercase base-32 alphabet, RFC 4648 variant matching the\n * `packages/protocol/src/log.ts:str2uintDesc` style (`[0-9a-v]`).\n * Lex-order-preserving under storage `list(prefix)` semantics.\n */\nconst B32_ALPHABET = \"0123456789abcdefghijklmnopqrstuv\";\n\n/**\n * Reject malformed {@link IndexDefinition} shapes synchronously.\n * Thrown at writer construction so a config typo trips before any\n * write lands.\n *\n * @throws BaerlyError code=\"SchemaError\" — `name` doesn't match\n * `/^[a-z_][a-z0-9_]*$/`; `on` is the empty string or empty\n * array.\n */\nexport const validateIndexDefinition = (def: IndexDefinition): void => {\n if (!INDEX_NAME_RE.test(def.name)) {\n throw new BaerlyError(\n \"SchemaError\",\n `index.name must match /^[a-z_][a-z0-9_]*$/; got ${JSON.stringify(def.name)}`,\n );\n }\n if (typeof def.on === \"string\") {\n if (def.on.length === 0) {\n throw new BaerlyError(\"SchemaError\", `index ${def.name}.on must be non-empty`);\n }\n } else if (def.on.length === 0) {\n throw new BaerlyError(\"SchemaError\", `index ${def.name}.on must be non-empty array`);\n }\n if (def.predicate !== undefined) {\n try {\n validateWire(def.predicate);\n } catch (error) {\n // Surface as SchemaError so the failure mode matches the rest\n // of validateIndexDefinition (writer-construction-time bail-out,\n // not query-time).\n if (error instanceof BaerlyError) {\n throw new BaerlyError(\n \"SchemaError\",\n `index ${def.name}.predicate is invalid: ${error.message}`,\n error,\n );\n }\n throw error;\n }\n }\n};\n\n/**\n * Type-tag bytes for the value-order-preserving wire format. The\n * tag is the LEADING byte of the encoded payload; the values are\n * picked so the type order under byte-wise lex is\n * `null < false < true < number < string < object`.\n *\n * | Type | Byte-prefix | Payload |\n * |---------|-------------|----------------------------------------------------|\n * | null | 0x10 | (none) |\n * | false | 0x20 | (none) |\n * | true | 0x21 | (none) |\n * | number | 0x30 | 8-byte sortable big-endian IEEE 754 |\n * | string | 0x40 | UTF-8 bytes of the string (no quotes, no escapes) |\n * | object | 0x50 | UTF-8 bytes of `JSON.stringify(v)` |\n *\n * Local to the encoder by design — these are wire shape, not\n * cross-package protocol constants (see `CLAUDE.md` § \"Magic\n * values\").\n */\nconst TYPE_NULL = 0x10;\nconst TYPE_FALSE = 0x20;\nconst TYPE_TRUE = 0x21;\nconst TYPE_NUMBER = 0x30;\nconst TYPE_STRING = 0x40;\nconst TYPE_OBJECT = 0x50;\n\n/**\n * Encode a JS double as an 8-byte big-endian sortable IEEE 754\n * payload. Byte-wise lex order on the result matches numeric order\n * across all finite doubles plus `±Infinity`:\n *\n * 1. Get the 8-byte big-endian view of the double.\n * 2. If the sign bit is `0` (zero or positive), flip the sign bit\n * (XOR `0x80` on byte 0) so positives sort above negatives.\n * 3. If the sign bit is `1` (negative), flip every bit in all 8\n * bytes so more-negative sorts lower.\n *\n * `NaN` has no order-preserving slot and is rejected — see the\n * `encodeIndexValue` JSDoc for the wire-contract rationale.\n * `-0` and `+0` collapse because the `n === 0 ? 0 : n` coercion below\n * forces both into the positive-zero branch before `setFloat64`.\n */\nconst encodeNumberPayload = (n: number): Uint8Array => {\n if (Number.isNaN(n)) {\n throw new BaerlyError(\n \"SchemaError\",\n `encodeIndexValue: NaN is not indexable (the byte encoding has no order-preserving slot for it)`,\n );\n }\n // Coerce `-0` to `+0` so both share the positive-zero serialisation\n // (`setFloat64(-0)` would produce `0x80 00...00` and take the\n // negative-branch all-bits-flip below, collapsing to a *different*\n // byte string than `+0`). Coercing up front keeps the wire stable.\n const buf = new ArrayBuffer(8);\n new DataView(buf).setFloat64(0, n === 0 ? 0 : n, false); // big-endian\n const bytes = new Uint8Array(buf);\n if ((bytes[0]! & 0x80) === 0) {\n // Positive (or +0): flip sign bit so positives sort above negatives.\n bytes[0] = bytes[0]! ^ 0x80;\n } else {\n // Negative: flip all bits so more-negative sorts lower.\n for (let i = 0; i < 8; i++) {\n bytes[i] = bytes[i]! ^ 0xff;\n }\n }\n return bytes;\n};\n\n/**\n * Compose the typed byte stream for one value. The leading byte is\n * the type tag (see {@link TYPE_NULL} et al.); the payload shape is\n * type-dependent. Strings are emitted as their raw UTF-8 bytes (no\n * JSON quoting / escaping) so byte-wise lex order on encoded strings\n * matches byte-wise lex order on the source UTF-8. Objects fall back\n * to `JSON.stringify` for equality only.\n */\nconst encodeBytes = (v: unknown): Uint8Array => {\n if (v === null || v === undefined) {\n return new Uint8Array([TYPE_NULL]);\n }\n if (v === false) {\n return new Uint8Array([TYPE_FALSE]);\n }\n if (v === true) {\n return new Uint8Array([TYPE_TRUE]);\n }\n if (typeof v === \"number\") {\n const payload = encodeNumberPayload(v);\n const out = new Uint8Array(1 + payload.length);\n out[0] = TYPE_NUMBER;\n out.set(payload, 1);\n return out;\n }\n if (typeof v === \"string\") {\n const utf8 = new TextEncoder().encode(v);\n const out = new Uint8Array(1 + utf8.length);\n out[0] = TYPE_STRING;\n out.set(utf8, 1);\n return out;\n }\n // Objects: equality only; insertion-order dependent (matches today's\n // contract on `JSON.stringify`-based equality).\n const utf8 = encodeJsonBytes(v);\n const out = new Uint8Array(1 + utf8.length);\n out[0] = TYPE_OBJECT;\n out.set(utf8, 1);\n return out;\n};\n\n/**\n * Encode an arbitrary `DocumentValue` value as a path-safe segment.\n *\n * Type-tagged byte stream, base-32-encoded for path safety. Lex\n * order on encoded bytes matches:\n *\n * - **Type order**: `null < false < true < number < string < object`.\n * - **Within numbers**: IEEE 754 numeric order (sortable\n * big-endian payload, sign-bit-flipped or all-bits-flipped).\n * `-Infinity` sorts lowest, `+Infinity` highest.\n * - **Within strings**: UTF-8 byte order.\n * - **Within objects**: byte-equality only (still\n * `JSON.stringify`-insertion-order dependent).\n *\n * Numbers ARE range-safe under this encoder — `9` sorts below `10`\n * as expected. The query planner's old\n * `numeric-range-on-byte-encoder` guard has been removed; range\n * walks and `$in` walks over numeric fields are routed normally.\n *\n * `NaN` throws `BaerlyError{code:\"SchemaError\"}` at write time —\n * the byte encoding has no order-preserving slot for it, and a\n * silent collapse to the `null` key (as the prior\n * `JSON.stringify`-based encoder did, since\n * `JSON.stringify(NaN) === \"null\"`) is a worse failure mode than\n * a loud reject.\n *\n * `-0` and `+0` collapse to the same encoding.\n *\n * Equal-by-value inputs (e.g. two `{a:1, b:2}` objects with the\n * same key insertion order) produce byte-equal segments;\n * structurally-different but visually-similar inputs (`\"5\"` vs `5`)\n * are kept apart by the type-tag prefix.\n *\n * String ranges remain safe: `\"2026-05-13\" < \"2026-05-14\"`\n * byte-wise matches semantic order. ISO 8601 timestamps,\n * alphabetical priorities like `\"p1\"/\"p2\"/\"p3\"`, and any\n * fixed-width string encoding are usable as range-walked indexed\n * fields.\n */\nexport const encodeIndexValue = (v: unknown): string => {\n const bytes = encodeBytes(v);\n let out = \"\";\n let bits = 0;\n let value = 0;\n for (const b of bytes) {\n value = (value << 8) | b;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out += B32_ALPHABET[(value >> bits) & 0x1f];\n }\n }\n if (bits > 0) {\n out += B32_ALPHABET[(value << (5 - bits)) & 0x1f];\n }\n // The type-prefix guarantees the byte stream is non-empty for every\n // input, so the \"empty → '0'\" fallback that the old encoder needed\n // is dead. Encoder output is always non-empty under the new contract.\n return out;\n};\n\n/**\n * Storage `list(prefix)` boundary for every entry under one index\n * of a collection: `<logPrefix>/index/<name>/`. Used by the rebuild\n * command's reconciliation walk and by the read-path index hint.\n */\nexport const indexKeyPrefix = (logPrefix: string, indexName: string): string =>\n `${logPrefix}/index/${indexName}/`;\n\n/**\n * Build the per-doc index key for one `(def, values, docId)`.\n *\n * Single-field: `<logPrefix>/index/<name>/<v0-b32>/<docId>.json`.\n * Composite: `<logPrefix>/index/<name>/<v0-b32>/<v1-b32>/.../<docId>.json`.\n *\n * Composite shape is accepted but the read path today only\n * consults single-field entries.\n */\nexport const indexKeyFor = (\n logPrefix: string,\n def: IndexDefinition,\n values: readonly unknown[],\n docId: string,\n): string => {\n const segments = values.map(encodeIndexValue).join(\"/\");\n return `${logPrefix}/index/${def.name}/${segments}/${docId}.json`;\n};\n\n/**\n * Project the value tuple a doc body produces under one index\n * definition. Returns `undefined` when any indexed field is\n * null / undefined / missing — no index entry for that doc under\n * that index (SQL \"NULL values don't enter the index\" semantics).\n *\n * @throws BaerlyError code=\"SchemaError\" — `on` contains a dotted\n * path, or the indexed field's value is an array. Both restrictions\n * are pre-launch; multi-value (array) indexes are a follow-up.\n */\nexport const projectIndexValues = (\n def: IndexDefinition,\n body: DocumentData | undefined,\n): readonly unknown[] | undefined => {\n if (body === undefined) {\n return undefined;\n }\n const fields = typeof def.on === \"string\" ? [def.on] : def.on;\n const values: unknown[] = [];\n for (const field of fields) {\n // Today we only support top-level fields. Dotted paths land in\n // a follow-up; throw loudly so a config typo doesn't silently\n // produce empty values.\n if (field.includes(\".\")) {\n throw new BaerlyError(\n \"SchemaError\",\n `index ${def.name}: dotted-path \"on\" fields not yet supported (got ${JSON.stringify(field)})`,\n );\n }\n const v = body[field];\n // null/undefined are skipped — no index entry. Mirrors SQL\n // \"NULL values don't go into a regular index\" semantics.\n if (v === null || v === undefined) {\n return undefined;\n }\n // Array values are valid in documents (RFC 7396 replacement\n // semantics) but multi-value indexes aren't supported yet — the\n // prefix-tree encoder produces one key per doc, not one per\n // element. Throw loudly so a user indexing a tag list gets a\n // clear error instead of garbage keys.\n if (Array.isArray(v)) {\n throw new BaerlyError(\n \"SchemaError\",\n `index ${def.name}: cannot index array field \"${field}\" — multi-value indexes are not supported yet`,\n );\n }\n values.push(v);\n }\n return values;\n};\n\n/**\n * Compute the full index-key set a single doc produces under every\n * declared index of its collection. Skips indexes whose projection\n * yields `undefined` (null/missing indexed field). Used by both\n * the writer (to PUT new keys) and the rebuild command (to compute\n * the expected key set across the live doc map).\n *\n * Filter-aware (T4): when `def.predicate !== undefined`, the doc\n * must satisfy `matchesWire(def.predicate, body)` or the def contributes\n * zero keys. The writer's diff `oldKeys` vs `newKeys` then covers\n * all four U-quadrants automatically — see the JSDoc on\n * `writer.ts` above the index-emission block. `body ===\n * undefined` short-circuits ahead of the filter check (no keys for\n * an unknown pre-image, regardless of filter), preserving the prior\n * D-quadrant behaviour.\n */\nexport const allIndexKeysFor = (\n logPrefix: string,\n defs: ReadonlyArray<IndexDefinition>,\n body: DocumentData | undefined,\n docId: string,\n): string[] => {\n const keys: string[] = [];\n for (const def of defs) {\n if (def.predicate !== undefined && body !== undefined) {\n if (!matchesWire(def.predicate, body)) {\n continue;\n }\n }\n const values = projectIndexValues(def, body);\n if (values !== undefined) {\n keys.push(indexKeyFor(logPrefix, def, values, docId));\n }\n }\n return keys;\n};\n"],"mappings":"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"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { d as IndexDefinition, f as DocumentData } from "./app-config-Cb5dO2s9.js";
|
|
2
|
+
//#region packages/server/src/indexes.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Compute the full index-key set a single doc produces under every
|
|
5
|
+
* declared index of its collection. Skips indexes whose projection
|
|
6
|
+
* yields `undefined` (null/missing indexed field). Used by both
|
|
7
|
+
* the writer (to PUT new keys) and the rebuild command (to compute
|
|
8
|
+
* the expected key set across the live doc map).
|
|
9
|
+
*
|
|
10
|
+
* Filter-aware (T4): when `def.predicate !== undefined`, the doc
|
|
11
|
+
* must satisfy `matchesWire(def.predicate, body)` or the def contributes
|
|
12
|
+
* zero keys. The writer's diff `oldKeys` vs `newKeys` then covers
|
|
13
|
+
* all four U-quadrants automatically — see the JSDoc on
|
|
14
|
+
* `writer.ts` above the index-emission block. `body ===
|
|
15
|
+
* undefined` short-circuits ahead of the filter check (no keys for
|
|
16
|
+
* an unknown pre-image, regardless of filter), preserving the prior
|
|
17
|
+
* D-quadrant behaviour.
|
|
18
|
+
*/
|
|
19
|
+
declare const allIndexKeysFor: (logPrefix: string, defs: ReadonlyArray<IndexDefinition>, body: DocumentData | undefined, docId: string) => string[];
|
|
20
|
+
//#endregion
|
|
21
|
+
export { allIndexKeysFor as t };
|
|
22
|
+
//# sourceMappingURL=indexes-DwOXkn1Y.d.ts.map
|