@tinycloud/replica 0.4.4-beta.0 → 0.4.5-beta.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.
@@ -1,563 +1,4 @@
1
- // ../bootstrap/dist/index.js
2
- var CAPABILITIES = [
3
- { urn: "tinycloud.kv/get", service: "tinycloud.kv", status: "active" },
4
- { urn: "tinycloud.kv/list", service: "tinycloud.kv", status: "active" },
5
- { urn: "tinycloud.kv/metadata", service: "tinycloud.kv", status: "active" },
6
- { urn: "tinycloud.kv/put", service: "tinycloud.kv", status: "active" },
7
- { urn: "tinycloud.kv/del", service: "tinycloud.kv", status: "active" },
8
- { urn: "tinycloud.kv/delete", service: "tinycloud.kv", status: "deprecated-alias", aliasOf: "tinycloud.kv/del" },
9
- { urn: "tinycloud.kv/sync", service: "tinycloud.kv", status: "active" },
10
- { urn: "tinycloud.kv/retain", service: "tinycloud.kv", status: "active" },
11
- { urn: "tinycloud.sql/read", service: "tinycloud.sql", status: "active" },
12
- { urn: "tinycloud.sql/select", service: "tinycloud.sql", status: "deprecated-alias", aliasOf: "tinycloud.sql/read" },
13
- { urn: "tinycloud.sql/write", service: "tinycloud.sql", status: "active" },
14
- { urn: "tinycloud.sql/schema", service: "tinycloud.sql", status: "active" },
15
- { urn: "tinycloud.sql/admin", service: "tinycloud.sql", status: "active", implies: ["tinycloud.sql/schema"] },
16
- { urn: "tinycloud.sql/*", service: "tinycloud.sql", status: "active", implies: ["tinycloud.sql/read", "tinycloud.sql/write", "tinycloud.sql/schema", "tinycloud.sql/admin"] },
17
- { urn: "tinycloud.duckdb/read", service: "tinycloud.duckdb", status: "active" },
18
- { urn: "tinycloud.duckdb/write", service: "tinycloud.duckdb", status: "active" },
19
- { urn: "tinycloud.duckdb/admin", service: "tinycloud.duckdb", status: "active" },
20
- { urn: "tinycloud.duckdb/import", service: "tinycloud.duckdb", status: "active" },
21
- { urn: "tinycloud.duckdb/export", service: "tinycloud.duckdb", status: "active" },
22
- { urn: "tinycloud.duckdb/select", service: "tinycloud.duckdb", status: "deprecated-alias", aliasOf: "tinycloud.duckdb/read" },
23
- { urn: "tinycloud.duckdb/*", service: "tinycloud.duckdb", status: "active", implies: ["tinycloud.duckdb/read", "tinycloud.duckdb/write", "tinycloud.duckdb/admin", "tinycloud.duckdb/import", "tinycloud.duckdb/export"] },
24
- { urn: "tinycloud.capabilities/read", service: "tinycloud.capabilities", status: "active" },
25
- { urn: "tinycloud.delegation/status", service: "tinycloud.delegation", status: "active" },
26
- { urn: "tinycloud.delegation/list", service: "tinycloud.delegation", status: "active" },
27
- { urn: "tinycloud.hooks/subscribe", service: "tinycloud.hooks", status: "active" },
28
- { urn: "tinycloud.hooks/register", service: "tinycloud.hooks", status: "active" },
29
- { urn: "tinycloud.hooks/list", service: "tinycloud.hooks", status: "active" },
30
- { urn: "tinycloud.hooks/unregister", service: "tinycloud.hooks", status: "active" },
31
- { urn: "tinycloud.encryption/decrypt", service: "tinycloud.encryption", status: "active" },
32
- { urn: "tinycloud.encryption/network.create", service: "tinycloud.encryption", status: "active" },
33
- { urn: "tinycloud.encryption/network.revoke", service: "tinycloud.encryption", status: "active" },
34
- { urn: "tinycloud.space/host", service: "tinycloud.space", status: "active" },
35
- { urn: "tinycloud.space/create", service: "tinycloud.space", status: "active" },
36
- { urn: "tinycloud.space/list", service: "tinycloud.space", status: "active" },
37
- { urn: "tinycloud.space/info", service: "tinycloud.space", status: "active" },
38
- { urn: "tinycloud.vfs/get", service: "tinycloud.vfs", status: "reserved" },
39
- { urn: "tinycloud.vfs/list", service: "tinycloud.vfs", status: "reserved" },
40
- { urn: "tinycloud.vfs/metadata", service: "tinycloud.vfs", status: "reserved" },
41
- { urn: "tinycloud.vfs/put", service: "tinycloud.vfs", status: "reserved" },
42
- { urn: "tinycloud.vfs/delete", service: "tinycloud.vfs", status: "reserved" }
43
- ];
44
- function actionKey(action) {
45
- if (action === "*") return "ALL";
46
- return action.toUpperCase().replace(/[^A-Z0-9]/g, "_");
47
- }
48
- function serviceOf(urn) {
49
- return urn.slice("tinycloud.".length, urn.indexOf("/"));
50
- }
51
- function actionOf(urn) {
52
- return urn.slice(urn.indexOf("/") + 1);
53
- }
54
- function deriveServiceConstants(service) {
55
- const out = {};
56
- for (const entry of CAPABILITIES) {
57
- if (serviceOf(entry.urn) !== service) continue;
58
- out[actionKey(actionOf(entry.urn))] = entry.urn;
59
- }
60
- return out;
61
- }
62
- var KV = deriveServiceConstants("kv");
63
- var SQL = {
64
- ...deriveServiceConstants("sql"),
65
- EXECUTE: "tinycloud.sql/execute",
66
- EXPORT: "tinycloud.sql/export"
67
- };
68
- var DUCKDB = {
69
- ...deriveServiceConstants("duckdb"),
70
- DESCRIBE: "tinycloud.duckdb/describe",
71
- EXECUTE: "tinycloud.duckdb/execute"
72
- };
73
- var CAPABILITIES2 = deriveServiceConstants("capabilities");
74
- var HOOKS = deriveServiceConstants("hooks");
75
- var ENCRYPTION = deriveServiceConstants("encryption");
76
- var SPACE = deriveServiceConstants("space");
77
- var CAPABILITY_REGISTRY = CAPABILITIES;
78
- var DEFAULT_MANIFEST_SPACE = "applications";
79
- var ACCOUNT_REGISTRY_SPACE = "account";
80
- var ACCOUNT_REGISTRY_PATH = "applications/";
81
- var SECRETS_SPACE = "secrets";
82
- var BOOTSTRAP_DEFAULT_SPACE = "default";
83
- var BOOTSTRAP_PUBLIC_SPACE = "public";
84
- var AGENTS_SPACE = "agents";
85
- var BOOTSTRAP_ENCRYPTION_NETWORK_NAME = "default";
86
- var BOOTSTRAP_ENCRYPTION_NETWORK_RESOURCE_TEMPLATE = `urn:tinycloud:encryption:{ownerDid}:${BOOTSTRAP_ENCRYPTION_NETWORK_NAME}`;
87
- var DEFAULT_EXPIRY_MS = 30 * 24 * 60 * 60 * 1e3;
88
- var VAULT_PERMISSION_SERVICE = "tinycloud.vault";
89
- var ENCRYPTION_PERMISSION_SERVICE = "tinycloud.encryption";
90
- var ENCRYPTION_MANIFEST_SPACE = "encryption";
91
- var NETWORK_CREATE_ACTION = ENCRYPTION.NETWORK_CREATE;
92
- var BOOTSTRAP_SPACE_NAMES = [
93
- BOOTSTRAP_DEFAULT_SPACE,
94
- DEFAULT_MANIFEST_SPACE,
95
- ACCOUNT_REGISTRY_SPACE,
96
- SECRETS_SPACE,
97
- BOOTSTRAP_PUBLIC_SPACE,
98
- AGENTS_SPACE
99
- ];
100
- var TINYCLOUD_DEFAULT_SPACE_MANIFEST = {
101
- app_id: "xyz.tinycloud.default",
102
- name: "TinyCloud Default Space",
103
- space: BOOTSTRAP_DEFAULT_SPACE,
104
- prefix: "",
105
- defaults: false,
106
- includePublicSpace: false,
107
- permissions: [
108
- {
109
- service: "tinycloud.kv",
110
- space: BOOTSTRAP_DEFAULT_SPACE,
111
- // Empty path = whole service on this space. Do NOT use "/": the recap
112
- // encoder joins it as `<space>/<service>//`, which the node's byte-prefix
113
- // resource matching can never extend (real paths start `<service>/x…`).
114
- path: "",
115
- actions: ["get", "put", "del", "list", "metadata"]
116
- },
117
- {
118
- service: "tinycloud.sql",
119
- space: BOOTSTRAP_DEFAULT_SPACE,
120
- path: "",
121
- actions: ["read", "write"]
122
- }
123
- ]
124
- };
125
- var TINYCLOUD_APPLICATIONS_SPACE_MANIFEST = {
126
- app_id: "xyz.tinycloud.applications",
127
- name: "TinyCloud Applications Space",
128
- space: DEFAULT_MANIFEST_SPACE,
129
- prefix: "",
130
- defaults: false,
131
- includePublicSpace: false,
132
- permissions: [
133
- {
134
- service: "tinycloud.kv",
135
- space: DEFAULT_MANIFEST_SPACE,
136
- // Empty path = whole service on this space. Do NOT use "/": the recap
137
- // encoder joins it as `<space>/<service>//`, which the node's byte-prefix
138
- // resource matching can never extend (real paths start `<service>/x…`).
139
- path: "",
140
- actions: ["get", "put", "del", "list", "metadata"]
141
- },
142
- {
143
- service: "tinycloud.sql",
144
- space: DEFAULT_MANIFEST_SPACE,
145
- path: "",
146
- actions: ["read", "write"]
147
- }
148
- ]
149
- };
150
- var TINYCLOUD_ACCOUNT_SPACE_MANIFEST = {
151
- app_id: "xyz.tinycloud.account",
152
- name: "TinyCloud Account Registry",
153
- space: ACCOUNT_REGISTRY_SPACE,
154
- prefix: "",
155
- defaults: false,
156
- includePublicSpace: false,
157
- permissions: [
158
- {
159
- service: "tinycloud.kv",
160
- space: ACCOUNT_REGISTRY_SPACE,
161
- path: "applications/",
162
- actions: ["get", "put", "list"]
163
- },
164
- {
165
- service: "tinycloud.kv",
166
- space: ACCOUNT_REGISTRY_SPACE,
167
- path: "spaces/",
168
- actions: ["get", "put", "list"]
169
- },
170
- {
171
- service: "tinycloud.sql",
172
- space: ACCOUNT_REGISTRY_SPACE,
173
- path: "account",
174
- actions: ["read", "write", "schema"]
175
- }
176
- ]
177
- };
178
- var TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST = {
179
- app_id: "xyz.tinycloud.secrets",
180
- name: "TinyCloud Secrets",
181
- space: SECRETS_SPACE,
182
- prefix: "",
183
- defaults: false,
184
- includePublicSpace: false,
185
- permissions: [
186
- {
187
- service: "tinycloud.vault",
188
- space: SECRETS_SPACE,
189
- path: "secrets/",
190
- actions: ["read"],
191
- skipPrefix: true
192
- },
193
- {
194
- service: "tinycloud.kv",
195
- space: SECRETS_SPACE,
196
- path: "variables",
197
- actions: ["list", "metadata"],
198
- skipPrefix: true
199
- },
200
- {
201
- service: "tinycloud.kv",
202
- space: SECRETS_SPACE,
203
- path: "variables/",
204
- actions: ["get", "put", "del", "list", "metadata"],
205
- skipPrefix: true
206
- },
207
- {
208
- service: "tinycloud.sql",
209
- space: SECRETS_SPACE,
210
- path: "default",
211
- actions: ["read", "write", "schema"],
212
- skipPrefix: true
213
- },
214
- {
215
- service: "tinycloud.capabilities",
216
- space: SECRETS_SPACE,
217
- path: "",
218
- actions: ["read"],
219
- skipPrefix: true
220
- }
221
- ]
222
- };
223
- var TINYCLOUD_PUBLIC_SPACE_MANIFEST = {
224
- app_id: "xyz.tinycloud.public",
225
- name: "TinyCloud Public Space",
226
- space: BOOTSTRAP_PUBLIC_SPACE,
227
- prefix: "",
228
- defaults: false,
229
- includePublicSpace: false,
230
- permissions: [
231
- {
232
- service: "tinycloud.kv",
233
- space: BOOTSTRAP_PUBLIC_SPACE,
234
- path: "",
235
- actions: ["get", "list", "metadata"]
236
- }
237
- ]
238
- };
239
- var TINYCLOUD_AGENTS_SPACE_MANIFEST = {
240
- app_id: "xyz.tinycloud.agents",
241
- name: "TinyCloud Agents Space",
242
- space: AGENTS_SPACE,
243
- prefix: "",
244
- defaults: false,
245
- includePublicSpace: false,
246
- permissions: [
247
- {
248
- service: "tinycloud.kv",
249
- space: AGENTS_SPACE,
250
- path: "",
251
- actions: ["get", "put", "del", "list", "metadata"]
252
- }
253
- ]
254
- };
255
- var BOOTSTRAP_SPACE_MANIFESTS = {
256
- [BOOTSTRAP_DEFAULT_SPACE]: TINYCLOUD_DEFAULT_SPACE_MANIFEST,
257
- [DEFAULT_MANIFEST_SPACE]: TINYCLOUD_APPLICATIONS_SPACE_MANIFEST,
258
- [ACCOUNT_REGISTRY_SPACE]: TINYCLOUD_ACCOUNT_SPACE_MANIFEST,
259
- [SECRETS_SPACE]: TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST,
260
- [BOOTSTRAP_PUBLIC_SPACE]: TINYCLOUD_PUBLIC_SPACE_MANIFEST,
261
- [AGENTS_SPACE]: TINYCLOUD_AGENTS_SPACE_MANIFEST
262
- };
263
- var BOOTSTRAP_PERSISTED_APPLICATION_MANIFESTS = [
264
- TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST
265
- ];
266
- var ACCOUNT_INDEX_SCHEMA = [
267
- `CREATE TABLE IF NOT EXISTS applications (
268
- app_id TEXT PRIMARY KEY,
269
- name TEXT,
270
- description TEXT,
271
- updated_at TEXT,
272
- manifest_json TEXT NOT NULL
273
- )`,
274
- `CREATE TABLE IF NOT EXISTS application_state (
275
- app_id TEXT PRIMARY KEY,
276
- manifest_hash TEXT NOT NULL,
277
- indexed_at TEXT NOT NULL
278
- )`,
279
- `CREATE TABLE IF NOT EXISTS spaces (
280
- space_id TEXT PRIMARY KEY,
281
- name TEXT NOT NULL,
282
- owner_did TEXT NOT NULL,
283
- type TEXT NOT NULL,
284
- permissions_json TEXT NOT NULL,
285
- status TEXT NOT NULL,
286
- registered_at TEXT,
287
- updated_at TEXT NOT NULL,
288
- expires_at TEXT
289
- )`,
290
- `CREATE TABLE IF NOT EXISTS delegations (
291
- cid TEXT PRIMARY KEY,
292
- direction TEXT NOT NULL,
293
- space_id TEXT NOT NULL,
294
- space_name TEXT,
295
- counterparty_did TEXT NOT NULL,
296
- delegate_did TEXT NOT NULL,
297
- delegator_did TEXT,
298
- path TEXT NOT NULL,
299
- actions_json TEXT NOT NULL,
300
- expiry TEXT NOT NULL,
301
- status TEXT NOT NULL,
302
- created_at TEXT,
303
- updated_at TEXT NOT NULL
304
- )`,
305
- `CREATE TABLE IF NOT EXISTS sync_state (
306
- source TEXT PRIMARY KEY,
307
- synced_at TEXT NOT NULL,
308
- count INTEGER NOT NULL
309
- )`,
310
- "CREATE INDEX IF NOT EXISTS idx_delegations_direction ON delegations(direction)",
311
- "CREATE INDEX IF NOT EXISTS idx_delegations_space ON delegations(space_id)",
312
- "CREATE INDEX IF NOT EXISTS idx_delegations_counterparty ON delegations(counterparty_did)",
313
- "CREATE INDEX IF NOT EXISTS idx_spaces_owner ON spaces(owner_did)",
314
- "CREATE INDEX IF NOT EXISTS idx_spaces_type ON spaces(type)"
315
- ];
316
- var SECRET_RECORDS_SCHEMA = [
317
- `CREATE TABLE IF NOT EXISTS secret_records (
318
- scope TEXT NOT NULL,
319
- name TEXT NOT NULL,
320
- provider_id TEXT,
321
- custom_note TEXT,
322
- created_at TEXT NOT NULL,
323
- updated_at TEXT NOT NULL,
324
- last_tested TEXT,
325
- test_status TEXT,
326
- test_message TEXT,
327
- PRIMARY KEY(scope, name)
328
- )`
329
- ];
330
- var BOOTSTRAP_MANIFEST = {
331
- spaces: BOOTSTRAP_SPACE_NAMES.map((name) => ({
332
- name,
333
- manifest: BOOTSTRAP_SPACE_MANIFESTS[name],
334
- persistedAsApplication: name === SECRETS_SPACE
335
- })),
336
- applications: BOOTSTRAP_PERSISTED_APPLICATION_MANIFESTS,
337
- accountIndexSchema: ACCOUNT_INDEX_SCHEMA,
338
- secretRecordsSchema: SECRET_RECORDS_SCHEMA,
339
- encryptionNetwork: {
340
- name: BOOTSTRAP_ENCRYPTION_NETWORK_NAME
341
- }
342
- };
343
- function cloneManifest(manifest) {
344
- return {
345
- ...manifest,
346
- permissions: manifest.permissions?.map((permission) => ({
347
- ...permission,
348
- actions: [...permission.actions]
349
- }))
350
- };
351
- }
352
- function actionUrn(service, action) {
353
- return action.includes("/") ? action : `${service}/${action}`;
354
- }
355
- function applyPrefix(prefix, path, skipPrefix) {
356
- if (skipPrefix === true || prefix === "" || path === "") {
357
- return path;
358
- }
359
- if (path === "/") {
360
- return `${prefix}/`;
361
- }
362
- const trimmedPrefix = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
363
- const trimmedPath = path.startsWith("/") ? path.slice(1) : path;
364
- return `${trimmedPrefix}/${trimmedPath}`;
365
- }
366
- function expandVaultPermission(entry) {
367
- return entry.actions.map((action) => {
368
- const normalized = action.startsWith("tinycloud.vault/") ? action.slice("tinycloud.vault/".length) : action.startsWith("tinycloud.kv/") ? action.slice("tinycloud.kv/".length) : action;
369
- const mapped = normalized === "read" || normalized === "get" ? KV.GET : normalized === "write" || normalized === "put" ? KV.PUT : normalized === "delete" || normalized === "del" ? KV.DEL : normalized === "list" ? KV.LIST : normalized === "metadata" ? KV.METADATA : void 0;
370
- if (mapped === void 0) {
371
- throw new Error(`unknown vault action ${JSON.stringify(action)}`);
372
- }
373
- const normalizedPath = entry.path.startsWith("/") ? entry.path.slice(1) : entry.path;
374
- return {
375
- ...entry,
376
- service: "tinycloud.kv",
377
- path: `vault/${normalizedPath}`,
378
- actions: [mapped],
379
- skipPrefix: true
380
- };
381
- });
382
- }
383
- function expandPermissionEntry(entry, prefix, inheritedSpace) {
384
- if (entry.service === VAULT_PERMISSION_SERVICE) {
385
- return expandVaultPermission(entry).flatMap(
386
- (expanded) => expandPermissionEntry(expanded, prefix, inheritedSpace)
387
- );
388
- }
389
- const skipPrefix = entry.skipPrefix === true || entry.service === ENCRYPTION_PERMISSION_SERVICE;
390
- return [
391
- {
392
- service: entry.service,
393
- space: entry.service === ENCRYPTION_PERMISSION_SERVICE ? ENCRYPTION_MANIFEST_SPACE : entry.space ?? inheritedSpace,
394
- path: applyPrefix(prefix, entry.path, skipPrefix),
395
- actions: entry.actions.map((action) => actionUrn(entry.service, action)),
396
- ...entry.description !== void 0 ? { description: entry.description } : {}
397
- }
398
- ];
399
- }
400
- function dedupeResources(resources) {
401
- const byKey = /* @__PURE__ */ new Map();
402
- for (const resource of resources) {
403
- const key = `${resource.service}\0${resource.space}\0${resource.path}`;
404
- const existing = byKey.get(key);
405
- if (!existing) {
406
- byKey.set(key, { ...resource, actions: [...resource.actions] });
407
- continue;
408
- }
409
- for (const action of resource.actions) {
410
- if (!existing.actions.includes(action)) {
411
- existing.actions.push(action);
412
- }
413
- }
414
- }
415
- return [...byKey.values()];
416
- }
417
- function withCapabilitiesReadForSpaces(resources) {
418
- const spaces = new Set(
419
- resources.filter((resource) => resource.service !== ENCRYPTION_PERMISSION_SERVICE).map((resource) => resource.space)
420
- );
421
- return dedupeResources([
422
- ...resources,
423
- ...[...spaces].map((space) => ({
424
- service: "tinycloud.capabilities",
425
- space,
426
- path: "",
427
- actions: [CAPABILITIES2.READ]
428
- }))
429
- ]);
430
- }
431
- function composeManifestRequest(inputs, options = {}) {
432
- if (!Array.isArray(inputs) || inputs.length === 0) {
433
- throw new Error("composeManifestRequest requires at least one manifest");
434
- }
435
- const includeAccountRegistryPermissions = options.includeAccountRegistryPermissions ?? true;
436
- const manifests = inputs.map(cloneManifest);
437
- const resources = manifests.flatMap((manifest) => {
438
- const prefix = manifest.prefix ?? manifest.app_id;
439
- const space = manifest.space ?? DEFAULT_MANIFEST_SPACE;
440
- const explicit = manifest.permissions ?? [];
441
- return explicit.flatMap((entry) => expandPermissionEntry(entry, prefix, space));
442
- });
443
- if (includeAccountRegistryPermissions) {
444
- resources.push(
445
- ...ACCOUNT_MANIFEST_PERMISSIONS.map((resource) => ({
446
- ...resource,
447
- actions: [...resource.actions]
448
- }))
449
- );
450
- }
451
- const manifestsByAppId = /* @__PURE__ */ new Map();
452
- for (const manifest of manifests) {
453
- const current = manifestsByAppId.get(manifest.app_id) ?? [];
454
- current.push(cloneManifest(manifest));
455
- manifestsByAppId.set(manifest.app_id, current);
456
- }
457
- return {
458
- manifests,
459
- resources: withCapabilitiesReadForSpaces(resources),
460
- delegationTargets: [],
461
- registryRecords: includeAccountRegistryPermissions ? [...manifestsByAppId.entries()].map(([app_id, appManifests]) => ({
462
- key: `${ACCOUNT_REGISTRY_PATH}${app_id}`,
463
- app_id,
464
- manifests: appManifests
465
- })) : [],
466
- expiryMs: DEFAULT_EXPIRY_MS,
467
- includePublicSpace: manifests.some(
468
- (manifest) => manifest.includePublicSpace ?? true
469
- )
470
- };
471
- }
472
- function composeBootstrapSpaceManifest(space) {
473
- return composeManifestRequest([BOOTSTRAP_SPACE_MANIFESTS[space]], {
474
- includeAccountRegistryPermissions: false
475
- });
476
- }
477
- var ACCOUNT_MANIFEST_PERMISSIONS = Object.freeze([
478
- {
479
- service: "tinycloud.kv",
480
- space: ACCOUNT_REGISTRY_SPACE,
481
- path: ACCOUNT_REGISTRY_PATH,
482
- actions: [KV.GET, KV.PUT, KV.LIST]
483
- },
484
- {
485
- service: "tinycloud.kv",
486
- space: ACCOUNT_REGISTRY_SPACE,
487
- path: "spaces/",
488
- actions: [KV.GET, KV.PUT, KV.LIST]
489
- },
490
- {
491
- service: "tinycloud.kv",
492
- space: ACCOUNT_REGISTRY_SPACE,
493
- path: "system/bootstrap/complete",
494
- actions: [KV.GET, KV.PUT]
495
- },
496
- {
497
- service: "tinycloud.delegation",
498
- space: ACCOUNT_REGISTRY_SPACE,
499
- path: "",
500
- actions: ["tinycloud.delegation/list"]
501
- },
502
- {
503
- service: "tinycloud.sql",
504
- space: ACCOUNT_REGISTRY_SPACE,
505
- path: "account",
506
- actions: [SQL.READ, SQL.WRITE, SQL.SCHEMA]
507
- },
508
- {
509
- service: "tinycloud.capabilities",
510
- space: ACCOUNT_REGISTRY_SPACE,
511
- path: "",
512
- actions: [CAPABILITIES2.READ]
513
- }
514
- ]);
515
- var BOOTSTRAP_DEFAULT_ONLY_SESSION_REQUEST = composeBootstrapSpaceManifest(BOOTSTRAP_DEFAULT_SPACE);
516
- var BOOTSTRAP_WIDENED_DEFAULT_SESSION_REQUEST = {
517
- ...BOOTSTRAP_DEFAULT_ONLY_SESSION_REQUEST,
518
- resources: [
519
- ...BOOTSTRAP_DEFAULT_ONLY_SESSION_REQUEST.resources,
520
- ...ACCOUNT_MANIFEST_PERMISSIONS.map((resource) => ({
521
- ...resource,
522
- actions: [...resource.actions]
523
- }))
524
- ]
525
- };
526
- var BOOTSTRAP_SESSION_REQUESTS = Object.freeze(
527
- Object.fromEntries(
528
- BOOTSTRAP_SPACE_NAMES.map((space) => [
529
- space,
530
- space === BOOTSTRAP_DEFAULT_SPACE ? BOOTSTRAP_WIDENED_DEFAULT_SESSION_REQUEST : composeBootstrapSpaceManifest(space)
531
- ])
532
- )
533
- );
534
- var ACCOUNT_SESSION_RAW_ALLOWLIST = Object.freeze([
535
- {
536
- service: "tinycloud.encryption",
537
- resource: BOOTSTRAP_ENCRYPTION_NETWORK_RESOURCE_TEMPLATE,
538
- actions: [NETWORK_CREATE_ACTION]
539
- }
540
- ]);
541
- var BOOTSTRAP_ALLOWLIST = Object.freeze(
542
- BOOTSTRAP_SPACE_NAMES.flatMap((space) => [
543
- {
544
- kind: "session",
545
- service: "tinycloud.session",
546
- space,
547
- actions: ["siwe"],
548
- resources: BOOTSTRAP_SESSION_REQUESTS[space].resources,
549
- ...space === ACCOUNT_REGISTRY_SPACE ? { rawAbilities: ACCOUNT_SESSION_RAW_ALLOWLIST } : {}
550
- },
551
- {
552
- kind: "space/host",
553
- service: "tinycloud.space",
554
- space,
555
- actions: [SPACE.HOST]
556
- }
557
- ])
558
- );
559
-
560
- // ../sdk-services/dist/kv/replication/index.js
1
+ // ../sdk-services/src/kv/replication/identity.ts
561
2
  var SPACE_ID = /^(tinycloud:pkh:eip155:\d+:)([^:]+)(:.+)$/;
