@noy-db/as-json 0.2.0-pre.8 → 0.3.0-pre.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,7 +26,7 @@ See the [main repository](https://github.com/vLannaAi/noy-db#readme) for setup,
26
26
 
27
27
  - Source — [`packages/as-json`](https://github.com/vLannaAi/noy-db/tree/main/packages/as-json)
28
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)
29
+ - Spec — [`SPEC.md`](https://github.com/vLannaAi/noy-db-docs/blob/main/SPEC.md)
30
30
 
31
31
  ## License
32
32
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noy-db/as-json",
3
- "version": "0.2.0-pre.8",
3
+ "version": "0.3.0-pre.1",
4
4
  "description": "Structured JSON plaintext export for noy-db — decrypts records and emits one JSON document per vault. Gated by RFC #249 canExportPlaintext capability; writes an audit-ledger entry on every call. Part of the @noy-db/as-* portable-artefact family (plaintext tier).",
5
5
  "license": "MIT",
6
6
  "author": "vLannaAi <vicio@lanna.ai>",
@@ -17,17 +17,10 @@
17
17
  "sideEffects": false,
18
18
  "exports": {
19
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
- }
20
+ "types": "./dist/index.d.ts",
21
+ "default": "./dist/index.js"
28
22
  }
29
23
  },
30
- "main": "./dist/index.cjs",
31
24
  "module": "./dist/index.js",
32
25
  "types": "./dist/index.d.ts",
33
26
  "files": [
@@ -36,14 +29,14 @@
36
29
  "LICENSE"
37
30
  ],
38
31
  "engines": {
39
- "node": ">=18.0.0"
32
+ "node": ">=22.0.0"
40
33
  },
41
34
  "peerDependencies": {
42
- "@noy-db/hub": "0.2.0-pre.8"
35
+ "@noy-db/hub": "0.3.0-pre.1"
43
36
  },
44
37
  "devDependencies": {
45
38
  "@types/node": "^22.0.0",
46
- "@noy-db/hub": "0.2.0-pre.8"
39
+ "@noy-db/hub": "0.3.0-pre.1"
47
40
  },
