ownledger 2.1.0 → 2.2.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.
Files changed (84) hide show
  1. package/AGENTS.md +24 -8
  2. package/CHANGELOG.md +33 -0
  3. package/README.md +5 -2
  4. package/assets/index.html +10 -10
  5. package/assets/static/{Account-sw3qGLbB.js → Account-CYrXDU9Z.js} +1 -1
  6. package/assets/static/{Accounts-DWyzX3qB.js → Accounts-BXleOwUO.js} +1 -1
  7. package/assets/static/{Attention-DxV-4qdY.js → Attention-Ci3luOdE.js} +1 -1
  8. package/assets/static/{ByCategory-B4P3ikmE.js → ByCategory-cLVOyjwd.js} +1 -1
  9. package/assets/static/{CardDetail-CayBXBm-.js → CardDetail-BxXfAcMp.js} +1 -1
  10. package/assets/static/{Cards-CVuOP8Bt.js → Cards-DNtITMnA.js} +1 -1
  11. package/assets/static/{Cards-XUBdWxyo.js → Cards-DnIsAWPD.js} +1 -1
  12. package/assets/static/{CardsValue-EoW2jG_0.js → CardsValue-V1-fYMLf.js} +1 -1
  13. package/assets/static/{Cashback-BibVYHf_.js → Cashback-B8lqwRnb.js} +1 -1
  14. package/assets/static/{CategoryIcon-HfjYhH1l.js → CategoryIcon-D4Cdb_ZP.js} +1 -1
  15. package/assets/static/{CategoryPicker-BkmvzX2I.js → CategoryPicker-54vkuxVh.js} +1 -1
  16. package/assets/static/{ChartWidget-u09-whUU.js → ChartWidget-S5F4Ze91.js} +1 -1
  17. package/assets/static/{Combobox-xXeyjGgK.js → Combobox-BvX68J3o.js} +1 -1
  18. package/assets/static/{Deposits-CLAda4dj.js → Deposits-Ct5HhCEc.js} +1 -1
  19. package/assets/static/{DrillLink-Bvfam9FA.js → DrillLink-CZyI-y0-.js} +1 -1
  20. package/assets/static/{Field-tKFmKDEF.js → Field-DYmqEAlI.js} +1 -1
  21. package/assets/static/{HomeEditor-4vxj5LMD.js → HomeEditor-Dv-h_ql-.js} +1 -1
  22. package/assets/static/{Import-DwaaFpRJ.js → Import-B2uhVnEm.js} +1 -1
  23. package/assets/static/{IncomeSpending-RVDSxAK4.js → IncomeSpending-DNT2CWH9.js} +1 -1
  24. package/assets/static/{KV-DMA1AlP-.js → KV-CKWaJkRK.js} +1 -1
  25. package/assets/static/{Left-C_4gTGSX.js → Left-BefXZztB.js} +1 -1
  26. package/assets/static/{Money-PfFNNDOw.js → Money-BwLucm7P.js} +1 -1
  27. package/assets/static/{NetWorth-BSoseczC.js → NetWorth-DeLSapZ2.js} +1 -1
  28. package/assets/static/{Pace-B8p-9174.js → Pace-D6gilOBZ.js} +1 -1
  29. package/assets/static/{Panel-BnfWrw9R.js → Panel-CSe25x0N.js} +1 -1
  30. package/assets/static/{PinDialog-BqAU9Vh4.js → PinDialog-CHiLIKEs.js} +1 -1
  31. package/assets/static/{Plans-2KuQH2_I.js → Plans-D7rJ1yHU.js} +1 -1
  32. package/assets/static/{Recent-Ccmb34bq.js → Recent-Dcqb2yko.js} +1 -1
  33. package/assets/static/{Reports-Dd-dhclr.js → Reports--PDAEnQM.js} +1 -1
  34. package/assets/static/{Settings-BR8WBlen.js → Settings-Bd0oglWl.js} +1 -1
  35. package/assets/static/{Transactions-BAuQ-6Eb.js → Transactions-CQ1yQ1UU.js} +1 -1
  36. package/assets/static/{TxRow-EKIIMQKa.js → TxRow-BGfpKo2m.js} +1 -1
  37. package/assets/static/{Unusual-CwFp8aA5.js → Unusual-DGB4ZOA2.js} +1 -1
  38. package/assets/static/{Upcoming-B28roT9r.js → Upcoming-B0HwBqmG.js} +1 -1
  39. package/assets/static/{WhichCard-B3kLc842.js → WhichCard-BefFKS2q.js} +1 -1
  40. package/assets/static/{arrow-up-D3gxUKLo.js → arrow-up-CRgLRKET.js} +1 -1
  41. package/assets/static/{bits-Dr2E0ObC.js → bits-D34d9IBm.js} +1 -1
  42. package/assets/static/{button-rfwMVz0i.js → button-BKhMn8jX.js} +1 -1
  43. package/assets/static/{cards-Bb5zjzRG.js → cards-Ct0jh73r.js} +1 -1
  44. package/assets/static/{charts-BqP7HKwP.js → charts-D-1glV8L.js} +1 -1
  45. package/assets/static/chevron-down-BWoQwA6m.js +1 -0
  46. package/assets/static/chevron-right-D7Sgw1v1.js +1 -0
  47. package/assets/static/{createLucideIcon-flJrJK2p.js → createLucideIcon-XZ28znwT.js} +1 -1
  48. package/assets/static/{dialog-BuRqO4sc.js → dialog-Bx-cd-2e.js} +1 -1
  49. package/assets/static/{dist-B4_eGtNj.js → dist--HKr0kfV.js} +1 -1
  50. package/assets/static/{dist-B7PR2b0C.js → dist-BFPyD74_.js} +1 -1
  51. package/assets/static/{dist-BDn7ydjn.js → dist-CmbuesVk.js} +1 -1
  52. package/assets/static/{dist-Dl-m8cc2.js → dist-vgyaCpaL.js} +1 -1
  53. package/assets/static/{es2015-DJh4h8NX.js → es2015-DqY4UvQc.js} +1 -1
  54. package/assets/static/{index-eR1GkdC_.js → index-DBHFdsYB.js} +4 -4
  55. package/assets/static/{queries-DZIMMe4i.js → queries-BcMmmb36.js} +1 -1
  56. package/assets/static/{react-dom-wK_7mEjs.js → react-dom-5dgiSOdd.js} +1 -1
  57. package/assets/static/{select-eaSi9K-d.js → select-B5P2TaPX.js} +1 -1
  58. package/assets/static/{shared-Box7on3B.js → shared-BgU6fc7z.js} +1 -1
  59. package/assets/static/{triangle-exclamation-point-CuL0XSJl.js → triangle-exclamation-point-CMy18kC0.js} +1 -1
  60. package/assets/static/{useMutation-_Lw8xXWa.js → useMutation-aC3Z1p9y.js} +1 -1
  61. package/dist/cli/statements.js +153 -5
  62. package/dist/engine/actions.d.ts +28 -0
  63. package/dist/engine/actions.js +109 -3
  64. package/dist/modules/cards/files.d.ts +1 -1
  65. package/dist/modules/cards/files.js +1 -1
  66. package/dist/modules/cards/terms.d.ts +2 -0
  67. package/dist/modules/cards/terms.js +7 -0
  68. package/dist/node/reconcile.d.ts +100 -0
  69. package/dist/node/reconcile.js +176 -0
  70. package/dist/node/statement-rows.d.ts +77 -0
  71. package/dist/node/statement-rows.js +245 -0
  72. package/dist/node/statements.d.ts +2 -1
  73. package/dist/worker/api.js +32 -5
  74. package/dist/worker/github.d.ts +18 -1
  75. package/dist/worker/github.js +53 -6
  76. package/dist/worker/mcp.js +32 -7
  77. package/dist/worker/store.js +1 -1
  78. package/dist/worker/version.d.ts +1 -1
  79. package/dist/worker/version.js +1 -1
  80. package/package.json +1 -1
  81. package/assets/static/chevron-down-Co1w7ApZ.js +0 -1
  82. package/assets/static/chevron-right-Dqh3vs9Y.js +0 -1
  83. package/dist/worker/tar.d.ts +0 -3
  84. package/dist/worker/tar.js +0 -65
