@noy-db/to-drive 0.1.0-pre.3
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/LICENSE +21 -0
- package/README.md +33 -0
- package/dist/index.cjs +142 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +132 -0
- package/dist/index.d.ts +132 -0
- package/dist/index.js +115 -0
- package/dist/index.js.map +1 -0
- package/package.json +67 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 vLannaAi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# @noy-db/to-drive
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@noy-db/to-drive)
|
|
4
|
+
|
|
5
|
+
> Google Drive bundle store for noy-db. Stores the whole vault as a single .noydb file in Drive's hidden appDataFolder; opaque ULID filenames never leak compartment names. Driver-agnostic
|
|
6
|
+
|
|
7
|
+
Part of [**`@noy-db/hub`**](https://www.npmjs.com/package/@noy-db/hub) — the zero-knowledge, offline-first, encrypted document store.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pnpm add @noy-db/hub @noy-db/to-drive
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## What it is
|
|
16
|
+
|
|
17
|
+
Google Drive bundle store for noy-db. Stores the whole vault as a single .noydb file in Drive's hidden appDataFolder; opaque ULID filenames never leak compartment names. Driver-agnostic — bring your own OAuth token.
|
|
18
|
+
|
|
19
|
+
## Status
|
|
20
|
+
|
|
21
|
+
**Pre-release** (`0.1.0-pre.1`). API may change before `1.0`.
|
|
22
|
+
|
|
23
|
+
## Documentation
|
|
24
|
+
|
|
25
|
+
See the [main repository](https://github.com/vLannaAi/noy-db#readme) for setup, examples, and the full subsystem catalog.
|
|
26
|
+
|
|
27
|
+
- Source — [`packages/to-drive`](https://github.com/vLannaAi/noy-db/tree/main/packages/to-drive)
|
|
28
|
+
- Issues — [github.com/vLannaAi/noy-db/issues](https://github.com/vLannaAi/noy-db/issues)
|
|
29
|
+
- Spec — [`SPEC.md`](https://github.com/vLannaAi/noy-db/blob/main/SPEC.md)
|
|
30
|
+
|
|
31
|
+
## License
|
|
32
|
+
|
|
33
|
+
[MIT](./LICENSE) © vLannaAi
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
drive: () => drive,
|
|
24
|
+
memoryHandleStore: () => memoryHandleStore,
|
|
25
|
+
newUlid: () => newUlid
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(index_exports);
|
|
28
|
+
var import_hub = require("@noy-db/hub");
|
|
29
|
+
function memoryHandleStore() {
|
|
30
|
+
const map = /* @__PURE__ */ new Map();
|
|
31
|
+
return {
|
|
32
|
+
async getHandle(vaultId) {
|
|
33
|
+
return map.get(vaultId) ?? null;
|
|
34
|
+
},
|
|
35
|
+
async setHandle(vaultId, handle) {
|
|
36
|
+
map.set(vaultId, handle);
|
|
37
|
+
},
|
|
38
|
+
async deleteHandle(vaultId) {
|
|
39
|
+
map.delete(vaultId);
|
|
40
|
+
},
|
|
41
|
+
async listHandles() {
|
|
42
|
+
return [...map.entries()].map(([vaultId, handle]) => ({ vaultId, handle }));
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
var ULID_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
47
|
+
function newUlid() {
|
|
48
|
+
const time = Date.now();
|
|
49
|
+
let timePart = "";
|
|
50
|
+
let t = time;
|
|
51
|
+
for (let i = 0; i < 10; i++) {
|
|
52
|
+
timePart = ULID_ALPHABET[t % 32] + timePart;
|
|
53
|
+
t = Math.floor(t / 32);
|
|
54
|
+
}
|
|
55
|
+
const rand = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
56
|
+
let randPart = "";
|
|
57
|
+
for (const byte of rand) {
|
|
58
|
+
randPart += ULID_ALPHABET[byte % 32];
|
|
59
|
+
}
|
|
60
|
+
return timePart + randPart;
|
|
61
|
+
}
|
|
62
|
+
var APP_DATA_FOLDER = "appDataFolder";
|
|
63
|
+
var DEFAULT_MIME = "application/octet-stream";
|
|
64
|
+
function drive(options) {
|
|
65
|
+
const parentId = options.parentId ?? APP_DATA_FOLDER;
|
|
66
|
+
const handles = options.handles ?? memoryHandleStore();
|
|
67
|
+
const suffix = options.suffix ?? ".noydb";
|
|
68
|
+
const { drive: client } = options;
|
|
69
|
+
async function handleFor(vaultId) {
|
|
70
|
+
return handles.getHandle(vaultId);
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
kind: "bundle",
|
|
74
|
+
name: "google-drive",
|
|
75
|
+
async readBundle(vaultId) {
|
|
76
|
+
const handle = await handleFor(vaultId);
|
|
77
|
+
if (!handle) return null;
|
|
78
|
+
const meta = await client.getFileMetadata(handle.fileId);
|
|
79
|
+
if (!meta) {
|
|
80
|
+
await handles.deleteHandle(vaultId);
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
const bytes = await client.getFileBytes(handle.fileId);
|
|
84
|
+
if (!bytes) return null;
|
|
85
|
+
return { bytes, version: meta.headRevisionId };
|
|
86
|
+
},
|
|
87
|
+
async writeBundle(vaultId, bytes, expectedVersion) {
|
|
88
|
+
const handle = await handleFor(vaultId);
|
|
89
|
+
if (!handle) {
|
|
90
|
+
if (expectedVersion !== null) {
|
|
91
|
+
throw new import_hub.BundleVersionConflictError(
|
|
92
|
+
`No existing bundle for vault "${vaultId}" but expectedVersion="${expectedVersion}" was supplied.`
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
const name = `${newUlid()}${suffix}`;
|
|
96
|
+
const meta2 = await client.createFile({
|
|
97
|
+
name,
|
|
98
|
+
bytes,
|
|
99
|
+
parents: [parentId],
|
|
100
|
+
mimeType: DEFAULT_MIME
|
|
101
|
+
});
|
|
102
|
+
await handles.setHandle(vaultId, { fileId: meta2.id, name: meta2.name });
|
|
103
|
+
return { version: meta2.headRevisionId };
|
|
104
|
+
}
|
|
105
|
+
const meta = await client.updateFile(handle.fileId, {
|
|
106
|
+
bytes,
|
|
107
|
+
expectedRevision: expectedVersion
|
|
108
|
+
});
|
|
109
|
+
return { version: meta.headRevisionId };
|
|
110
|
+
},
|
|
111
|
+
async deleteBundle(vaultId) {
|
|
112
|
+
const handle = await handleFor(vaultId);
|
|
113
|
+
if (!handle) return;
|
|
114
|
+
try {
|
|
115
|
+
await client.deleteFile(handle.fileId);
|
|
116
|
+
} catch {
|
|
117
|
+
}
|
|
118
|
+
await handles.deleteHandle(vaultId);
|
|
119
|
+
},
|
|
120
|
+
async listBundles() {
|
|
121
|
+
if (handles.listHandles) {
|
|
122
|
+
const known = await handles.listHandles();
|
|
123
|
+
const out = [];
|
|
124
|
+
for (const { vaultId, handle } of known) {
|
|
125
|
+
const meta = await client.getFileMetadata(handle.fileId);
|
|
126
|
+
if (!meta) continue;
|
|
127
|
+
out.push({ vaultId, version: meta.headRevisionId, size: meta.size });
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
const files = await client.listFiles({ parents: [parentId], mimeType: DEFAULT_MIME });
|
|
132
|
+
return files.filter((f) => f.name.endsWith(suffix)).map((f) => ({ vaultId: f.name.slice(0, -suffix.length), version: f.headRevisionId, size: f.size }));
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
137
|
+
0 && (module.exports = {
|
|
138
|
+
drive,
|
|
139
|
+
memoryHandleStore,
|
|
140
|
+
newUlid
|
|
141
|
+
});
|
|
142
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/to-drive** — Google Drive bundle store for noy-db.\n *\n * Stores each vault as a single `.noydb` bundle in Drive. Implements\n * the `NoydbBundleStore` contract (read/write/delete/list whole-bundle);\n * wrap with `wrapBundleStore()` from `@noy-db/hub` to get the standard\n * six-method `NoydbStore` surface.\n *\n * ## Privacy posture\n *\n * - **ULID filenames** — `01HXG4F5ZK7…noydb`, never `acme.noydb`.\n * Drive folder listings are visible to share recipients, Workspace\n * admins on managed accounts, and Google's internal search index.\n * Naming the file after the vault leaks client identity to all of\n * those. ULIDs give a sortable, collision-free alternative that\n * discloses nothing.\n * - **`appDataFolder` by default** — a hidden Drive folder that does\n * NOT show in the Drive UI and is scoped to the installed app only.\n * Opt in to a user-visible folder for \"restore from Drive\" UX.\n * - **`drive.file` scope** — the OAuth token can only see files this\n * app created. No read access to the user's other Drive contents.\n * - **No custom properties** — Drive allows arbitrary key/value\n * metadata on files. This adapter writes nothing there. Every piece\n * of vault metadata lives inside the encrypted body.\n *\n * ## Driver — bring your own\n *\n * noy-db does NOT pull `googleapis` (or any Google SDK) as a runtime\n * dependency. The consumer wires their preferred client (`googleapis`,\n * `gapi-client-ts`, a bespoke `fetch` wrapper) and passes a duck-typed\n * `DriveClient` in. Every OAuth refresh concern stays outside this\n * package.\n *\n * ## Handle registry\n *\n * Drive's API identifies files by `fileId`, not filename. To resolve\n * \"give me the bundle for vault ACME,\" the store needs to remember\n * which fileId corresponds to which vault. Two options:\n *\n * 1. **Consumer-persisted** — pass a `HandleStore` that implements\n * `getHandle(vaultId)` / `setHandle(vaultId, handle)`. Typical\n * implementations: localStorage in browsers, the vault's\n * `_sync_credentials` collection, or a JSON file on disk.\n * 2. **Drive-lookup** (default) — when no handle is cached, issue a\n * `files.list` call filtering by the ULID-encoded vaultId hash.\n * Slower but requires no extra plumbing.\n *\n * @packageDocumentation\n */\n\nimport type { NoydbBundleStore } from '@noy-db/hub'\nimport { BundleVersionConflictError } from '@noy-db/hub'\n\n// ── Duck-typed Drive client ──────────────────────────────────────────────\n\n/**\n * Minimal shape the store needs from a Google Drive client. Every\n * production Drive wrapper (`googleapis`, `gapi`, hand-rolled `fetch`\n * code) can expose this surface with a thin adapter.\n */\nexport interface DriveClient {\n createFile(request: DriveCreateRequest): Promise<DriveFileMeta>\n updateFile(fileId: string, request: DriveUpdateRequest): Promise<DriveFileMeta>\n getFileMetadata(fileId: string): Promise<DriveFileMeta | null>\n getFileBytes(fileId: string): Promise<Uint8Array | null>\n deleteFile(fileId: string): Promise<void>\n listFiles(query: DriveListQuery): Promise<DriveFileMeta[]>\n}\n\nexport interface DriveCreateRequest {\n readonly name: string\n readonly bytes: Uint8Array\n readonly parents: readonly string[]\n readonly mimeType?: string\n}\n\nexport interface DriveUpdateRequest {\n readonly bytes: Uint8Array\n readonly expectedRevision?: string | null\n}\n\nexport interface DriveListQuery {\n readonly parents?: readonly string[]\n readonly namePrefix?: string\n readonly nameExact?: string\n readonly mimeType?: string\n readonly limit?: number\n}\n\nexport interface DriveFileMeta {\n readonly id: string\n readonly name: string\n readonly headRevisionId: string\n readonly size: number\n}\n\n// ── Handle registry ──────────────────────────────────────────────────────\n\nexport interface HandleStore {\n getHandle(vaultId: string): Promise<DriveHandle | null>\n setHandle(vaultId: string, handle: DriveHandle): Promise<void>\n deleteHandle(vaultId: string): Promise<void>\n /** Return every known { vaultId, handle } pair. Used by `listBundles()`. */\n listHandles?(): Promise<Array<{ vaultId: string; handle: DriveHandle }>>\n}\n\nexport interface DriveHandle {\n /** Stable Drive fileId. */\n readonly fileId: string\n /** ULID filename — what lives in Drive. */\n readonly name: string\n}\n\n/**\n * In-memory handle store — fine for short-lived processes and tests.\n * Production consumers should persist handles to localStorage, IDB,\n * or a vault's `_sync_credentials` collection.\n */\nexport function memoryHandleStore(): HandleStore {\n const map = new Map<string, DriveHandle>()\n return {\n async getHandle(vaultId) { return map.get(vaultId) ?? null },\n async setHandle(vaultId, handle) { map.set(vaultId, handle) },\n async deleteHandle(vaultId) { map.delete(vaultId) },\n async listHandles() {\n return [...map.entries()].map(([vaultId, handle]) => ({ vaultId, handle }))\n },\n }\n}\n\n// ── ULID generator (minimal, copy-free) ───────────────────────────────────\n\nconst ULID_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\n/**\n * Generate a new ULID — 26 characters: 10 chars of timestamp (ms\n * granularity, sortable lexically when generated ≥ 1 ms apart) plus\n * 16 chars of entropy (80 bits).\n */\nexport function newUlid(): string {\n const time = Date.now()\n let timePart = ''\n let t = time\n for (let i = 0; i < 10; i++) {\n timePart = ULID_ALPHABET[t % 32]! + timePart\n t = Math.floor(t / 32)\n }\n // 16 chars of random → 16 bytes. 256 is a multiple of 32 so `byte % 32`\n // produces a uniform distribution over the alphabet.\n const rand = globalThis.crypto.getRandomValues(new Uint8Array(16))\n let randPart = ''\n for (const byte of rand) {\n randPart += ULID_ALPHABET[byte % 32]\n }\n return timePart + randPart\n}\n\n// ── Options + factory ────────────────────────────────────────────────────\n\nexport interface DriveStoreOptions {\n readonly drive: DriveClient\n /**\n * Parent folder id. Defaults to Drive's `appDataFolder` — hidden from\n * the user, scoped to the app. Pass an explicit id to use a\n * user-visible folder.\n */\n readonly parentId?: string\n /** Handle registry — memory by default. Persist yourself in prod. */\n readonly handles?: HandleStore\n /** Bundle filename suffix. Default `'.noydb'`. */\n readonly suffix?: string\n}\n\nconst APP_DATA_FOLDER = 'appDataFolder'\nconst DEFAULT_MIME = 'application/octet-stream'\n\nexport function drive(options: DriveStoreOptions): NoydbBundleStore {\n const parentId = options.parentId ?? APP_DATA_FOLDER\n const handles = options.handles ?? memoryHandleStore()\n const suffix = options.suffix ?? '.noydb'\n const { drive: client } = options\n\n async function handleFor(vaultId: string): Promise<DriveHandle | null> {\n return handles.getHandle(vaultId)\n }\n\n return {\n kind: 'bundle',\n name: 'google-drive',\n\n async readBundle(vaultId) {\n const handle = await handleFor(vaultId)\n if (!handle) return null\n\n const meta = await client.getFileMetadata(handle.fileId)\n if (!meta) {\n // Out-of-band deletion — clear the cached handle.\n await handles.deleteHandle(vaultId)\n return null\n }\n const bytes = await client.getFileBytes(handle.fileId)\n if (!bytes) return null\n return { bytes, version: meta.headRevisionId }\n },\n\n async writeBundle(vaultId, bytes, expectedVersion) {\n const handle = await handleFor(vaultId)\n if (!handle) {\n if (expectedVersion !== null) {\n throw new BundleVersionConflictError(\n `No existing bundle for vault \"${vaultId}\" but expectedVersion=\"${expectedVersion}\" was supplied.`,\n )\n }\n const name = `${newUlid()}${suffix}`\n const meta = await client.createFile({\n name,\n bytes,\n parents: [parentId],\n mimeType: DEFAULT_MIME,\n })\n await handles.setHandle(vaultId, { fileId: meta.id, name: meta.name })\n return { version: meta.headRevisionId }\n }\n const meta = await client.updateFile(handle.fileId, {\n bytes,\n expectedRevision: expectedVersion,\n })\n return { version: meta.headRevisionId }\n },\n\n async deleteBundle(vaultId) {\n const handle = await handleFor(vaultId)\n if (!handle) return\n try {\n await client.deleteFile(handle.fileId)\n } catch {\n // Already gone.\n }\n await handles.deleteHandle(vaultId)\n },\n\n async listBundles() {\n if (handles.listHandles) {\n const known = await handles.listHandles()\n const out: Array<{ vaultId: string; version: string; size: number }> = []\n for (const { vaultId, handle } of known) {\n const meta = await client.getFileMetadata(handle.fileId)\n if (!meta) continue\n out.push({ vaultId, version: meta.headRevisionId, size: meta.size })\n }\n return out\n }\n // No handle index: fall back to Drive listing. This returns Drive\n // file ids as \"vault ids\", which is imperfect — consumers are\n // expected to either run a handle store or never call listBundles.\n const files = await client.listFiles({ parents: [parentId], mimeType: DEFAULT_MIME })\n return files\n .filter(f => f.name.endsWith(suffix))\n .map(f => ({ vaultId: f.name.slice(0, -suffix.length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AAAA,MACvC,QAAQ;AAAA,MAER;AACA,YAAM,QAAQ,aAAa,OAAO;AAAA,IACpC;AAAA,IAEA,MAAM,cAAc;AAClB,UAAI,QAAQ,aAAa;AACvB,cAAM,QAAQ,MAAM,QAAQ,YAAY;AACxC,cAAM,MAAiE,CAAC;AACxE,mBAAW,EAAE,SAAS,OAAO,KAAK,OAAO;AACvC,gBAAM,OAAO,MAAM,OAAO,gBAAgB,OAAO,MAAM;AACvD,cAAI,CAAC,KAAM;AACX,cAAI,KAAK,EAAE,SAAS,SAAS,KAAK,gBAAgB,MAAM,KAAK,KAAK,CAAC;AAAA,QACrE;AACA,eAAO;AAAA,MACT;AAIA,YAAM,QAAQ,MAAM,OAAO,UAAU,EAAE,SAAS,CAAC,QAAQ,GAAG,UAAU,aAAa,CAAC;AACpF,aAAO,MACJ,OAAO,OAAK,EAAE,KAAK,SAAS,MAAM,CAAC,EACnC,IAAI,QAAM,EAAE,SAAS,EAAE,KAAK,MAAM,GAAG,CAAC,OAAO,MAAM,GAAG,SAAS,EAAE,gBAAgB,MAAM,EAAE,KAAK,EAAE;AAAA,IACrG;AAAA,EACF;AACF;","names":["meta"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { NoydbBundleStore } from '@noy-db/hub';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* **@noy-db/to-drive** — Google Drive bundle store for noy-db.
|
|
5
|
+
*
|
|
6
|
+
* Stores each vault as a single `.noydb` bundle in Drive. Implements
|
|
7
|
+
* the `NoydbBundleStore` contract (read/write/delete/list whole-bundle);
|
|
8
|
+
* wrap with `wrapBundleStore()` from `@noy-db/hub` to get the standard
|
|
9
|
+
* six-method `NoydbStore` surface.
|
|
10
|
+
*
|
|
11
|
+
* ## Privacy posture
|
|
12
|
+
*
|
|
13
|
+
* - **ULID filenames** — `01HXG4F5ZK7…noydb`, never `acme.noydb`.
|
|
14
|
+
* Drive folder listings are visible to share recipients, Workspace
|
|
15
|
+
* admins on managed accounts, and Google's internal search index.
|
|
16
|
+
* Naming the file after the vault leaks client identity to all of
|
|
17
|
+
* those. ULIDs give a sortable, collision-free alternative that
|
|
18
|
+
* discloses nothing.
|
|
19
|
+
* - **`appDataFolder` by default** — a hidden Drive folder that does
|
|
20
|
+
* NOT show in the Drive UI and is scoped to the installed app only.
|
|
21
|
+
* Opt in to a user-visible folder for "restore from Drive" UX.
|
|
22
|
+
* - **`drive.file` scope** — the OAuth token can only see files this
|
|
23
|
+
* app created. No read access to the user's other Drive contents.
|
|
24
|
+
* - **No custom properties** — Drive allows arbitrary key/value
|
|
25
|
+
* metadata on files. This adapter writes nothing there. Every piece
|
|
26
|
+
* of vault metadata lives inside the encrypted body.
|
|
27
|
+
*
|
|
28
|
+
* ## Driver — bring your own
|
|
29
|
+
*
|
|
30
|
+
* noy-db does NOT pull `googleapis` (or any Google SDK) as a runtime
|
|
31
|
+
* dependency. The consumer wires their preferred client (`googleapis`,
|
|
32
|
+
* `gapi-client-ts`, a bespoke `fetch` wrapper) and passes a duck-typed
|
|
33
|
+
* `DriveClient` in. Every OAuth refresh concern stays outside this
|
|
34
|
+
* package.
|
|
35
|
+
*
|
|
36
|
+
* ## Handle registry
|
|
37
|
+
*
|
|
38
|
+
* Drive's API identifies files by `fileId`, not filename. To resolve
|
|
39
|
+
* "give me the bundle for vault ACME," the store needs to remember
|
|
40
|
+
* which fileId corresponds to which vault. Two options:
|
|
41
|
+
*
|
|
42
|
+
* 1. **Consumer-persisted** — pass a `HandleStore` that implements
|
|
43
|
+
* `getHandle(vaultId)` / `setHandle(vaultId, handle)`. Typical
|
|
44
|
+
* implementations: localStorage in browsers, the vault's
|
|
45
|
+
* `_sync_credentials` collection, or a JSON file on disk.
|
|
46
|
+
* 2. **Drive-lookup** (default) — when no handle is cached, issue a
|
|
47
|
+
* `files.list` call filtering by the ULID-encoded vaultId hash.
|
|
48
|
+
* Slower but requires no extra plumbing.
|
|
49
|
+
*
|
|
50
|
+
* @packageDocumentation
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Minimal shape the store needs from a Google Drive client. Every
|
|
55
|
+
* production Drive wrapper (`googleapis`, `gapi`, hand-rolled `fetch`
|
|
56
|
+
* code) can expose this surface with a thin adapter.
|
|
57
|
+
*/
|
|
58
|
+
interface DriveClient {
|
|
59
|
+
createFile(request: DriveCreateRequest): Promise<DriveFileMeta>;
|
|
60
|
+
updateFile(fileId: string, request: DriveUpdateRequest): Promise<DriveFileMeta>;
|
|
61
|
+
getFileMetadata(fileId: string): Promise<DriveFileMeta | null>;
|
|
62
|
+
getFileBytes(fileId: string): Promise<Uint8Array | null>;
|
|
63
|
+
deleteFile(fileId: string): Promise<void>;
|
|
64
|
+
listFiles(query: DriveListQuery): Promise<DriveFileMeta[]>;
|
|
65
|
+
}
|
|
66
|
+
interface DriveCreateRequest {
|
|
67
|
+
readonly name: string;
|
|
68
|
+
readonly bytes: Uint8Array;
|
|
69
|
+
readonly parents: readonly string[];
|
|
70
|
+
readonly mimeType?: string;
|
|
71
|
+
}
|
|
72
|
+
interface DriveUpdateRequest {
|
|
73
|
+
readonly bytes: Uint8Array;
|
|
74
|
+
readonly expectedRevision?: string | null;
|
|
75
|
+
}
|
|
76
|
+
interface DriveListQuery {
|
|
77
|
+
readonly parents?: readonly string[];
|
|
78
|
+
readonly namePrefix?: string;
|
|
79
|
+
readonly nameExact?: string;
|
|
80
|
+
readonly mimeType?: string;
|
|
81
|
+
readonly limit?: number;
|
|
82
|
+
}
|
|
83
|
+
interface DriveFileMeta {
|
|
84
|
+
readonly id: string;
|
|
85
|
+
readonly name: string;
|
|
86
|
+
readonly headRevisionId: string;
|
|
87
|
+
readonly size: number;
|
|
88
|
+
}
|
|
89
|
+
interface HandleStore {
|
|
90
|
+
getHandle(vaultId: string): Promise<DriveHandle | null>;
|
|
91
|
+
setHandle(vaultId: string, handle: DriveHandle): Promise<void>;
|
|
92
|
+
deleteHandle(vaultId: string): Promise<void>;
|
|
93
|
+
/** Return every known { vaultId, handle } pair. Used by `listBundles()`. */
|
|
94
|
+
listHandles?(): Promise<Array<{
|
|
95
|
+
vaultId: string;
|
|
96
|
+
handle: DriveHandle;
|
|
97
|
+
}>>;
|
|
98
|
+
}
|
|
99
|
+
interface DriveHandle {
|
|
100
|
+
/** Stable Drive fileId. */
|
|
101
|
+
readonly fileId: string;
|
|
102
|
+
/** ULID filename — what lives in Drive. */
|
|
103
|
+
readonly name: string;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* In-memory handle store — fine for short-lived processes and tests.
|
|
107
|
+
* Production consumers should persist handles to localStorage, IDB,
|
|
108
|
+
* or a vault's `_sync_credentials` collection.
|
|
109
|
+
*/
|
|
110
|
+
declare function memoryHandleStore(): HandleStore;
|
|
111
|
+
/**
|
|
112
|
+
* Generate a new ULID — 26 characters: 10 chars of timestamp (ms
|
|
113
|
+
* granularity, sortable lexically when generated ≥ 1 ms apart) plus
|
|
114
|
+
* 16 chars of entropy (80 bits).
|
|
115
|
+
*/
|
|
116
|
+
declare function newUlid(): string;
|
|
117
|
+
interface DriveStoreOptions {
|
|
118
|
+
readonly drive: DriveClient;
|
|
119
|
+
/**
|
|
120
|
+
* Parent folder id. Defaults to Drive's `appDataFolder` — hidden from
|
|
121
|
+
* the user, scoped to the app. Pass an explicit id to use a
|
|
122
|
+
* user-visible folder.
|
|
123
|
+
*/
|
|
124
|
+
readonly parentId?: string;
|
|
125
|
+
/** Handle registry — memory by default. Persist yourself in prod. */
|
|
126
|
+
readonly handles?: HandleStore;
|
|
127
|
+
/** Bundle filename suffix. Default `'.noydb'`. */
|
|
128
|
+
readonly suffix?: string;
|
|
129
|
+
}
|
|
130
|
+
declare function drive(options: DriveStoreOptions): NoydbBundleStore;
|
|
131
|
+
|
|
132
|
+
export { type DriveClient, type DriveCreateRequest, type DriveFileMeta, type DriveHandle, type DriveListQuery, type DriveStoreOptions, type DriveUpdateRequest, type HandleStore, drive, memoryHandleStore, newUlid };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { NoydbBundleStore } from '@noy-db/hub';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* **@noy-db/to-drive** — Google Drive bundle store for noy-db.
|
|
5
|
+
*
|
|
6
|
+
* Stores each vault as a single `.noydb` bundle in Drive. Implements
|
|
7
|
+
* the `NoydbBundleStore` contract (read/write/delete/list whole-bundle);
|
|
8
|
+
* wrap with `wrapBundleStore()` from `@noy-db/hub` to get the standard
|
|
9
|
+
* six-method `NoydbStore` surface.
|
|
10
|
+
*
|
|
11
|
+
* ## Privacy posture
|
|
12
|
+
*
|
|
13
|
+
* - **ULID filenames** — `01HXG4F5ZK7…noydb`, never `acme.noydb`.
|
|
14
|
+
* Drive folder listings are visible to share recipients, Workspace
|
|
15
|
+
* admins on managed accounts, and Google's internal search index.
|
|
16
|
+
* Naming the file after the vault leaks client identity to all of
|
|
17
|
+
* those. ULIDs give a sortable, collision-free alternative that
|
|
18
|
+
* discloses nothing.
|
|
19
|
+
* - **`appDataFolder` by default** — a hidden Drive folder that does
|
|
20
|
+
* NOT show in the Drive UI and is scoped to the installed app only.
|
|
21
|
+
* Opt in to a user-visible folder for "restore from Drive" UX.
|
|
22
|
+
* - **`drive.file` scope** — the OAuth token can only see files this
|
|
23
|
+
* app created. No read access to the user's other Drive contents.
|
|
24
|
+
* - **No custom properties** — Drive allows arbitrary key/value
|
|
25
|
+
* metadata on files. This adapter writes nothing there. Every piece
|
|
26
|
+
* of vault metadata lives inside the encrypted body.
|
|
27
|
+
*
|
|
28
|
+
* ## Driver — bring your own
|
|
29
|
+
*
|
|
30
|
+
* noy-db does NOT pull `googleapis` (or any Google SDK) as a runtime
|
|
31
|
+
* dependency. The consumer wires their preferred client (`googleapis`,
|
|
32
|
+
* `gapi-client-ts`, a bespoke `fetch` wrapper) and passes a duck-typed
|
|
33
|
+
* `DriveClient` in. Every OAuth refresh concern stays outside this
|
|
34
|
+
* package.
|
|
35
|
+
*
|
|
36
|
+
* ## Handle registry
|
|
37
|
+
*
|
|
38
|
+
* Drive's API identifies files by `fileId`, not filename. To resolve
|
|
39
|
+
* "give me the bundle for vault ACME," the store needs to remember
|
|
40
|
+
* which fileId corresponds to which vault. Two options:
|
|
41
|
+
*
|
|
42
|
+
* 1. **Consumer-persisted** — pass a `HandleStore` that implements
|
|
43
|
+
* `getHandle(vaultId)` / `setHandle(vaultId, handle)`. Typical
|
|
44
|
+
* implementations: localStorage in browsers, the vault's
|
|
45
|
+
* `_sync_credentials` collection, or a JSON file on disk.
|
|
46
|
+
* 2. **Drive-lookup** (default) — when no handle is cached, issue a
|
|
47
|
+
* `files.list` call filtering by the ULID-encoded vaultId hash.
|
|
48
|
+
* Slower but requires no extra plumbing.
|
|
49
|
+
*
|
|
50
|
+
* @packageDocumentation
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Minimal shape the store needs from a Google Drive client. Every
|
|
55
|
+
* production Drive wrapper (`googleapis`, `gapi`, hand-rolled `fetch`
|
|
56
|
+
* code) can expose this surface with a thin adapter.
|
|
57
|
+
*/
|
|
58
|
+
interface DriveClient {
|
|
59
|
+
createFile(request: DriveCreateRequest): Promise<DriveFileMeta>;
|
|
60
|
+
updateFile(fileId: string, request: DriveUpdateRequest): Promise<DriveFileMeta>;
|
|
61
|
+
getFileMetadata(fileId: string): Promise<DriveFileMeta | null>;
|
|
62
|
+
getFileBytes(fileId: string): Promise<Uint8Array | null>;
|
|
63
|
+
deleteFile(fileId: string): Promise<void>;
|
|
64
|
+
listFiles(query: DriveListQuery): Promise<DriveFileMeta[]>;
|
|
65
|
+
}
|
|
66
|
+
interface DriveCreateRequest {
|
|
67
|
+
readonly name: string;
|
|
68
|
+
readonly bytes: Uint8Array;
|
|
69
|
+
readonly parents: readonly string[];
|
|
70
|
+
readonly mimeType?: string;
|
|
71
|
+
}
|
|
72
|
+
interface DriveUpdateRequest {
|
|
73
|
+
readonly bytes: Uint8Array;
|
|
74
|
+
readonly expectedRevision?: string | null;
|
|
75
|
+
}
|
|
76
|
+
interface DriveListQuery {
|
|
77
|
+
readonly parents?: readonly string[];
|
|
78
|
+
readonly namePrefix?: string;
|
|
79
|
+
readonly nameExact?: string;
|
|
80
|
+
readonly mimeType?: string;
|
|
81
|
+
readonly limit?: number;
|
|
82
|
+
}
|
|
83
|
+
interface DriveFileMeta {
|
|
84
|
+
readonly id: string;
|
|
85
|
+
readonly name: string;
|
|
86
|
+
readonly headRevisionId: string;
|
|
87
|
+
readonly size: number;
|
|
88
|
+
}
|
|
89
|
+
interface HandleStore {
|
|
90
|
+
getHandle(vaultId: string): Promise<DriveHandle | null>;
|
|
91
|
+
setHandle(vaultId: string, handle: DriveHandle): Promise<void>;
|
|
92
|
+
deleteHandle(vaultId: string): Promise<void>;
|
|
93
|
+
/** Return every known { vaultId, handle } pair. Used by `listBundles()`. */
|
|
94
|
+
listHandles?(): Promise<Array<{
|
|
95
|
+
vaultId: string;
|
|
96
|
+
handle: DriveHandle;
|
|
97
|
+
}>>;
|
|
98
|
+
}
|
|
99
|
+
interface DriveHandle {
|
|
100
|
+
/** Stable Drive fileId. */
|
|
101
|
+
readonly fileId: string;
|
|
102
|
+
/** ULID filename — what lives in Drive. */
|
|
103
|
+
readonly name: string;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* In-memory handle store — fine for short-lived processes and tests.
|
|
107
|
+
* Production consumers should persist handles to localStorage, IDB,
|
|
108
|
+
* or a vault's `_sync_credentials` collection.
|
|
109
|
+
*/
|
|
110
|
+
declare function memoryHandleStore(): HandleStore;
|
|
111
|
+
/**
|
|
112
|
+
* Generate a new ULID — 26 characters: 10 chars of timestamp (ms
|
|
113
|
+
* granularity, sortable lexically when generated ≥ 1 ms apart) plus
|
|
114
|
+
* 16 chars of entropy (80 bits).
|
|
115
|
+
*/
|
|
116
|
+
declare function newUlid(): string;
|
|
117
|
+
interface DriveStoreOptions {
|
|
118
|
+
readonly drive: DriveClient;
|
|
119
|
+
/**
|
|
120
|
+
* Parent folder id. Defaults to Drive's `appDataFolder` — hidden from
|
|
121
|
+
* the user, scoped to the app. Pass an explicit id to use a
|
|
122
|
+
* user-visible folder.
|
|
123
|
+
*/
|
|
124
|
+
readonly parentId?: string;
|
|
125
|
+
/** Handle registry — memory by default. Persist yourself in prod. */
|
|
126
|
+
readonly handles?: HandleStore;
|
|
127
|
+
/** Bundle filename suffix. Default `'.noydb'`. */
|
|
128
|
+
readonly suffix?: string;
|
|
129
|
+
}
|
|
130
|
+
declare function drive(options: DriveStoreOptions): NoydbBundleStore;
|
|
131
|
+
|
|
132
|
+
export { type DriveClient, type DriveCreateRequest, type DriveFileMeta, type DriveHandle, type DriveListQuery, type DriveStoreOptions, type DriveUpdateRequest, type HandleStore, drive, memoryHandleStore, newUlid };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { BundleVersionConflictError } from "@noy-db/hub";
|
|
3
|
+
function memoryHandleStore() {
|
|
4
|
+
const map = /* @__PURE__ */ new Map();
|
|
5
|
+
return {
|
|
6
|
+
async getHandle(vaultId) {
|
|
7
|
+
return map.get(vaultId) ?? null;
|
|
8
|
+
},
|
|
9
|
+
async setHandle(vaultId, handle) {
|
|
10
|
+
map.set(vaultId, handle);
|
|
11
|
+
},
|
|
12
|
+
async deleteHandle(vaultId) {
|
|
13
|
+
map.delete(vaultId);
|
|
14
|
+
},
|
|
15
|
+
async listHandles() {
|
|
16
|
+
return [...map.entries()].map(([vaultId, handle]) => ({ vaultId, handle }));
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
var ULID_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
21
|
+
function newUlid() {
|
|
22
|
+
const time = Date.now();
|
|
23
|
+
let timePart = "";
|
|
24
|
+
let t = time;
|
|
25
|
+
for (let i = 0; i < 10; i++) {
|
|
26
|
+
timePart = ULID_ALPHABET[t % 32] + timePart;
|
|
27
|
+
t = Math.floor(t / 32);
|
|
28
|
+
}
|
|
29
|
+
const rand = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
30
|
+
let randPart = "";
|
|
31
|
+
for (const byte of rand) {
|
|
32
|
+
randPart += ULID_ALPHABET[byte % 32];
|
|
33
|
+
}
|
|
34
|
+
return timePart + randPart;
|
|
35
|
+
}
|
|
36
|
+
var APP_DATA_FOLDER = "appDataFolder";
|
|
37
|
+
var DEFAULT_MIME = "application/octet-stream";
|
|
38
|
+
function drive(options) {
|
|
39
|
+
const parentId = options.parentId ?? APP_DATA_FOLDER;
|
|
40
|
+
const handles = options.handles ?? memoryHandleStore();
|
|
41
|
+
const suffix = options.suffix ?? ".noydb";
|
|
42
|
+
const { drive: client } = options;
|
|
43
|
+
async function handleFor(vaultId) {
|
|
44
|
+
return handles.getHandle(vaultId);
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
kind: "bundle",
|
|
48
|
+
name: "google-drive",
|
|
49
|
+
async readBundle(vaultId) {
|
|
50
|
+
const handle = await handleFor(vaultId);
|
|
51
|
+
if (!handle) return null;
|
|
52
|
+
const meta = await client.getFileMetadata(handle.fileId);
|
|
53
|
+
if (!meta) {
|
|
54
|
+
await handles.deleteHandle(vaultId);
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
const bytes = await client.getFileBytes(handle.fileId);
|
|
58
|
+
if (!bytes) return null;
|
|
59
|
+
return { bytes, version: meta.headRevisionId };
|
|
60
|
+
},
|
|
61
|
+
async writeBundle(vaultId, bytes, expectedVersion) {
|
|
62
|
+
const handle = await handleFor(vaultId);
|
|
63
|
+
if (!handle) {
|
|
64
|
+
if (expectedVersion !== null) {
|
|
65
|
+
throw new BundleVersionConflictError(
|
|
66
|
+
`No existing bundle for vault "${vaultId}" but expectedVersion="${expectedVersion}" was supplied.`
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
const name = `${newUlid()}${suffix}`;
|
|
70
|
+
const meta2 = await client.createFile({
|
|
71
|
+
name,
|
|
72
|
+
bytes,
|
|
73
|
+
parents: [parentId],
|
|
74
|
+
mimeType: DEFAULT_MIME
|
|
75
|
+
});
|
|
76
|
+
await handles.setHandle(vaultId, { fileId: meta2.id, name: meta2.name });
|
|
77
|
+
return { version: meta2.headRevisionId };
|
|
78
|
+
}
|
|
79
|
+
const meta = await client.updateFile(handle.fileId, {
|
|
80
|
+
bytes,
|
|
81
|
+
expectedRevision: expectedVersion
|
|
82
|
+
});
|
|
83
|
+
return { version: meta.headRevisionId };
|
|
84
|
+
},
|
|
85
|
+
async deleteBundle(vaultId) {
|
|
86
|
+
const handle = await handleFor(vaultId);
|
|
87
|
+
if (!handle) return;
|
|
88
|
+
try {
|
|
89
|
+
await client.deleteFile(handle.fileId);
|
|
90
|
+
} catch {
|
|
91
|
+
}
|
|
92
|
+
await handles.deleteHandle(vaultId);
|
|
93
|
+
},
|
|
94
|
+
async listBundles() {
|
|
95
|
+
if (handles.listHandles) {
|
|
96
|
+
const known = await handles.listHandles();
|
|
97
|
+
const out = [];
|
|
98
|
+
for (const { vaultId, handle } of known) {
|
|
99
|
+
const meta = await client.getFileMetadata(handle.fileId);
|
|
100
|
+
if (!meta) continue;
|
|
101
|
+
out.push({ vaultId, version: meta.headRevisionId, size: meta.size });
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
const files = await client.listFiles({ parents: [parentId], mimeType: DEFAULT_MIME });
|
|
106
|
+
return files.filter((f) => f.name.endsWith(suffix)).map((f) => ({ vaultId: f.name.slice(0, -suffix.length), version: f.headRevisionId, size: f.size }));
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
export {
|
|
111
|
+
drive,
|
|
112
|
+
memoryHandleStore,
|
|
113
|
+
newUlid
|
|
114
|
+
};
|
|
115
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/to-drive** — Google Drive bundle store for noy-db.\n *\n * Stores each vault as a single `.noydb` bundle in Drive. Implements\n * the `NoydbBundleStore` contract (read/write/delete/list whole-bundle);\n * wrap with `wrapBundleStore()` from `@noy-db/hub` to get the standard\n * six-method `NoydbStore` surface.\n *\n * ## Privacy posture\n *\n * - **ULID filenames** — `01HXG4F5ZK7…noydb`, never `acme.noydb`.\n * Drive folder listings are visible to share recipients, Workspace\n * admins on managed accounts, and Google's internal search index.\n * Naming the file after the vault leaks client identity to all of\n * those. ULIDs give a sortable, collision-free alternative that\n * discloses nothing.\n * - **`appDataFolder` by default** — a hidden Drive folder that does\n * NOT show in the Drive UI and is scoped to the installed app only.\n * Opt in to a user-visible folder for \"restore from Drive\" UX.\n * - **`drive.file` scope** — the OAuth token can only see files this\n * app created. No read access to the user's other Drive contents.\n * - **No custom properties** — Drive allows arbitrary key/value\n * metadata on files. This adapter writes nothing there. Every piece\n * of vault metadata lives inside the encrypted body.\n *\n * ## Driver — bring your own\n *\n * noy-db does NOT pull `googleapis` (or any Google SDK) as a runtime\n * dependency. The consumer wires their preferred client (`googleapis`,\n * `gapi-client-ts`, a bespoke `fetch` wrapper) and passes a duck-typed\n * `DriveClient` in. Every OAuth refresh concern stays outside this\n * package.\n *\n * ## Handle registry\n *\n * Drive's API identifies files by `fileId`, not filename. To resolve\n * \"give me the bundle for vault ACME,\" the store needs to remember\n * which fileId corresponds to which vault. Two options:\n *\n * 1. **Consumer-persisted** — pass a `HandleStore` that implements\n * `getHandle(vaultId)` / `setHandle(vaultId, handle)`. Typical\n * implementations: localStorage in browsers, the vault's\n * `_sync_credentials` collection, or a JSON file on disk.\n * 2. **Drive-lookup** (default) — when no handle is cached, issue a\n * `files.list` call filtering by the ULID-encoded vaultId hash.\n * Slower but requires no extra plumbing.\n *\n * @packageDocumentation\n */\n\nimport type { NoydbBundleStore } from '@noy-db/hub'\nimport { BundleVersionConflictError } from '@noy-db/hub'\n\n// ── Duck-typed Drive client ──────────────────────────────────────────────\n\n/**\n * Minimal shape the store needs from a Google Drive client. Every\n * production Drive wrapper (`googleapis`, `gapi`, hand-rolled `fetch`\n * code) can expose this surface with a thin adapter.\n */\nexport interface DriveClient {\n createFile(request: DriveCreateRequest): Promise<DriveFileMeta>\n updateFile(fileId: string, request: DriveUpdateRequest): Promise<DriveFileMeta>\n getFileMetadata(fileId: string): Promise<DriveFileMeta | null>\n getFileBytes(fileId: string): Promise<Uint8Array | null>\n deleteFile(fileId: string): Promise<void>\n listFiles(query: DriveListQuery): Promise<DriveFileMeta[]>\n}\n\nexport interface DriveCreateRequest {\n readonly name: string\n readonly bytes: Uint8Array\n readonly parents: readonly string[]\n readonly mimeType?: string\n}\n\nexport interface DriveUpdateRequest {\n readonly bytes: Uint8Array\n readonly expectedRevision?: string | null\n}\n\nexport interface DriveListQuery {\n readonly parents?: readonly string[]\n readonly namePrefix?: string\n readonly nameExact?: string\n readonly mimeType?: string\n readonly limit?: number\n}\n\nexport interface DriveFileMeta {\n readonly id: string\n readonly name: string\n readonly headRevisionId: string\n readonly size: number\n}\n\n// ── Handle registry ──────────────────────────────────────────────────────\n\nexport interface HandleStore {\n getHandle(vaultId: string): Promise<DriveHandle | null>\n setHandle(vaultId: string, handle: DriveHandle): Promise<void>\n deleteHandle(vaultId: string): Promise<void>\n /** Return every known { vaultId, handle } pair. Used by `listBundles()`. */\n listHandles?(): Promise<Array<{ vaultId: string; handle: DriveHandle }>>\n}\n\nexport interface DriveHandle {\n /** Stable Drive fileId. */\n readonly fileId: string\n /** ULID filename — what lives in Drive. */\n readonly name: string\n}\n\n/**\n * In-memory handle store — fine for short-lived processes and tests.\n * Production consumers should persist handles to localStorage, IDB,\n * or a vault's `_sync_credentials` collection.\n */\nexport function memoryHandleStore(): HandleStore {\n const map = new Map<string, DriveHandle>()\n return {\n async getHandle(vaultId) { return map.get(vaultId) ?? null },\n async setHandle(vaultId, handle) { map.set(vaultId, handle) },\n async deleteHandle(vaultId) { map.delete(vaultId) },\n async listHandles() {\n return [...map.entries()].map(([vaultId, handle]) => ({ vaultId, handle }))\n },\n }\n}\n\n// ── ULID generator (minimal, copy-free) ───────────────────────────────────\n\nconst ULID_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\n/**\n * Generate a new ULID — 26 characters: 10 chars of timestamp (ms\n * granularity, sortable lexically when generated ≥ 1 ms apart) plus\n * 16 chars of entropy (80 bits).\n */\nexport function newUlid(): string {\n const time = Date.now()\n let timePart = ''\n let t = time\n for (let i = 0; i < 10; i++) {\n timePart = ULID_ALPHABET[t % 32]! + timePart\n t = Math.floor(t / 32)\n }\n // 16 chars of random → 16 bytes. 256 is a multiple of 32 so `byte % 32`\n // produces a uniform distribution over the alphabet.\n const rand = globalThis.crypto.getRandomValues(new Uint8Array(16))\n let randPart = ''\n for (const byte of rand) {\n randPart += ULID_ALPHABET[byte % 32]\n }\n return timePart + randPart\n}\n\n// ── Options + factory ────────────────────────────────────────────────────\n\nexport interface DriveStoreOptions {\n readonly drive: DriveClient\n /**\n * Parent folder id. Defaults to Drive's `appDataFolder` — hidden from\n * the user, scoped to the app. Pass an explicit id to use a\n * user-visible folder.\n */\n readonly parentId?: string\n /** Handle registry — memory by default. Persist yourself in prod. */\n readonly handles?: HandleStore\n /** Bundle filename suffix. Default `'.noydb'`. */\n readonly suffix?: string\n}\n\nconst APP_DATA_FOLDER = 'appDataFolder'\nconst DEFAULT_MIME = 'application/octet-stream'\n\nexport function drive(options: DriveStoreOptions): NoydbBundleStore {\n const parentId = options.parentId ?? APP_DATA_FOLDER\n const handles = options.handles ?? memoryHandleStore()\n const suffix = options.suffix ?? '.noydb'\n const { drive: client } = options\n\n async function handleFor(vaultId: string): Promise<DriveHandle | null> {\n return handles.getHandle(vaultId)\n }\n\n return {\n kind: 'bundle',\n name: 'google-drive',\n\n async readBundle(vaultId) {\n const handle = await handleFor(vaultId)\n if (!handle) return null\n\n const meta = await client.getFileMetadata(handle.fileId)\n if (!meta) {\n // Out-of-band deletion — clear the cached handle.\n await handles.deleteHandle(vaultId)\n return null\n }\n const bytes = await client.getFileBytes(handle.fileId)\n if (!bytes) return null\n return { bytes, version: meta.headRevisionId }\n },\n\n async writeBundle(vaultId, bytes, expectedVersion) {\n const handle = await handleFor(vaultId)\n if (!handle) {\n if (expectedVersion !== null) {\n throw new BundleVersionConflictError(\n `No existing bundle for vault \"${vaultId}\" but expectedVersion=\"${expectedVersion}\" was supplied.`,\n )\n }\n const name = `${newUlid()}${suffix}`\n const meta = await client.createFile({\n name,\n bytes,\n parents: [parentId],\n mimeType: DEFAULT_MIME,\n })\n await handles.setHandle(vaultId, { fileId: meta.id, name: meta.name })\n return { version: meta.headRevisionId }\n }\n const meta = await client.updateFile(handle.fileId, {\n bytes,\n expectedRevision: expectedVersion,\n })\n return { version: meta.headRevisionId }\n },\n\n async deleteBundle(vaultId) {\n const handle = await handleFor(vaultId)\n if (!handle) return\n try {\n await client.deleteFile(handle.fileId)\n } catch {\n // Already gone.\n }\n await handles.deleteHandle(vaultId)\n },\n\n async listBundles() {\n if (handles.listHandles) {\n const known = await handles.listHandles()\n const out: Array<{ vaultId: string; version: string; size: number }> = []\n for (const { vaultId, handle } of known) {\n const meta = await client.getFileMetadata(handle.fileId)\n if (!meta) continue\n out.push({ vaultId, version: meta.headRevisionId, size: meta.size })\n }\n return out\n }\n // No handle index: fall back to Drive listing. This returns Drive\n // file ids as \"vault ids\", which is imperfect — consumers are\n // expected to either run a handle store or never call listBundles.\n const files = await client.listFiles({ parents: [parentId], mimeType: DEFAULT_MIME })\n return files\n .filter(f => f.name.endsWith(suffix))\n .map(f => ({ vaultId: f.name.slice(0, -suffix.length), version: f.headRevisionId, size: f.size }))\n },\n }\n}\n"],"mappings":";AAmDA,SAAS,kCAAkC;AAmEpC,SAAS,oBAAiC;AAC/C,QAAM,MAAM,oBAAI,IAAyB;AACzC,SAAO;AAAA,IACL,MAAM,UAAU,SAA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,OAAO;AACvC,gBAAM,OAAO,MAAM,OAAO,gBAAgB,OAAO,MAAM;AACvD,cAAI,CAAC,KAAM;AACX,cAAI,KAAK,EAAE,SAAS,SAAS,KAAK,gBAAgB,MAAM,KAAK,KAAK,CAAC;AAAA,QACrE;AACA,eAAO;AAAA,MACT;AAIA,YAAM,QAAQ,MAAM,OAAO,UAAU,EAAE,SAAS,CAAC,QAAQ,GAAG,UAAU,aAAa,CAAC;AACpF,aAAO,MACJ,OAAO,OAAK,EAAE,KAAK,SAAS,MAAM,CAAC,EACnC,IAAI,QAAM,EAAE,SAAS,EAAE,KAAK,MAAM,GAAG,CAAC,OAAO,MAAM,GAAG,SAAS,EAAE,gBAAgB,MAAM,EAAE,KAAK,EAAE;AAAA,IACrG;AAAA,EACF;AACF;","names":["meta"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@noy-db/to-drive",
|
|
3
|
+
"version": "0.1.0-pre.3",
|
|
4
|
+
"description": "Google Drive bundle store for noy-db. Stores the whole vault as a single .noydb file in Drive's hidden appDataFolder; opaque ULID filenames never leak compartment names. Driver-agnostic — bring your own OAuth token.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "vLannaAi <vicio@lanna.ai>",
|
|
7
|
+
"homepage": "https://github.com/vLannaAi/noy-db/tree/main/packages/to-drive#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/vLannaAi/noy-db.git",
|
|
11
|
+
"directory": "packages/to-drive"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/vLannaAi/noy-db/issues"
|
|
15
|
+
},
|
|
16
|
+
"type": "module",
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"import": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"require": {
|
|
25
|
+
"types": "./dist/index.d.cts",
|
|
26
|
+
"default": "./dist/index.cjs"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"main": "./dist/index.cjs",
|
|
31
|
+
"module": "./dist/index.js",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=18.0.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@noy-db/hub": "0.1.0-pre.3"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/node": "^22.0.0",
|
|
46
|
+
"@noy-db/hub": "0.1.0-pre.3"
|
|
47
|
+
},
|
|
48
|
+
"keywords": [
|
|
49
|
+
"noy-db",
|
|
50
|
+
"to-drive",
|
|
51
|
+
"google-drive",
|
|
52
|
+
"oauth",
|
|
53
|
+
"bundle",
|
|
54
|
+
"storage",
|
|
55
|
+
"zero-knowledge"
|
|
56
|
+
],
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public",
|
|
59
|
+
"tag": "latest"
|
|
60
|
+
},
|
|
61
|
+
"scripts": {
|
|
62
|
+
"build": "tsup",
|
|
63
|
+
"test": "vitest run",
|
|
64
|
+
"lint": "eslint src/",
|
|
65
|
+
"typecheck": "tsc --noEmit"
|
|
66
|
+
}
|
|
67
|
+
}
|