48
41
  "keywords": [
49
42
  "noy-db",
package/dist/index.cjs DELETED
@@ -1,147 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- download: () => download,
34
- fromObject: () => fromObject,
35
- fromString: () => fromString,
36
- toObject: () => toObject,
37
- toString: () => toString,
38
- write: () => write
39
- });
40
- module.exports = __toCommonJS(index_exports);
41
- var import_hub = require("@noy-db/hub");
42
- async function toString(vault, options = {}) {
43
- const doc = await toObject(vault, options);
44
- const indent = typeof options.pretty === "number" ? options.pretty : options.pretty === false ? 0 : 2;
45
- return indent > 0 ? JSON.stringify(doc, null, indent) : JSON.stringify(doc);
46
- }
47
- async function toObject(vault, options = {}) {
48
- vault.assertCanExport("plaintext", "json");
49
- const allowlist = options.collections ? new Set(options.collections) : null;
50
- const doc = {};
51
- for await (const chunk of vault.exportStream({ granularity: "collection" })) {
52
- if (allowlist && !allowlist.has(chunk.collection)) continue;
53
- const bucket = doc[chunk.collection] ?? (doc[chunk.collection] = []);
54
- for (const record of chunk.records) {
55
- if (options.includeMeta) {
56
- bucket.push(record);
57
- } else {
58
- bucket.push(stripMeta(record));
59
- }
60
- }
61
- }
62
- return doc;
63
- }
64
- async function download(vault, options = {}) {
65
- const json = await toString(vault, options);
66
- const filename = options.filename ?? "vault-export.json";
67
- const blob = new Blob([json], { type: "application/json;charset=utf-8" });
68
- const url = URL.createObjectURL(blob);
69
- const a = document.createElement("a");
70
- a.href = url;
71
- a.download = filename;
72
- a.click();
73
- URL.revokeObjectURL(url);
74
- }
75
- async function write(vault, path, options) {
76
- if (options.acknowledgeRisks !== true) {
77
- throw new Error(
78
- 'as-json.write: acknowledgeRisks: true is required for on-disk plaintext output. See docs/patterns/as-exports.md \xA7"The three tiers of \\"plaintext out\\""'
79
- );
80
- }
81
- const json = await toString(vault, options);
82
- const { writeFile } = await import("fs/promises");
83
- await writeFile(path, json, "utf-8");
84
- }
85
- function stripMeta(record) {
86
- const out = {};
87
- for (const [key, value] of Object.entries(record)) {
88
- if (key === "_v" || key === "_ts" || key === "_by" || key === "_iv" || key === "_data" || key === "_noydb") continue;
89
- out[key] = value;
90
- }
91
- return out;
92
- }
93
- async function fromObject(vault, doc, options = {}) {
94
- vault.assertCanImport("plaintext", "json");
95
- const policy = options.policy ?? "merge";
96
- const idKey = options.idKey ?? "id";
97
- const plan = await (0, import_hub.diffVault)(vault, doc, {
98
- ...options.collections ? { collections: options.collections } : {},
99
- idKey
100
- });
101
- return {
102
- plan,
103
- policy,
104
- async apply() {
105
- await vault.noydb.transaction((tx) => {
106
- const txVault = tx.vault(vault.name);
107
- for (const entry of plan.added) {
108
- txVault.collection(entry.collection).put(entry.id, entry.record, { reason: "import:json" });
109
- }
110
- if (policy !== "insert-only") {
111
- for (const entry of plan.modified) {
112
- txVault.collection(entry.collection).put(entry.id, entry.record, { reason: "import:json" });
113
- }
114
- }
115
- if (policy === "replace") {
116
- for (const entry of plan.deleted) {
117
- txVault.collection(entry.collection).delete(entry.id);
118
- }
119
- }
120
- });
121
- }
122
- };
123
- }
124
- async function fromString(vault, json, options = {}) {
125
- let parsed;
126
- try {
127
- parsed = JSON.parse(json);
128
- } catch (err) {
129
- throw new Error(`as-json.fromString: input is not valid JSON (${err.message})`);
130
- }
131
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
132
- throw new Error(
133
- `as-json.fromString: top-level value must be an object mapping collections \u2192 records[], got ${Array.isArray(parsed) ? "array" : typeof parsed}`
134
- );
135
- }
136
- return fromObject(vault, parsed, options);
137
- }
138
- // Annotate the CommonJS export names for ESM import in node:
139
- 0 && (module.exports = {
140
- download,
141
- fromObject,
142
- fromString,
143
- toObject,
144
- toString,
145
- write
146
- });
147
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/as-json** — structured JSON plaintext export for noy-db.\n *\n * Decrypts ACL-scoped records from a vault and emits one structured\n * JSON document grouping records by collection. Sibling to the core\n * `exportJSON()` helper — same shape, but gated behind\n * `canExportPlaintext` and paired with browser-download +\n * Node file-write helpers.\n *\n * **Scope.** Multi-collection per call (unlike `as-csv` which is\n * single-collection). Whole-vault by default; pass `collections` to\n * restrict.\n *\n * See `docs/patterns/as-exports.md` for the three-tier egress model\n * (Tier 1 in-memory → Tier 2 browser download → Tier 3 disk write).\n *\n * @packageDocumentation\n */\n\nimport type { Vault } from '@noy-db/hub'\n\nexport interface AsJSONOptions {\n /**\n * Collection allowlist. When omitted, every collection the caller\n * can read is included. Collections not in the caller's ACL silently\n * drop out even when listed here — ACL-scoping runs at the\n * `exportStream` layer.\n */\n readonly collections?: readonly string[]\n\n /**\n * Pretty-print with indentation. Default `2` (2-space indent). Pass\n * `0` or `false` for compact single-line output.\n */\n readonly pretty?: number | boolean\n\n /**\n * Include envelope metadata (`_v`, `_ts`, `_by`) alongside each\n * record. Default `false` — stripped so the JSON matches the shape\n * of the raw records the consumer originally put.\n */\n readonly includeMeta?: boolean\n}\n\nexport interface AsJSONDownloadOptions extends AsJSONOptions {\n /** Filename offered to the browser. Default `'vault-export.json'`. */\n readonly filename?: string\n}\n\nexport interface AsJSONWriteOptions extends AsJSONOptions {\n /** Required to write plaintext JSON to disk — Tier 3 risk gate. */\n readonly acknowledgeRisks: true\n}\n\n/**\n * Shape of the emitted document: one top-level key per collection,\n * each mapping to an array of record objects.\n */\nexport type AsJSONDocument = Record<string, readonly Record<string, unknown>[]>\n\n/**\n * Serialise the vault as a JSON string. Pure operation — no side\n * effects beyond the authorization check and audit ledger write.\n */\nexport async function toString(vault: Vault, options: AsJSONOptions = {}): Promise<string> {\n const doc = await toObject(vault, options)\n const indent = typeof options.pretty === 'number'\n ? options.pretty\n : options.pretty === false\n ? 0\n : 2\n return indent > 0 ? JSON.stringify(doc, null, indent) : JSON.stringify(doc)\n}\n\n/**\n * Serialise the vault as a plain JS object. Useful for in-process\n * pipelines that want to post-process the data before writing.\n */\nexport async function toObject(vault: Vault, options: AsJSONOptions = {}): Promise<AsJSONDocument> {\n vault.assertCanExport('plaintext', 'json')\n\n const allowlist = options.collections ? new Set(options.collections) : null\n const doc: Record<string, Record<string, unknown>[]> = {}\n for await (const chunk of vault.exportStream({ granularity: 'collection' })) {\n if (allowlist && !allowlist.has(chunk.collection)) continue\n const bucket = doc[chunk.collection] ?? (doc[chunk.collection] = [])\n for (const record of chunk.records) {\n if (options.includeMeta) {\n bucket.push(record as Record<string, unknown>)\n } else {\n bucket.push(stripMeta(record as Record<string, unknown>))\n }\n }\n }\n return doc\n}\n\n/**\n * Browser download — wraps `toString()` in a Blob and triggers the\n * browser's save-as prompt. Requires a DOM — in Node, use `write()`.\n */\nexport async function download(vault: Vault, options: AsJSONDownloadOptions = {}): Promise<void> {\n const json = await toString(vault, options)\n const filename = options.filename ?? 'vault-export.json'\n const blob = new Blob([json], { type: 'application/json;charset=utf-8' })\n const url = URL.createObjectURL(blob)\n const a = document.createElement('a')\n a.href = url\n a.download = filename\n a.click()\n URL.revokeObjectURL(url)\n}\n\n/**\n * Node file-write — persists the JSON to disk. Requires\n * `acknowledgeRisks: true` because plaintext outlives the process.\n */\nexport async function write(\n vault: Vault,\n path: string,\n options: AsJSONWriteOptions,\n): Promise<void> {\n if (options.acknowledgeRisks !== true) {\n throw new Error(\n 'as-json.write: acknowledgeRisks: true is required for on-disk plaintext output. ' +\n 'See docs/patterns/as-exports.md §\"The three tiers of \\\\\"plaintext out\\\\\"\"',\n )\n }\n const json = await toString(vault, options)\n const { writeFile } = await import('node:fs/promises')\n await writeFile(path, json, 'utf-8')\n}\n\nfunction stripMeta(record: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(record)) {\n if (key === '_v' || key === '_ts' || key === '_by' || key === '_iv' || key === '_data' || key === '_noydb') continue\n out[key] = value\n }\n return out\n}\n\n// ─── Reader ─────────────────────────────────────────────\n\nimport { diffVault, type VaultDiff } from '@noy-db/hub'\n\n/**\n * Reconciliation policy for `apply()`.\n *\n * - `'merge'` (default) — insert + update, never delete. Records\n * present in the live vault but absent from the file are left\n * intact.\n * - `'replace'` — full mirror. Records present in the live vault but\n * absent from the file are deleted.\n * - `'insert-only'` — only insert new records; skip both updates and\n * deletes. Useful for append-only ledgers.\n */\nexport type ImportPolicy = 'merge' | 'replace' | 'insert-only'\n\nexport interface AsJSONImportOptions {\n /** Restrict the diff + apply to a subset of collections. */\n readonly collections?: readonly string[]\n /** Field on each record that carries its id. Default `'id'`. */\n readonly idKey?: string\n /** Reconciliation policy. Default `'merge'`. */\n readonly policy?: ImportPolicy\n}\n\n/**\n * Output of `fromString` / `fromObject` — preview the changes a JSON\n * import would apply, then commit them with `apply()`. Two-step shape\n * keeps the diff cheap and lets consumers render review-and-confirm\n * UIs without a separate dry-run mode.\n */\nexport interface AsJSONImportPlan {\n readonly plan: VaultDiff\n readonly policy: ImportPolicy\n /** Apply every change in `plan` (filtered by `policy`) to the vault. */\n apply(): Promise<void>\n}\n\n/**\n * Build an import plan from a parsed JSON document. Same shape\n * `as-json.toObject()` produces — `Record<collection, records[]>`.\n */\nexport async function fromObject(\n vault: Vault,\n doc: AsJSONDocument,\n options: AsJSONImportOptions = {},\n): Promise<AsJSONImportPlan> {\n vault.assertCanImport('plaintext', 'json')\n const policy: ImportPolicy = options.policy ?? 'merge'\n const idKey = options.idKey ?? 'id'\n\n // Cast through unknown — diffVault is type-erased at the boundary\n // and AsJSONDocument's per-record type is `Record<string, unknown>`.\n const plan = await diffVault(vault, doc as unknown as Record<string, readonly Record<string, unknown>[]>, {\n ...(options.collections ? { collections: options.collections } : {}),\n idKey,\n })\n\n return {\n plan,\n policy,\n async apply(): Promise<void> {\n // Add and modify go through collection.put which runs the normal\n // permissions check + envelope encryption + ledger write.\n // Delete only runs under the 'replace' policy.\n // Wrapped via vault.noydb.transaction so a partial failure rolls\n // back every executed put. Routes through the txStrategy seam —\n // throws a clear error pointing at withTransactions() when the\n // strategy is not opted in.\n await vault.noydb.transaction((tx) => {\n const txVault = tx.vault(vault.name)\n for (const entry of plan.added) {\n txVault.collection(entry.collection).put(entry.id, entry.record, { reason: 'import:json' })\n }\n if (policy !== 'insert-only') {\n for (const entry of plan.modified) {\n txVault.collection(entry.collection).put(entry.id, entry.record, { reason: 'import:json' })\n }\n }\n if (policy === 'replace') {\n for (const entry of plan.deleted) {\n txVault.collection(entry.collection).delete(entry.id)\n }\n }\n })\n },\n }\n}\n\n/**\n * Build an import plan from a JSON string — parse, then dispatch to\n * `fromObject`. Convenience for the canonical \"load my exported file\"\n * workflow.\n */\nexport async function fromString(\n vault: Vault,\n json: string,\n options: AsJSONImportOptions = {},\n): Promise<AsJSONImportPlan> {\n let parsed: unknown\n try {\n parsed = JSON.parse(json)\n } catch (err) {\n throw new Error(`as-json.fromString: input is not valid JSON (${(err as Error).message})`)\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(\n `as-json.fromString: top-level value must be an object mapping collections → records[], got ${\n Array.isArray(parsed) ? 'array' : typeof parsed\n }`,\n )\n }\n return fromObject(vault, parsed as AsJSONDocument, options)\n}\n"],"mappings":"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","names":[]}
package/dist/index.d.cts DELETED
@@ -1,120 +0,0 @@
1
- import { VaultDiff, Vault } from '@noy-db/hub';
2
-
3
- /**
4
- * **@noy-db/as-json** — structured JSON plaintext export for noy-db.
5
- *
6
- * Decrypts ACL-scoped records from a vault and emits one structured
7
- * JSON document grouping records by collection. Sibling to the core
8
- * `exportJSON()` helper — same shape, but gated behind
9
- * `canExportPlaintext` and paired with browser-download +
10
- * Node file-write helpers.
11
- *
12
- * **Scope.** Multi-collection per call (unlike `as-csv` which is
13
- * single-collection). Whole-vault by default; pass `collections` to
14
- * restrict.
15
- *
16
- * See `docs/patterns/as-exports.md` for the three-tier egress model
17
- * (Tier 1 in-memory → Tier 2 browser download → Tier 3 disk write).
18
- *
19
- * @packageDocumentation
20
- */
21
-
22
- interface AsJSONOptions {
23
- /**
24
- * Collection allowlist. When omitted, every collection the caller
25
- * can read is included. Collections not in the caller's ACL silently
26
- * drop out even when listed here — ACL-scoping runs at the
27
- * `exportStream` layer.
28
- */
29
- readonly collections?: readonly string[];
30
- /**
31
- * Pretty-print with indentation. Default `2` (2-space indent). Pass
32
- * `0` or `false` for compact single-line output.
33
- */
34
- readonly pretty?: number | boolean;
35
- /**
36
- * Include envelope metadata (`_v`, `_ts`, `_by`) alongside each
37
- * record. Default `false` — stripped so the JSON matches the shape
38
- * of the raw records the consumer originally put.
39
- */
40
- readonly includeMeta?: boolean;
41
- }
42
- interface AsJSONDownloadOptions extends AsJSONOptions {
43
- /** Filename offered to the browser. Default `'vault-export.json'`. */
44
- readonly filename?: string;
45
- }
46
- interface AsJSONWriteOptions extends AsJSONOptions {
47
- /** Required to write plaintext JSON to disk — Tier 3 risk gate. */
48
- readonly acknowledgeRisks: true;
49
- }
50
- /**
51
- * Shape of the emitted document: one top-level key per collection,
52
- * each mapping to an array of record objects.
53
- */
54
- type AsJSONDocument = Record<string, readonly Record<string, unknown>[]>;
55
- /**
56
- * Serialise the vault as a JSON string. Pure operation — no side
57
- * effects beyond the authorization check and audit ledger write.
58
- */
59
- declare function toString(vault: Vault, options?: AsJSONOptions): Promise<string>;
60
- /**
61
- * Serialise the vault as a plain JS object. Useful for in-process
62
- * pipelines that want to post-process the data before writing.
63
- */
64
- declare function toObject(vault: Vault, options?: AsJSONOptions): Promise<AsJSONDocument>;
65
- /**
66
- * Browser download — wraps `toString()` in a Blob and triggers the
67
- * browser's save-as prompt. Requires a DOM — in Node, use `write()`.
68
- */
69
- declare function download(vault: Vault, options?: AsJSONDownloadOptions): Promise<void>;
70
- /**
71
- * Node file-write — persists the JSON to disk. Requires
72
- * `acknowledgeRisks: true` because plaintext outlives the process.
73
- */
74
- declare function write(vault: Vault, path: string, options: AsJSONWriteOptions): Promise<void>;
75
-
76
- /**
77
- * Reconciliation policy for `apply()`.
78
- *
79
- * - `'merge'` (default) — insert + update, never delete. Records
80
- * present in the live vault but absent from the file are left
81
- * intact.
82
- * - `'replace'` — full mirror. Records present in the live vault but
83
- * absent from the file are deleted.
84
- * - `'insert-only'` — only insert new records; skip both updates and
85
- * deletes. Useful for append-only ledgers.
86
- */
87
- type ImportPolicy = 'merge' | 'replace' | 'insert-only';
88
- interface AsJSONImportOptions {
89
- /** Restrict the diff + apply to a subset of collections. */
90
- readonly collections?: readonly string[];
91
- /** Field on each record that carries its id. Default `'id'`. */
92
- readonly idKey?: string;
93
- /** Reconciliation policy. Default `'merge'`. */
94
- readonly policy?: ImportPolicy;
95
- }
96
- /**
97
- * Output of `fromString` / `fromObject` — preview the changes a JSON
98
- * import would apply, then commit them with `apply()`. Two-step shape
99
- * keeps the diff cheap and lets consumers render review-and-confirm
100
- * UIs without a separate dry-run mode.
101
- */
102
- interface AsJSONImportPlan {
103
- readonly plan: VaultDiff;
104
- readonly policy: ImportPolicy;
105
- /** Apply every change in `plan` (filtered by `policy`) to the vault. */
106
- apply(): Promise<void>;
107
- }
108
- /**
109
- * Build an import plan from a parsed JSON document. Same shape
110
- * `as-json.toObject()` produces — `Record<collection, records[]>`.
111
- */
112
- declare function fromObject(vault: Vault, doc: AsJSONDocument, options?: AsJSONImportOptions): Promise<AsJSONImportPlan>;
113
- /**
114
- * Build an import plan from a JSON string — parse, then dispatch to
115
- * `fromObject`. Convenience for the canonical "load my exported file"
116
- * workflow.
117
- */
118
- declare function fromString(vault: Vault, json: string, options?: AsJSONImportOptions): Promise<AsJSONImportPlan>;
119
-
120
- export { type AsJSONDocument, type AsJSONDownloadOptions, type AsJSONImportOptions, type AsJSONImportPlan, type AsJSONOptions, type AsJSONWriteOptions, type ImportPolicy, download, fromObject, fromString, toObject, toString, write };