@@ -12,7 +12,23 @@ export interface GitHubAppConfig {
12
12
  }
13
13
  export declare function installationToken(c: GitHubAppConfig): Promise<string>;
14
14
  export declare function headSha(c: GitHubAppConfig): Promise<string>;
15
- /** Every file under data/ and imports/*.mapping.yaml at a commit, from one tarball; statement PDFs by path only (""). */
15
+ /** Files the Worker reads as text: everything under data/ and imports/*.mapping.yaml. */
16
+ export declare const isDataFile: (p: string) => boolean;
17
+ interface TreeEntry {
18
+ path: string;
19
+ type: string;
20
+ sha: string;
21
+ }
22
+ /** Which tree entries to read as text, and which to list by path only (statement PDFs, never downloaded). */
23
+ export declare function pickFiles(tree: TreeEntry[]): {
24
+ text: TreeEntry[];
25
+ pathOnly: string[];
26
+ };
27
+ /**
28
+ * Every file under data/ and imports/*.mapping.yaml at a commit; statement PDFs by path only ("").
29
+ * One tree listing plus one GraphQL call per 100 files: no tarball, so binary files in the repo
30
+ * (statement PDFs, raw exports) cost the Worker nothing (a tarball of them ran past the Free plan's CPU limit).
31
+ */
16
32
  export declare function filesAt(c: GitHubAppConfig, sha: string): Promise<Record<string, string>>;