562
3
  var PRINCIPAL_DID = /^(did:pkh:eip155:\d+:)([^:]+)$/;
563
4
  function canonicalReplicationIdentity(raw) {
@@ -600,92 +41,6 @@ ${canonical.host}
600
41
  ${canonical.space}
601
42
  ${canonical.principal}`;
602
43
  }
603
- var ErrorCodes = {
604
- // Common errors
605
- NOT_FOUND: "NOT_FOUND",
606
- AUTH_EXPIRED: "AUTH_EXPIRED",
607
- AUTH_REQUIRED: "AUTH_REQUIRED",
608
- AUTH_UNAUTHORIZED: "AUTH_UNAUTHORIZED",
609
- /** HTTP 401: the delegation the invocation cites was revoked. */
610
- AUTH_DELEGATION_REVOKED: "AUTH_DELEGATION_REVOKED",
611
- /** HTTP 401: a delegation the cited one rests on was revoked. */
612
- AUTH_DELEGATION_ANCESTOR_REVOKED: "AUTH_DELEGATION_ANCESTOR_REVOKED",
613
- NETWORK_ERROR: "NETWORK_ERROR",
614
- TIMEOUT: "TIMEOUT",
615
- ABORTED: "ABORTED",
616
- INVALID_INPUT: "INVALID_INPUT",
617
- PERMISSION_DENIED: "PERMISSION_DENIED",
618
- // Node retry signals (tinycloud-node #347). `meta.retryable` says whether a
619
- // retry is safe; `meta.retryAfterMs` carries the node's Retry-After.
620
- /** HTTP 503 `sql_busy:<stage>` / `unavailable_retryable`/`read_audit_busy`: nothing was applied; retry after `meta.retryAfterMs`. */
621
- NODE_BUSY: "NODE_BUSY",
622
- /** HTTP 503 `request_timeout`: the node's deadline passed before any write began; nothing was applied. */
623
- REQUEST_TIMEOUT: "REQUEST_TIMEOUT",
624
- /** HTTP 500 `outcome_unknown`: a write may have been applied; read back before retrying a non-idempotent operation. */
625
- OUTCOME_UNKNOWN: "OUTCOME_UNKNOWN",
626
- // KV-specific errors
627
- KV_NOT_FOUND: "KV_NOT_FOUND",
628
- KV_WRITE_FAILED: "KV_WRITE_FAILED",
629
- KV_PRECONDITION_FAILED: "KV_PRECONDITION_FAILED",
630
- KV_CONFLICT: "KV_CONFLICT",
631
- KV_RESPONSE_TOO_LARGE: "KV_RESPONSE_TOO_LARGE",
632
- /** HTTP 410 from the change feed: discard sync state and restart without a cursor; `meta.reason` says why. */
633
- KV_SYNC_RESET_REQUIRED: "KV_SYNC_RESET_REQUIRED",
634
- /** HTTP 403 from the change feed: the retention grant was refused; `meta.reason` says why. */
635
- KV_RETENTION_GRANT_REFUSED: "KV_RETENTION_GRANT_REFUSED",
636
- // SQL-specific errors
637
- SQL_ERROR: "SQL_ERROR",
638
- SQL_PERMISSION_DENIED: "SQL_PERMISSION_DENIED",
639
- SQL_DATABASE_NOT_FOUND: "SQL_DATABASE_NOT_FOUND",
640
- SQL_RESPONSE_TOO_LARGE: "SQL_RESPONSE_TOO_LARGE",
641
- SQL_QUOTA_EXCEEDED: "SQL_QUOTA_EXCEEDED",
642
- SQL_INVALID_STATEMENT: "SQL_INVALID_STATEMENT",
643
- SQL_SCHEMA_ERROR: "SQL_SCHEMA_ERROR",
644
- SQL_READONLY_VIOLATION: "SQL_READONLY_VIOLATION",
645
- // Storage quota errors
646
- STORAGE_QUOTA_EXCEEDED: "STORAGE_QUOTA_EXCEEDED",
647
- STORAGE_LIMIT_REACHED: "STORAGE_LIMIT_REACHED",
648
- /** The node answered the usage read without usage numbers (it predates the read). */
649
- STORAGE_STATUS_UNAVAILABLE: "STORAGE_STATUS_UNAVAILABLE",
650
- // DuckDB-specific errors
651
- DUCKDB_ERROR: "DUCKDB_ERROR",
652
- DUCKDB_PERMISSION_DENIED: "DUCKDB_PERMISSION_DENIED",
653
- DUCKDB_DATABASE_NOT_FOUND: "DUCKDB_DATABASE_NOT_FOUND",
654
- DUCKDB_RESPONSE_TOO_LARGE: "DUCKDB_RESPONSE_TOO_LARGE",
655
- DUCKDB_QUOTA_EXCEEDED: "DUCKDB_QUOTA_EXCEEDED",
656
- DUCKDB_INVALID_STATEMENT: "DUCKDB_INVALID_STATEMENT",
657
- DUCKDB_SCHEMA_ERROR: "DUCKDB_SCHEMA_ERROR",
658
- DUCKDB_READONLY_VIOLATION: "DUCKDB_READONLY_VIOLATION"
659
- };
660
- var defaultRetryPolicy = {
661
- maxAttempts: 4,
662
- backoff: "exponential",
663
- baseDelayMs: 250,
664
- maxDelayMs: 4e3,
665
- retryableErrors: [ErrorCodes.NODE_BUSY, ErrorCodes.REQUEST_TIMEOUT],
666
- maxTotalMs: 12e3
667
- };
668
- var grantableActions = new Set(
669
- CAPABILITY_REGISTRY.map(({ urn }) => urn).filter((urn) => !urn.endsWith("/*"))
670
- );
671
- var capabilityServices = new Set(
672
- CAPABILITY_REGISTRY.map(({ service }) => service.slice("tinycloud.".length))
673
- );
674
- var DEFINITIVE_FAILURES = /* @__PURE__ */ new Set([
675
- ErrorCodes.AUTH_REQUIRED,
676
- ErrorCodes.INVALID_INPUT,
677
- ErrorCodes.AUTH_UNAUTHORIZED,
678
- ErrorCodes.KV_PRECONDITION_FAILED,
679
- ErrorCodes.STORAGE_QUOTA_EXCEEDED,
680
- ErrorCodes.STORAGE_LIMIT_REACHED
681
- ]);
682
- var encoder = new TextEncoder();
683
- var decoder = new TextDecoder("utf-8", { fatal: true });
684
- var HOUR_MS = 60 * 60 * 1e3;
685
- var DAY_MS = 24 * HOUR_MS;
686
- var MAX_GRANT_TTL_MS = 7 * DAY_MS;
687
- var CONSENT_WINDOW_MS = 7 * DAY_MS;
688
- var EXPIRED = Number.NEGATIVE_INFINITY;
689
44
 
690
45
  // src/errors.ts
691
46
  var ReplicaErrorCode = {
@@ -868,10 +223,10 @@ function validAccountKey(record, gate) {
868
223
  }
869
224
 
870
225
  // ../sdk-services/dist/kv/replication/contractConstants.js
871
- var HOUR_MS2 = 60 * 60 * 1e3;
872
- var DAY_MS2 = 24 * HOUR_MS2;
873
- var MAX_GRANT_TTL_MS2 = 7 * DAY_MS2;
874
- var CONSENT_WINDOW_MS2 = 7 * DAY_MS2;
226
+ var HOUR_MS = 60 * 60 * 1e3;
227
+ var DAY_MS = 24 * HOUR_MS;
228
+ var MAX_GRANT_TTL_MS = 7 * DAY_MS;
229
+ var CONSENT_WINDOW_MS = 7 * DAY_MS;
875
230
  var DEFAULT_MIN_FREE_BYTES = 64 * 1024 * 1024;
876
231
  var REPLICA_KV_DATABASE = "tinycloud-replica-kv";
877
232
  var REPLICA_KV_STORES = {
@@ -905,11 +260,11 @@ function principalOf(did) {
905
260
 
906
261
  // src/kv-storage/sealed.ts
907
262
  import { bytesToHex } from "@noble/hashes/utils";
908
- var encoder2 = new TextEncoder();
263
+ var encoder = new TextEncoder();
909
264
  var NONCE_LENGTH = 12;
910
265
  var TAG_LENGTH = 16;
911
266
  function aad(context) {
912
- return encoder2.encode(`tinycloud-replica-kv:v1\0${context}`);
267
+ return encoder.encode(`tinycloud-replica-kv:v1\0${context}`);
913
268
  }
914
269
  async function seal(key, plaintext, context) {
915
270
  const iv = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH));
@@ -1647,7 +1002,7 @@ function createIndexedDbLifecycle(options = {}) {
1647
1002
  deniedAt: floor.deniedAt,
1648
1003
  keyId: hash.keyId,
1649
1004
  accountKeyId: account.keyId,
1650
- consentDeadline: issuedAt + CONSENT_WINDOW_MS2
1005
+ consentDeadline: issuedAt + CONSENT_WINDOW_MS
1651
1006
  };
1652
1007
  if (!Number.isSafeInteger(created.consentDeadline)) throw gatedError("not_established", "The consent deadline is invalid.");
1653
1008
  await writeGate(created, current, { hash, account });
@@ -2008,8 +1363,8 @@ function createIndexedDbLifecycle(options = {}) {
2008
1363
 
2009
1364
  // src/kv-storage/codec.ts
2010
1365
  import { bytesToHex as bytesToHex2, hexToBytes } from "@noble/hashes/utils";
2011
- var encoder3 = new TextEncoder();
2012
- var decoder2 = new TextDecoder("utf-8", { fatal: true });
1366
+ var encoder2 = new TextEncoder();
1367
+ var decoder = new TextDecoder("utf-8", { fatal: true });
2013
1368
  function encodeValue(value) {
2014
1369
  if (value === void 0) return ["undefined"];
2015
1370
  if (value instanceof Uint8Array) return ["bytes", bytesToHex2(value)];
@@ -2044,11 +1399,11 @@ function decodeValue(value) {
2044
1399
  throw new ReplicaError(ReplicaErrorCode.STORAGE_ERROR, "The replica record has an invalid payload variant.");
2045
1400
  }
2046
1401
  function encodeJson(value) {
2047
- return encoder3.encode(JSON.stringify(["tinycloud-replica-kv", 1, encodeValue(value)]));
1402
+ return encoder2.encode(JSON.stringify(["tinycloud-replica-kv", 1, encodeValue(value)]));
2048
1403
  }
2049
1404
  function decodeJson(bytes) {
2050
1405
  try {
2051
- const value = JSON.parse(decoder2.decode(bytes));
1406
+ const value = JSON.parse(decoder.decode(bytes));
2052
1407
  if (!Array.isArray(value) || value.length !== 3 || value[0] !== "tinycloud-replica-kv" || value[1] !== 1) {
2053
1408
  throw new ReplicaError(ReplicaErrorCode.STORAGE_ERROR, "The replica record has an unknown payload version.");
2054
1409
  }
@@ -2172,7 +1527,7 @@ function spawn(source) {
2172
1527
  if (source instanceof URL || typeof source === "string") return new Worker(source, { type: "module" });
2173
1528
  if (typeof source === "function") return source();
2174
1529
  }
2175
- return new Worker(new URL("./kv-storage.worker.f36b4011295de4d2bd57791c065186645b328f57ad08f1b6fc5843ad6e34c315.js", import.meta.url), { type: "module" });
1530
+ return new Worker(new URL("./kv-storage.worker.bb0d0e128851db2916b3233f31e5c31ca360a97a536bbe1fe81a0fa6886ea307.js", import.meta.url), { type: "module" });
2176
1531
  }
2177
1532
  var WorkerConnection = class {
2178
1533
  ready;