17
33
  /** One file's bytes at a commit, streamed (null when it isn't there). */
18
34
  export declare function blobAt(c: GitHubAppConfig, sha: string, path: string): Promise<Response | null>;
@@ -29,3 +45,4 @@ export declare function githubAuthorizeUrl(clientId: string, redirectUri: string
29
45
  export declare function githubLogin(clientId: string, clientSecret: string, code: string, verifier: string, redirectUri: string): Promise<string>;
30
46
  export declare function s256(verifier: string): Promise<string>;
31
47
  export declare function randomToken(bytes?: number): string;
48
+ export {};
@@ -76,14 +76,61 @@ export async function headSha(c) {
76
76
  throw new Error(`GitHub head of ${c.branch}: ${res.status}`);
77
77
  return (await res.text()).trim();
78
78
  }
79
- /** Every file under data/ and imports/*.mapping.yaml at a commit, from one tarball; statement PDFs by path only (""). */
79
+ /** Files the Worker reads as text: everything under data/ and imports/*.mapping.yaml. */
80
+ export const isDataFile = (p) => p.startsWith("data/") || /^imports\/[^/]+\.mapping\.yaml$/.test(p);
81
+ /** Which tree entries to read as text, and which to list by path only (statement PDFs, never downloaded). */
82
+ export function pickFiles(tree) {
83
+ const text = [];
84
+ const pathOnly = [];
85
+ for (const e of tree) {
86
+ if (e.type !== "blob")
87
+ continue;
88
+ if (isDataFile(e.path))
89
+ text.push(e);
90
+ else if (STATEMENT_PDF_RE.test(e.path))
91
+ pathOnly.push(e.path);
92
+ }
93
+ return { text, pathOnly };
94
+ }
95
+ const GRAPHQL_BATCH = 100;
96
+ /**
97
+ * Every file under data/ and imports/*.mapping.yaml at a commit; statement PDFs by path only ("").
98
+ * One tree listing plus one GraphQL call per 100 files: no tarball, so binary files in the repo
99
+ * (statement PDFs, raw exports) cost the Worker nothing (a tarball of them ran past the Free plan's CPU limit).
100
+ */
80
101
  export async function filesAt(c, sha) {
81
102
  const token = await installationToken(c);
82
- const res = await gh(`/repos/${c.repo}/tarball/${sha}`, token);
83
- if (!res.ok || !res.body)
84
- throw new Error(`GitHub tarball: ${res.status}`);
85
- const { untar } = await import("./tar.js");
86
- return untar(res.body.pipeThrough(new DecompressionStream("gzip")), (p) => p.startsWith("data/") || /^imports\/[^/]+\.mapping\.yaml$/.test(p), (p) => STATEMENT_PDF_RE.test(p));
103
+ const t = await ok(await gh(`/repos/${c.repo}/git/trees/${sha}?recursive=1`, token), "list the data repo's files");
104
+ if (t.truncated)
105
+ throw new Error("GitHub file list: the data repo has too many files for one listing (over 100,000)");
106
+ const { text, pathOnly } = pickFiles(t.tree);
107
+ const out = {};
108
+ for (const p of pathOnly)
109
+ out[p] = "";
110
+ const [owner, name] = c.repo.split("/");
111
+ for (let i = 0; i < text.length; i += GRAPHQL_BATCH) {
112
+ const batch = text.slice(i, i + GRAPHQL_BATCH);
113
+ const fields = batch.map((e, j) => `f${j}: object(oid: ${JSON.stringify(e.sha)}) { ... on Blob { text isTruncated } }`).join("\n");
114
+ const res = await gh(`/graphql`, token, {
115
+ method: "POST",
116
+ body: JSON.stringify({ query: `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`, variables: { owner, name } }),
117
+ });
118
+ const j = await ok(res, "read the data files");
119
+ if (j.errors?.length || !j.data)
120
+ throw new Error(`GitHub read the data files: ${j.errors?.map((e) => e.message).join("; ") ?? "no data"}`);
121
+ for (const [k, e] of batch.entries()) {
122
+ const b = j.data.repository[`f${k}`];
123
+ // Too big for GraphQL's text field: fetch that one file raw.
124
+ out[e.path] = b && b.text !== null && !b.isTruncated ? b.text : await blobText(c.repo, e, token);
125
+ }
126
+ }
127
+ return out;
128
+ }
129
+ async function blobText(repo, e, token) {
130
+ const res = await gh(`/repos/${repo}/git/blobs/${e.sha}`, token, { headers: { Accept: "application/vnd.github.raw+json" } });
131
+ if (!res.ok)
132
+ throw new Error(`GitHub file ${e.path}: ${res.status}`);
133
+ return res.text();
87
134
  }
88
135
  /** One file's bytes at a commit, streamed (null when it isn't there). */
89
136
  export async function blobAt(c, sha, path) {
@@ -19,14 +19,14 @@ import { yamlText } from "../engine/write.js";
19
19
  import { dashboardOf } from "./api.js";
20
20
  import { cardList } from "../modules/cards/index.js";
21
21
  import { cashback, closeOnOrAfter, feeWaiver, lineKind, statements } from "../modules/cards/statements.js";
22
- import { cardsData, STATEMENTS_FILE, termsOf, recordFor } from "../modules/cards/terms.js";
22
+ import { STATEMENTS_FILE, termsOf, recordFor, withBankAmounts } from "../modules/cards/terms.js";
23
23
  import { bestCard } from "./bestcard.js";
24
24
  import { openWalletClient } from "./openwallet.js";
25
25
  const out = (v) => ({ content: [{ type: "text", text: typeof v === "string" ? v : JSON.stringify(v) }] });
26
26
  const fail = (msg) => ({ content: [{ type: "text", text: msg }], isError: true });
27
27
  const INSTRUCTIONS = `ownledger: the owner's personal finance ledger, kept in their private GitHub repo.
28
28
  Amounts are whole numbers in the base currency (see about). Answers are computed here; never add up raw rows yourself when a tool computes it.
29
- Writes: the add_/edit_/void_/set_/remove_ tools only PREVIEW. Show the owner the preview (what, amounts, accounts), wait for their explicit go, then call apply with the preview_id. Never invent an amount, date, account or category: ask. Call rules once before the first write.
29
+ Writes: the add_/edit_/void_/set_/remove_ tools and batch only PREVIEW. Show the owner the preview (what, amounts, accounts), wait for their explicit go, then call apply with the preview_id. Never invent an amount, date, account or category: ask. Call rules once before the first write. For more than ~3 transaction writes at once, use batch: one preview, one go, one commit.
30
30
  Dashboard: when the owner asks to "track", "watch" or "put on my dashboard" something, offer a widget (add_widget), using the categories and accounts from rules.
31
31
  Cards: for "which card should I use", call best_card; statements, cashback and fee waivers come from cards and card_statement.`;
32
32
  const OPENWALLET_LINE = `
@@ -92,18 +92,22 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
92
92
  return fail(`error: ${e.message}`);
93
93
  }
94
94
  };
95
- const preview = async (build) => {
95
+ const preview = async (build, show = 20) => {
96
96
  const s = await snap();
97
97
  const p = build(s.files);
98
98
  const id = await savePending(env, { baseSha: s.sha, files: p.files, message: p.message, summary: p.summary, created: new Date().toISOString() });
99
99
  const shown = [];
100
- for (const t of [...(p.change.addTransactions ?? []), ...(p.change.replaceTransactions ?? [])].slice(0, 20))
100
+ const all = [...(p.change.addTransactions ?? []), ...(p.change.replaceTransactions ?? [])];
101
+ for (const t of all.slice(0, show))
101
102
  shown.push(compactTx(t));
103
+ const b = p;
102
104
  return {
103
105
  preview_id: id,
104
106
  will: p.summary,
105
107
  commit_message: p.message,
106
108
  ...(shown.length ? { transactions: shown } : {}),
109
+ ...(all.length > shown.length ? { not_shown: all.length - shown.length } : {}),
110
+ ...(b.balanceChange ? { balance_change: b.balanceChange } : {}),
107
111
  ...(p.warnings.length ? { warnings: p.warnings.map((w) => w.message) } : {}),
108
112
  next: "Show this to the owner. Only after their explicit go, call apply with this preview_id.",
109
113
  };
@@ -327,6 +331,29 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
327
331
  }));
328
332
  server.registerTool("edit_transaction", { description: "PREVIEW changes to a transaction by id (only the fields given change).", inputSchema: z.object({ id: z.string(), ...txFields, date: z.string().optional(), reason }), annotations: pv }, wrap(async ({ id, reason, ...patch }) => preview((f) => A.editTransaction(f, id, patch, meta(reason)))));
329
333
  server.registerTool("void_transaction", { description: "PREVIEW voiding a transaction (kept in history, excluded everywhere).", inputSchema: z.object({ id: z.string(), reason }), annotations: pv }, wrap(async ({ id, reason }) => preview((f) => A.voidTransaction(f, id, reason, meta(reason)))));
334
+ const batchOp = z.object(txFields).partial().extend({
335
+ op: z.enum(["add", "edit", "void"]),
336
+ id: z.string().optional().describe("edit / void: the transaction id"),
337
+ reason: z.string().trim().max(A.REASON_MAX).optional().describe("optional: this op's own reason, added to the batch's"),
338
+ });
339
+ server.registerTool("batch", {
340
+ description: `PREVIEW many adds, edits and voids as ONE change (writes nothing): one preview, one go, one commit. Use it for more than ~3 writes (e.g. fixes from a statement check). Each op takes the same fields as add_transaction / edit_transaction / void_transaction plus op. Ops run in order; if any op fails, the whole batch is refused and the reply names the op. Max ${A.BATCH_MAX} ops.`,
341
+ inputSchema: z.object({ ops: z.array(batchOp).min(1).max(A.BATCH_MAX), reason }),
342
+ annotations: pv,
343
+ }, wrap(async ({ ops, reason }) => {
344
+ const s = await snap();
345
+ const p = poolOf(s.ledger, dashboardOf(s.files, props.login)?.prefs?.pool, now());
346
+ const list = ops.map((o, i) => {
347
+ if (o.op !== "add" && !o.id)
348
+ throw new A.ActionError(`batch refused: op ${i + 1} (${o.op}) needs an id`);
349
+ if (o.op === "add" && !o.date)
350
+ throw new A.ActionError(`batch refused: op ${i + 1} (add) needs a date`);
351
+ if (o.op === "add" && !o.lines?.length && !o.account && p.on && p.default_account)
352
+ return { ...o, account: p.default_account };
353
+ return o;
354
+ });
355
+ return preview((f) => A.batch(f, list, meta(reason)), A.BATCH_MAX);
356
+ }));
330
357
  const accountFields = {
331
358
  name: z.string(),
332
359
  type: z.string().describe("cash, bank, ewallet, credit_card, bnpl, deposit, savings_goal, gold, fund, stock, etf, crypto, insurance, loan_given, loan_taken, other (or a new one)"),
@@ -410,9 +437,7 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
410
437
  const { ledger } = A.loadForAction(f);
411
438
  if (!ledger.accounts.some((a) => a.id === account))
412
439
  throw new A.ActionError(`no account ${account}`);
413
- const list = cardsData(ledger).statements.filter((x) => !(x.account === account && x.statement_date === statement_date));
414
- list.push({ account, statement_date, amount });
415
- list.sort((x, y) => (x.statement_date < y.statement_date ? -1 : x.statement_date > y.statement_date ? 1 : x.account < y.account ? -1 : 1));
440
+ const list = withBankAmounts(ledger, [{ account, statement_date, amount }]);
416
441
  return A.plan(f, { putFiles: { [STATEMENTS_FILE]: yamlText(list) } }, `Card statement: ${account} ${statement_date}`);
417
442
  })));
418
443
  server.registerTool("add_instalment", { description: "PREVIEW turning a card purchase into a 0% instalment plan (trả góp 0%): each statement then counts only the monthly amount.", inputSchema: z.object({ transaction: z.string().describe("id of the purchase on the card"), count: z.number().int().min(2).max(60), fee: z.number().int().min(0).optional().describe("conversion fee per month, if any"), id: z.string().optional(), name: z.string().optional(), first_statement: z.string().optional().describe("yyyy-mm-dd; default the first statement after the purchase") }), annotations: pv }, wrap(async ({ transaction, count, fee, id, name, first_statement }) => preview((f) => {
@@ -37,7 +37,7 @@ export function sourceFor(env) {
37
37
  return env.DEV_DATA_URL ? devSource(env) : githubSource(env);
38
38
  }
39
39
  // Parsed ledgers live in the isolate's memory (keyed by commit); raw files also in KV, so a cold isolate
40
- // needs no GitHub tarball for a commit it has seen. Both are safe to drop: GitHub is the only store.
40
+ // needs no GitHub reads for a commit it has seen. Both are safe to drop: GitHub is the only store.
41
41
  const memory = new Map();
42
42
  const KV_PREFIX = "ownledger:files2:"; // 2: with statement PDF paths (plan 004)
43
43
  export async function snapshot(env, src, sha) {
@@ -1 +1 @@
1
- export declare const VERSION = "2.1.0";
1
+ export declare const VERSION = "2.2.0";
@@ -1,2 +1,2 @@
1
1
  // generated by scripts/version.mjs
2
- export const VERSION = "2.1.0";
2
+ export const VERSION = "2.2.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ownledger",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Personal finance ledger used through AI chat (MCP). Your data in your own private GitHub repo, served by your own Cloudflare Worker.",
5
5
  "license": "MIT",
6
6
  "author": "phucbm",
@@ -1 +0,0 @@
1
- import{t as e}from"./createLucideIcon-flJrJK2p.js";var t={name:`chevron-down`,size:24,node:[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]};t.node;var n=e(t);export{n as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./createLucideIcon-flJrJK2p.js";var t={name:`chevron-right`,size:24,node:[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]};t.node;var n=e(t);export{n as t};
@@ -1,3 +0,0 @@
1
- /** Minimal streaming tar reader (ustar + pax path headers), enough for GitHub's tarballs. */
2
- /** `keep`: files whose text is returned. `pathOnly`: files returned with "" (their bytes are skipped, never decoded). */
3
- export declare function untar(stream: ReadableStream<Uint8Array>, keep: (path: string) => boolean, pathOnly?: (path: string) => boolean): Promise<Record<string, string>>;
@@ -1,65 +0,0 @@
1
- /** Minimal streaming tar reader (ustar + pax path headers), enough for GitHub's tarballs. */
2
- /** `keep`: files whose text is returned. `pathOnly`: files returned with "" (their bytes are skipped, never decoded). */
3
- export async function untar(stream, keep, pathOnly) {
4
- const out = {};
5
- const reader = stream.getReader();
6
- let buf = new Uint8Array(0);
7
- let done = false;
8
- const need = async (n) => {
9
- while (buf.length < n && !done) {
10
- const r = await reader.read();
11
- if (r.done)
12
- done = true;
13
- else {
14
- const nb = new Uint8Array(buf.length + r.value.length);
15
- nb.set(buf);
16
- nb.set(r.value, buf.length);
17
- buf = nb;
18
- }
19
- }
20
- return buf.length >= n;
21
- };
22
- const take = (n) => {
23
- const v = buf.subarray(0, n);
24
- buf = buf.subarray(n);
25
- return v;
26
- };
27
- const dec = new TextDecoder();
28
- const str = (b) => {
29
- const z = b.indexOf(0);
30
- return dec.decode(z >= 0 ? b.subarray(0, z) : b);
31
- };
32
- let paxPath = null;
33
- for (;;) {
34
- if (!(await need(512)))
35
- break;
36
- const h = take(512);
37
- if (h.every((x) => x === 0))
38
- break;
39
- const name = str(h.subarray(0, 100));
40
- const size = parseInt(str(h.subarray(124, 136)).trim() || "0", 8);
41
- const type = String.fromCharCode(h[156]);
42
- const prefix = str(h.subarray(345, 500));
43
- const padded = Math.ceil(size / 512) * 512;
44
- await need(padded);
45
- const body = take(padded).slice(0, size);
46
- if (type === "x") {
47
- const m = /\d+ path=([^\n]*)\n/.exec(dec.decode(body));
48
- paxPath = m ? m[1] : null;
49
- continue;
50
- }
51
- if (type === "g")
52
- continue;
53
- const full = paxPath ?? (prefix ? `${prefix}/${name}` : name);
54
- paxPath = null;
55
- if (type !== "0" && type !== "\0")
56
- continue;
57
- const rel = full.slice(full.indexOf("/") + 1); // strip "<repo>-<sha>/"
58
- if (keep(rel))
59
- out[rel] = dec.decode(body);
60
- else if (pathOnly?.(rel))
61
- out[rel] = "";
62
- }
63
- reader.cancel().catch(() => undefined);
64
- return out;
65
- }