projectionlab-mcp 1.4.2 → 1.5.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 (116) hide show
  1. package/HOW-IT-WORKS.md +2 -2
  2. package/README.md +4 -2
  3. package/REFERENCE.md +20 -8
  4. package/dist/appBusy.d.ts +3 -0
  5. package/dist/appBusy.js +7 -0
  6. package/dist/appBusy.js.map +1 -0
  7. package/dist/appMap.d.ts +59 -0
  8. package/dist/appMap.js +595 -0
  9. package/dist/appMap.js.map +1 -0
  10. package/dist/appResultsPage.d.ts +31 -0
  11. package/dist/appResultsPage.js +427 -0
  12. package/dist/appResultsPage.js.map +1 -0
  13. package/dist/bootstrap.d.ts +3 -1
  14. package/dist/bootstrap.js +18 -3
  15. package/dist/bootstrap.js.map +1 -1
  16. package/dist/bridge.d.ts +42 -5
  17. package/dist/bridge.js +15 -1
  18. package/dist/bridge.js.map +1 -1
  19. package/dist/changeSummary.d.ts +30 -0
  20. package/dist/changeSummary.js +40 -0
  21. package/dist/changeSummary.js.map +1 -1
  22. package/dist/editAccess.d.ts +6 -3
  23. package/dist/editAccess.js +10 -3
  24. package/dist/editAccess.js.map +1 -1
  25. package/dist/errors.d.ts +1 -1
  26. package/dist/errors.js.map +1 -1
  27. package/dist/extensionBridge.d.ts +27 -6
  28. package/dist/extensionBridge.js +103 -11
  29. package/dist/extensionBridge.js.map +1 -1
  30. package/dist/index.js +19 -0
  31. package/dist/index.js.map +1 -1
  32. package/dist/instructions.d.ts +1 -1
  33. package/dist/instructions.js +1 -1
  34. package/dist/largeOutput.js +2 -23
  35. package/dist/largeOutput.js.map +1 -1
  36. package/dist/planEventTemplates.d.ts +35 -0
  37. package/dist/planEventTemplates.js +177 -0
  38. package/dist/planEventTemplates.js.map +1 -0
  39. package/dist/planReport.d.ts +9 -0
  40. package/dist/planReport.js +902 -0
  41. package/dist/planReport.js.map +1 -0
  42. package/dist/plans.d.ts +2 -0
  43. package/dist/plans.js +6 -0
  44. package/dist/plans.js.map +1 -1
  45. package/dist/printHtml.d.ts +8 -0
  46. package/dist/printHtml.js +144 -0
  47. package/dist/printHtml.js.map +1 -0
  48. package/dist/prompts/index.js +41 -11
  49. package/dist/prompts/index.js.map +1 -1
  50. package/dist/reportCopy.d.ts +16 -0
  51. package/dist/reportCopy.js +55 -0
  52. package/dist/reportCopy.js.map +1 -0
  53. package/dist/resources/appMap.d.ts +2 -0
  54. package/dist/resources/appMap.js +14 -0
  55. package/dist/resources/appMap.js.map +1 -0
  56. package/dist/resources/knowledge.d.ts +1 -1
  57. package/dist/resources/knowledge.js +302 -71
  58. package/dist/resources/knowledge.js.map +1 -1
  59. package/dist/retention.d.ts +8 -0
  60. package/dist/retention.js +35 -0
  61. package/dist/retention.js.map +1 -0
  62. package/dist/settingsReport.d.ts +26 -0
  63. package/dist/settingsReport.js +54 -20
  64. package/dist/settingsReport.js.map +1 -1
  65. package/dist/snapshot.d.ts +12 -0
  66. package/dist/snapshot.js +52 -2
  67. package/dist/snapshot.js.map +1 -1
  68. package/dist/tools/addPlanEvent.d.ts +4 -0
  69. package/dist/tools/addPlanEvent.js +301 -0
  70. package/dist/tools/addPlanEvent.js.map +1 -0
  71. package/dist/tools/clonePlan.d.ts +1 -1
  72. package/dist/tools/clonePlan.js +3 -1
  73. package/dist/tools/clonePlan.js.map +1 -1
  74. package/dist/tools/deletePlan.d.ts +1 -1
  75. package/dist/tools/deletePlan.js +3 -1
  76. package/dist/tools/deletePlan.js.map +1 -1
  77. package/dist/tools/findInApp.d.ts +2 -0
  78. package/dist/tools/findInApp.js +31 -0
  79. package/dist/tools/findInApp.js.map +1 -0
  80. package/dist/tools/listChanges.d.ts +3 -0
  81. package/dist/tools/listChanges.js +147 -0
  82. package/dist/tools/listChanges.js.map +1 -0
  83. package/dist/tools/planReport.d.ts +3 -0
  84. package/dist/tools/planReport.js +62 -0
  85. package/dist/tools/planReport.js.map +1 -0
  86. package/dist/tools/projection.d.ts +3 -0
  87. package/dist/tools/projection.js +381 -0
  88. package/dist/tools/projection.js.map +1 -0
  89. package/dist/tools/removePlanEvent.d.ts +4 -0
  90. package/dist/tools/removePlanEvent.js +196 -0
  91. package/dist/tools/removePlanEvent.js.map +1 -0
  92. package/dist/tools/restore.d.ts +1 -1
  93. package/dist/tools/restore.js +10 -6
  94. package/dist/tools/restore.js.map +1 -1
  95. package/dist/tools/settingsReport.js +23 -4
  96. package/dist/tools/settingsReport.js.map +1 -1
  97. package/dist/tools/snapshots.d.ts +1 -1
  98. package/dist/tools/snapshots.js +54 -31
  99. package/dist/tools/snapshots.js.map +1 -1
  100. package/dist/tools/updateAccount.d.ts +1 -1
  101. package/dist/tools/updateAccount.js +3 -1
  102. package/dist/tools/updateAccount.js.map +1 -1
  103. package/dist/tools/updatePlanEvent.d.ts +1 -1
  104. package/dist/tools/updatePlanEvent.js +3 -1
  105. package/dist/tools/updatePlanEvent.js.map +1 -1
  106. package/dist/tools/updatePlanSection.d.ts +1 -1
  107. package/dist/tools/updatePlanSection.js +3 -1
  108. package/dist/tools/updatePlanSection.js.map +1 -1
  109. package/dist/tools/updatePlanSettings.d.ts +1 -1
  110. package/dist/tools/updatePlanSettings.js +3 -1
  111. package/dist/tools/updatePlanSettings.js.map +1 -1
  112. package/dist/types/wire.d.ts +30 -2
  113. package/dist/types/wire.js +8 -0
  114. package/dist/types/wire.js.map +1 -1
  115. package/package.json +1 -1
  116. package/skills/projectionlab/SKILL.md +139 -17
@@ -0,0 +1,902 @@
1
+ import { listV5Accounts } from "./currentFinances.js";
2
+ import { matchDataModelField } from "./dataModel.js";
3
+ import { exportSections } from "./layout.js";
4
+ import { eventLink, isOverridden } from "./linkedFields.js";
5
+ import { eventDisplayNames, eventLabel, getEvents, milestoneNames, planDisplayName, startLabel, } from "./plans.js";
6
+ import { buildRealAssetBlock } from "./realEstate.js";
7
+ import { redactSecrets } from "./redact.js";
8
+ import { calendarYear, cell, choiceText, formatValue, parseEnabledBy, renderSettingsReport, words, } from "./settingsReport.js";
9
+ import { buildSummary } from "./summary.js";
10
+ /**
11
+ * Fields that shape only how ProjectionLab draws an item, or that identify
12
+ * it internally, and say nothing about the plan's inputs.
13
+ */
14
+ const COSMETIC = new Set([
15
+ "id",
16
+ "kind",
17
+ "icon",
18
+ "customIcon",
19
+ "color",
20
+ "hidden",
21
+ "order",
22
+ "_meta",
23
+ "generated",
24
+ "displaySection",
25
+ "removable",
26
+ "version",
27
+ ]);
28
+ /**
29
+ * Settings the report leaves out because they do not bear on rebuilding the
30
+ * plan elsewhere: how ProjectionLab's own Chance of Success simulation treats
31
+ * an account, an account's RMD rules, and an asset's Modify account switch.
32
+ */
33
+ const OMITTED = new Set(["monteCarloTreatment", "rmdType", "modifyAccount"]);
34
+ /** Plan settings rows the report leaves out, by stored path. */
35
+ const OMITTED_SETTINGS = ["drawdownBlendingStrategy.enabled"];
36
+ /** The plan settings topics the report includes, by settings report title. */
37
+ const SETTINGS_TOPICS = [
38
+ "Growth and inflation",
39
+ "Spending and withdrawals",
40
+ "Tax strategy and Roth conversions",
41
+ "Taxes",
42
+ "Bonds and dividends",
43
+ "Estate",
44
+ ];
45
+ /** Units a numeric field's `<field>Type` sibling can carry. */
46
+ const AMOUNT_BASES = new Set(["$", "today$", "future$", "grow$", "%", "%-earnings"]);
47
+ const MONTHS = [
48
+ "January", "February", "March", "April", "May", "June",
49
+ "July", "August", "September", "October", "November", "December",
50
+ ];
51
+ /**
52
+ * The on-screen names of an account's `withdraw` choices, per the data
53
+ * model's note on accounts.withdraw.
54
+ */
55
+ const WITHDRAW_NAMES = {
56
+ true: "Always",
57
+ false: "Never",
58
+ "when-liquid": "When Liquid",
59
+ after: "Reach Specific Year",
60
+ EWAge: "After Qualified Withdrawal Age",
61
+ };
62
+ /**
63
+ * One plan's inputs and settings as a markdown document to keep, print or
64
+ * share, complete enough for someone to rebuild the plan from: the household,
65
+ * Current Finances, milestones, income, expenses, flows, how the plan treats
66
+ * each account and asset, and every plan setting. Projected outcomes are not
67
+ * part of the export, so the document holds none.
68
+ */
69
+ export function renderPlanReport(data, plan) {
70
+ const sections = exportSections(data);
71
+ const finances = (redactSecrets(sections.currentFinances, { byName: true }) ?? {});
72
+ const safePlan = redactSecrets(plan, { byName: true });
73
+ const summary = buildSummary(data);
74
+ const entries = listV5Accounts(finances);
75
+ const people = new Map();
76
+ for (const person of summary.household?.people ?? []) {
77
+ if (person.name)
78
+ people.set(person.role, person.name);
79
+ }
80
+ people.set("joint", "Joint");
81
+ const items = new Map();
82
+ for (const entry of entries)
83
+ items.set(entry.id, entry.name);
84
+ for (const section of ["accounts", "assets"]) {
85
+ for (const event of getEvents(safePlan[section])) {
86
+ const obj = event;
87
+ if (typeof obj?.id === "string" && typeof obj.name === "string") {
88
+ items.set(obj.id, obj.name);
89
+ }
90
+ }
91
+ }
92
+ const readAt = data?.exportedAt;
93
+ const ctx = {
94
+ milestones: milestoneNames(safePlan),
95
+ milestoneDates: milestoneDates(safePlan, summary.household?.people ?? []),
96
+ people,
97
+ items,
98
+ currentYear: typeof readAt === "number" && Number.isFinite(readAt)
99
+ ? new Date(readAt).getFullYear()
100
+ : new Date().getFullYear(),
101
+ planRates: planRates(safePlan),
102
+ };
103
+ const name = planDisplayName(safePlan);
104
+ const lines = ["# Plan Inputs and Assumptions", ""];
105
+ lines.push(`**Plan:** ${name} `);
106
+ const read = dateText(readAt);
107
+ if (read)
108
+ lines.push(`**Data read:** ${read} `);
109
+ const saved = dateText(safePlan.lastUpdated);
110
+ if (saved)
111
+ lines.push(`**Plan last saved:** ${saved} `);
112
+ lines.push("", "Names in plain text are the labels ProjectionLab 5 shows. Names in *italics* " +
113
+ "describe a field the app shows with no recorded label, and names in `code` " +
114
+ "are stored field names. A plan amount is either in today's dollars, adjusted " +
115
+ "for inflation to the year it applies, or in future dollars, the nominal amount " +
116
+ "in that year, and says which. Current Finances balances are today's figures. " +
117
+ "A milestone's date is worked out from its own definition; one reached by a " +
118
+ "condition such as net worth has no fixed date.", "");
119
+ lines.push(...householdSection(summary.household, finances));
120
+ lines.push(...currentFinancesSection(entries, summary.totalNetWorth, ctx));
121
+ lines.push(...startingConditionsNote(safePlan, ctx));
122
+ lines.push(...milestonesSection(safePlan, ctx));
123
+ lines.push(...cashFlowSection("Income", "income", safePlan, ctx));
124
+ lines.push(...cashFlowSection("Expenses", "expenses", safePlan, ctx));
125
+ lines.push(...cashFlowSection("Flows", "priorities", safePlan, ctx));
126
+ lines.push(...planItemsSection("Accounts", "accounts", safePlan, ctx));
127
+ lines.push(...planItemsSection("Assets", "assets", safePlan, ctx));
128
+ lines.push("## Plan settings", "", "The settings the plan uses, by topic.", "", renderSettingsReport([plan], {
129
+ embedded: true,
130
+ topics: SETTINGS_TOPICS,
131
+ firstPlanYear: ctx.currentYear,
132
+ omit: OMITTED_SETTINGS,
133
+ }).trimEnd(), "");
134
+ return lines.join("\n").trimEnd() + "\n";
135
+ }
136
+ function householdSection(household, finances) {
137
+ const lines = ["## Household", ""];
138
+ const people = household?.people ?? [];
139
+ if (people.length > 0) {
140
+ lines.push("| Name | Born | Life Expectancy |", "| --- | --- | --- |");
141
+ for (const person of people) {
142
+ const born = person.birthYear === undefined
143
+ ? "not set"
144
+ : person.birthMonth !== undefined && MONTHS[person.birthMonth - 1]
145
+ ? `${MONTHS[person.birthMonth - 1]} ${person.birthYear}`
146
+ : String(person.birthYear);
147
+ lines.push(`| ${cell(person.name ?? "not set")} | ${born} | ${person.lifeExpectancy ?? "not set"} |`);
148
+ }
149
+ lines.push("");
150
+ }
151
+ const facts = [];
152
+ const location = finances.location;
153
+ if (location && typeof location === "object") {
154
+ const place = [location.state, location.country].filter((part) => typeof part === "string" && part !== "");
155
+ if (place.length > 0)
156
+ facts.push(`*Location:* ${place.join(", ")}`);
157
+ }
158
+ if (facts.length > 0)
159
+ lines.push(facts.join(" \n"), "");
160
+ if (lines.length === 2)
161
+ lines.push("No household is recorded.", "");
162
+ return lines;
163
+ }
164
+ function currentFinancesSection(entries, netWorth, ctx) {
165
+ const lines = [
166
+ "## Current Finances",
167
+ "",
168
+ `Net worth: ${formatValue(netWorth, "dollars")} (balances and values, less debts).`,
169
+ "",
170
+ ];
171
+ const active = entries.filter((entry) => !entry.archived);
172
+ const recordSkip = (shown) => (path) => shown.includes(path) || path === "archivedOn";
173
+ const accounts = active.filter((entry) => entry.kind === "account");
174
+ if (accounts.length > 0) {
175
+ lines.push("| Name | Type | Owner | Balance | Cost Basis | Details |", "| --- | --- | --- | --- | --- | --- |");
176
+ for (const entry of accounts) {
177
+ const a = entry.account;
178
+ lines.push(row([
179
+ entry.name,
180
+ String(entry.type ?? "not set"),
181
+ ownerText(a.owner, ctx),
182
+ money(a.balance),
183
+ money(a.costBasis),
184
+ detailsText(detailRows("accounts", a, ctx, recordSkip(["name", "type", "owner", "balance", "costBasis"]))),
185
+ ]));
186
+ }
187
+ lines.push("");
188
+ }
189
+ const realAssets = active.filter((entry) => entry.kind === "real-asset");
190
+ if (realAssets.length > 0) {
191
+ lines.push("### Real assets", "", "| Name | Type | Owner | Current Value | Purchase Price | Loans | Details |", "| --- | --- | --- | --- | --- | --- | --- |");
192
+ for (const entry of realAssets) {
193
+ const a = entry.account;
194
+ const block = buildRealAssetBlock(entry, entries);
195
+ const loans = Number(block?.loanBalance ?? 0);
196
+ lines.push(row([
197
+ entry.name,
198
+ String(entry.type ?? "not set"),
199
+ ownerText(a.owner, ctx),
200
+ money(a.value),
201
+ money(a.purchasePrice),
202
+ loans > 0 ? formatValue(loans, "dollars") : "none",
203
+ detailsText(detailRows("assets", a, ctx, recordSkip(["name", "type", "owner", "value", "purchasePrice"]))),
204
+ ]));
205
+ }
206
+ lines.push("");
207
+ }
208
+ const debts = active.filter((entry) => entry.kind === "debt");
209
+ if (debts.length > 0) {
210
+ lines.push("### Debts", "", "| Name | Type | Owner | Balance | Secured By | Details |", "| --- | --- | --- | --- | --- | --- |");
211
+ for (const entry of debts) {
212
+ const a = entry.account;
213
+ const secured = typeof a.securedByAssetId === "string"
214
+ ? (ctx.items.get(a.securedByAssetId) ?? a.securedByAssetId)
215
+ : "none";
216
+ lines.push(row([
217
+ entry.name,
218
+ String(entry.type ?? "not set"),
219
+ ownerText(a.owner, ctx),
220
+ typeof a.balance === "number" ? formatValue(Math.abs(a.balance), "dollars") : "not set",
221
+ secured,
222
+ detailsText(detailRows("accounts", a, ctx, recordSkip(["name", "type", "owner", "balance", "securedByAssetId"]))),
223
+ ]));
224
+ }
225
+ lines.push("");
226
+ }
227
+ const other = active.filter((entry) => !["account", "real-asset", "debt"].includes(entry.kind ?? ""));
228
+ if (other.length > 0) {
229
+ lines.push("### Other records", "", "Records of a kind this report does not recognize, left out of net worth.", "", "| Name | Kind | Details |", "| --- | --- | --- |");
230
+ for (const entry of other) {
231
+ lines.push(row([
232
+ entry.name,
233
+ String(entry.kind ?? "not set"),
234
+ detailsText(detailRows("accounts", entry.account, ctx, recordSkip(["name"]))),
235
+ ]));
236
+ }
237
+ lines.push("");
238
+ }
239
+ if (active.length === 0)
240
+ lines.push("No accounts, assets or debts are recorded.", "");
241
+ return lines;
242
+ }
243
+ /**
244
+ * Plans start from Current Finances. ProjectionLab 5 exports store that as
245
+ * `startingConditionsType: "default"` with empty `startingConditions`, so any
246
+ * other value is called out with whatever conditions the plan stores.
247
+ */
248
+ function startingConditionsNote(plan, ctx) {
249
+ const type = plan.startingConditionsType;
250
+ if (type === undefined || type === "default" || type === "currentFinances")
251
+ return [];
252
+ const lines = [
253
+ "### Starting conditions",
254
+ "",
255
+ `This plan's starting conditions setting is \`${String(type)}\` rather than the ` +
256
+ "usual `default`, so it may start from its own figures instead of Current Finances.",
257
+ "",
258
+ ];
259
+ const conditions = plan.startingConditions;
260
+ if (conditions && typeof conditions === "object" && !Array.isArray(conditions)) {
261
+ const rows = detailRows("startingConditions", conditions, ctx, () => false);
262
+ if (rows.length > 0) {
263
+ lines.push("| Setting | Value |", "| --- | --- |");
264
+ for (const detail of rows)
265
+ lines.push(`| ${labelText(detail)} | ${cell(detail.text)} |`);
266
+ lines.push("");
267
+ }
268
+ }
269
+ return lines;
270
+ }
271
+ function milestonesSection(plan, ctx) {
272
+ const milestones = getEvents(plan.milestones).filter((m) => Boolean(m) && typeof m === "object" && !Array.isArray(m));
273
+ const lines = ["## Milestones", ""];
274
+ if (milestones.length === 0)
275
+ return [...lines, "No milestones.", ""];
276
+ const rows = milestones.map((milestone) => {
277
+ const id = String(milestone.id ?? "");
278
+ const when = criteriaOf(milestone)
279
+ .map((c) => criterionText(c, id, ctx))
280
+ .join("; ");
281
+ const date = ctx.milestoneDates.get(id);
282
+ return [
283
+ typeof milestone.name === "string" ? milestone.name : String(milestone.id ?? "unnamed"),
284
+ date ? whenText(date) : "no fixed date",
285
+ when || "not set",
286
+ detailsText(detailRows("milestones", milestone, ctx, (path) => path === "name" || path === "criteria")),
287
+ ];
288
+ });
289
+ // The Details column is left out when no milestone has any.
290
+ const withDetails = rows.some((cells) => cells[3] !== "");
291
+ lines.push(withDetails
292
+ ? "| Milestone | Date | Reached When | Details |"
293
+ : "| Milestone | Date | Reached When |", withDetails ? "| --- | --- | --- | --- |" : "| --- | --- | --- |");
294
+ for (const cells of rows)
295
+ lines.push(row(withDetails ? cells : cells.slice(0, 3)));
296
+ lines.push("");
297
+ return lines;
298
+ }
299
+ /** The income, expense and flow events of a plan, one table row each. */
300
+ function cashFlowSection(title, section, plan, ctx) {
301
+ const events = getEvents(plan[section]).filter((e) => Boolean(e) && typeof e === "object" && !Array.isArray(e));
302
+ const lines = [`## ${title}`, ""];
303
+ if (section === "priorities") {
304
+ lines.push("Where the plan sends surplus cash, in priority order.", "");
305
+ }
306
+ if (events.length === 0)
307
+ return [...lines, `No ${title.toLowerCase()} events.`, ""];
308
+ // The Start column tells apart events that share a name.
309
+ const names = events.map(eventLabel);
310
+ const flows = section === "priorities";
311
+ const shown = [
312
+ "name",
313
+ "owner",
314
+ "amount",
315
+ "amountType",
316
+ "frequency",
317
+ "start",
318
+ "end",
319
+ "yearlyChange",
320
+ ...(flows ? ["accountId", "desiredContribution"] : []),
321
+ ];
322
+ lines.push(flows
323
+ ? "| Name | Account | Owner | Goal | Amount | Frequency | Start | End | Details |"
324
+ : "| Name | Owner | Amount | Frequency | Start | End | Change Over Time | Details |", flows
325
+ ? "| --- | --- | --- | --- | --- | --- | --- | --- | --- |"
326
+ : "| --- | --- | --- | --- | --- | --- | --- | --- |");
327
+ events.forEach((event, index) => {
328
+ const amount = amountText(event.amount, event.amountType, "dollars");
329
+ // A one-time event happens at its start; a stored end has no effect.
330
+ const timing = [
331
+ timingText(event.start, ctx) ?? "not set",
332
+ event.frequency === "once" ? "n/a (one time)" : (timingText(event.end, ctx) ?? "not set"),
333
+ ];
334
+ const details = detailsText(detailRows(section, event, ctx, (path) => shown.includes(path)));
335
+ if (flows) {
336
+ const account = typeof event.accountId === "string"
337
+ ? (ctx.items.get(event.accountId) ?? event.accountId)
338
+ : "none";
339
+ const goal = choiceText("desiredContribution", event.desiredContribution, matchDataModelField(section, "desiredContribution")?.allowedValues) ?? formatValue(event.desiredContribution);
340
+ lines.push(row([
341
+ names[index],
342
+ account,
343
+ ownerText(event.owner, ctx),
344
+ event.desiredContribution === undefined ? "not set" : goal,
345
+ amount,
346
+ frequencyText(event.frequency),
347
+ ...timing,
348
+ details,
349
+ ]));
350
+ }
351
+ else {
352
+ lines.push(row([
353
+ names[index],
354
+ ownerText(event.owner, ctx),
355
+ amount,
356
+ frequencyText(event.frequency),
357
+ ...timing,
358
+ changeText(event),
359
+ details,
360
+ ]));
361
+ }
362
+ });
363
+ lines.push("");
364
+ return lines;
365
+ }
366
+ /** How the plan treats each account or asset: one table per item. */
367
+ function planItemsSection(title, section, plan, ctx) {
368
+ const events = getEvents(plan[section]).filter((e) => Boolean(e) && typeof e === "object" && !Array.isArray(e));
369
+ const lines = [`## ${title}`, ""];
370
+ if (events.length === 0)
371
+ return [...lines, `No ${title.toLowerCase()} in this plan.`, ""];
372
+ lines.push(section === "accounts"
373
+ ? "How this plan treats each account. An account's balance, owner and other " +
374
+ "details shared by every plan are under Current Finances."
375
+ : "How this plan treats each real asset, including purchases the plan makes " +
376
+ "later. A current asset's value and other details shared by every plan are " +
377
+ "under Current Finances.", "");
378
+ const names = eventDisplayNames(events, ctx.milestones);
379
+ events.forEach((event, index) => {
380
+ const link = eventLink(section, event);
381
+ const skip = (path) => {
382
+ if (path === "name")
383
+ return true;
384
+ if (!link)
385
+ return false;
386
+ if (path === link.linkKey)
387
+ return true;
388
+ // A linked amount's `<field>Type` unit travels with it.
389
+ const top = path.split(".")[0];
390
+ const field = top.endsWith("Type") && link.fields.includes(top.slice(0, -4)) ? top.slice(0, -4) : top;
391
+ return link.fields.includes(field) && !isOverridden(event, field);
392
+ };
393
+ const rows = detailRows(section, event, ctx, skip);
394
+ if (section === "assets")
395
+ rows.sort((a, b) => timingRank(a.path) - timingRank(b.path));
396
+ lines.push(`### ${names[index]}`, "");
397
+ if (!link)
398
+ lines.push("Not in Current Finances: the plan adds this item.", "");
399
+ if (rows.length === 0) {
400
+ lines.push("No plan-specific settings.", "");
401
+ }
402
+ else {
403
+ lines.push("| Setting | Value |", "| --- | --- |");
404
+ for (const detail of rows) {
405
+ lines.push(`| ${labelText(detail)} | ${cell(detail.text)} |`);
406
+ }
407
+ lines.push("");
408
+ }
409
+ });
410
+ return lines;
411
+ }
412
+ /**
413
+ * The fields of a stored object in effect, as labeled values, nested objects
414
+ * flattened to dot paths. A start or end reference reads as its timing, a
415
+ * curve as its points, and a number takes the unit its `<field>Type` sibling
416
+ * names, which is then not listed on its own. Settings switched off, or left
417
+ * unused by the item's own choices, are not listed.
418
+ */
419
+ function detailRows(scope, obj, ctx, skip, prefix = "", root = obj) {
420
+ const rows = [];
421
+ for (const [key, value] of Object.entries(obj)) {
422
+ const path = prefix ? `${prefix}.${key}` : key;
423
+ if (COSMETIC.has(key) || OMITTED.has(key) || skip(path) || value === "" || value === null) {
424
+ continue;
425
+ }
426
+ // ProjectionLab keeps a switched-off setting under its name with a
427
+ // leading underscore, such as `_rothConversions`.
428
+ if (key.startsWith("_") || !inEffect(scope, path, root))
429
+ continue;
430
+ if (typeof value === "string" &&
431
+ AMOUNT_BASES.has(value) &&
432
+ ((key.endsWith("Type") && typeof obj[key.slice(0, -4)] === "number") ||
433
+ (key === "type" && (typeof obj.amount === "number" || Array.isArray(obj.data))))) {
434
+ continue;
435
+ }
436
+ // An object holding { amount, type } or { data, type } keeps the unit in `type`.
437
+ const ownBasis = typeof obj.type === "string" && AMOUNT_BASES.has(obj.type) ? obj.type : undefined;
438
+ let text;
439
+ // A yearly change that stores only its type, such as { type: "none" },
440
+ // has the shape of a timing reference, so it is read first.
441
+ if (key === "yearlyChange" && value && typeof value === "object" && !Array.isArray(value)) {
442
+ text = changeText(obj);
443
+ }
444
+ else if (isTiming(value)) {
445
+ text = timingText(value, ctx);
446
+ }
447
+ else if (isCurve(value) && key === "allocation") {
448
+ // A bond allocation is on the plan timeline: x is the plan year and y
449
+ // a percentage, per the data model note on bondSettings.allocation.
450
+ text = pointsText(value.data, "%", ctx.currentYear);
451
+ }
452
+ else if (isCurve(value)) {
453
+ text = pointsText(value.data, value.type);
454
+ }
455
+ else if (value && typeof value === "object" && !Array.isArray(value)) {
456
+ rows.push(...detailRows(scope, value, ctx, skip, path, root));
457
+ continue;
458
+ }
459
+ else if (Array.isArray(value) && value.every(isPoint) && value.length > 0) {
460
+ text = pointsText(value, key === "data" ? ownBasis : undefined);
461
+ }
462
+ else if (key === "withdraw" && String(value) in WITHDRAW_NAMES) {
463
+ text = WITHDRAW_NAMES[String(value)];
464
+ }
465
+ else if (typeof value === "number") {
466
+ const field = matchDataModelField(scope, path);
467
+ const basis = obj[`${key}Type`] ?? (key === "amount" ? ownBasis : undefined);
468
+ text = amountText(value, basis, field?.units);
469
+ }
470
+ else if (key === "owner" || key === "recipient") {
471
+ text = ownerText(value, ctx);
472
+ }
473
+ else {
474
+ const field = matchDataModelField(scope, path);
475
+ text = choiceText(path, value, field?.allowedValues) ?? formatValue(value, field?.units);
476
+ // "plan" takes the rate the plan settings set, shown beside it.
477
+ const rate = value === "plan" ? ctx.planRates.get(path) : undefined;
478
+ if (rate !== undefined)
479
+ text += ` (${rate})`;
480
+ }
481
+ rows.push({ ...rowLabel(scope, path), path, text: text ?? formatValue(value) });
482
+ }
483
+ return prefix === "" ? distinctLabels(rows) : rows;
484
+ }
485
+ /** An asset's timing first: start, end, then repeat and its settings. */
486
+ function timingRank(path) {
487
+ if (path === "start" || path.startsWith("start."))
488
+ return 0;
489
+ if (path === "end" || path.startsWith("end."))
490
+ return 1;
491
+ if (path === "repeat")
492
+ return 2;
493
+ return path.startsWith("repeat") ? 3 : 4;
494
+ }
495
+ /**
496
+ * Whether a setting is in effect, from its data model `enabledBy`: each
497
+ * controlling field holds the value it needs. A condition naming a choice,
498
+ * such as withdraw "after", is not met when the item stores no choice: the
499
+ * choice that reveals a setting is one the user picked. An on/off control
500
+ * the item does not store, whose default is not recorded, counts as met, as
501
+ * does a condition in another form.
502
+ */
503
+ function inEffect(scope, path, root) {
504
+ for (const condition of parseEnabledBy(matchDataModelField(scope, path)?.enabledBy)) {
505
+ let value = root;
506
+ for (const segment of condition.path.split(".")) {
507
+ value = value && typeof value === "object" ? value[segment] : undefined;
508
+ }
509
+ if (value === undefined && condition.equals === undefined)
510
+ continue;
511
+ const met = condition.equals === undefined ? Boolean(value) : value === condition.equals;
512
+ if (!met)
513
+ return false;
514
+ }
515
+ return true;
516
+ }
517
+ /** Rows that share an on-screen label, told apart by their stored field. */
518
+ function distinctLabels(rows) {
519
+ const counts = new Map();
520
+ for (const row of rows)
521
+ counts.set(row.label, (counts.get(row.label) ?? 0) + 1);
522
+ return rows.map((row) => (counts.get(row.label) ?? 0) > 1 && row.style === "label"
523
+ ? { ...row, label: `${row.label} (${words(row.path.split(".").pop() ?? row.path)})` }
524
+ : row);
525
+ }
526
+ function rowLabel(scope, path) {
527
+ const label = matchDataModelField(scope, path)?.uiLabel;
528
+ if (label)
529
+ return { label, style: "label" };
530
+ const segments = path.split(".");
531
+ if (segments.every((segment) => /^[a-z][a-zA-Z0-9]*$/.test(segment))) {
532
+ const described = segments
533
+ .map((segment, i) => (i === 0 ? words(segment) : lowerFirst(words(segment))))
534
+ .join(": ");
535
+ return { label: described, style: "described" };
536
+ }
537
+ return { label: path, style: "path" };
538
+ }
539
+ /** A later segment of a described name: "Part A premium" reads "part A premium". */
540
+ function lowerFirst(text) {
541
+ return /^[A-Z][a-z]/.test(text) ? text.charAt(0).toLowerCase() + text.slice(1) : text;
542
+ }
543
+ /** A row's label styled by where its name comes from; `escape` for a table cell. */
544
+ function labelText(detail, escape = true) {
545
+ const text = escape ? cell(detail.label) : detail.label;
546
+ if (detail.style === "described")
547
+ return `*${text}*`;
548
+ if (detail.style === "path")
549
+ return `\`${text}\``;
550
+ return text;
551
+ }
552
+ /** Labeled values in one line, left unescaped for `row` to escape. */
553
+ function detailsText(rows) {
554
+ return rows
555
+ .map((detail) => `${labelText(detail, false)}: ${detail.text}`)
556
+ .join("; ");
557
+ }
558
+ /** A start, end or similar reference: { type, value, modifier }. */
559
+ function isTiming(value) {
560
+ if (!value || typeof value !== "object" || Array.isArray(value))
561
+ return false;
562
+ const obj = value;
563
+ return (typeof obj.type === "string" &&
564
+ Object.keys(obj).every((key) => ["type", "value", "modifier", "precision", "years"].includes(key)));
565
+ }
566
+ /** A stored curve: { type?, data: [{ x, y }] }. */
567
+ function isCurve(value) {
568
+ if (!value || typeof value !== "object" || Array.isArray(value))
569
+ return false;
570
+ const obj = value;
571
+ return (Array.isArray(obj.data) &&
572
+ obj.data.every(isPoint) &&
573
+ Object.keys(obj).every((key) => key === "data" || key === "type"));
574
+ }
575
+ function isPoint(value) {
576
+ return (Boolean(value) &&
577
+ typeof value === "object" &&
578
+ !Array.isArray(value) &&
579
+ "x" in value &&
580
+ "y" in value);
581
+ }
582
+ /**
583
+ * A curve's points as "x: y" pairs, its dollar basis stated once at the end.
584
+ * With `firstPlanYear`, x is a plan year and reads as its calendar year.
585
+ */
586
+ function pointsText(points, type, firstPlanYear) {
587
+ if (points.length === 0)
588
+ return "(empty list)";
589
+ const dollars = type === "$" || type === "future$" || type === "today$";
590
+ const text = points
591
+ .map((point) => {
592
+ const { x, y } = point;
593
+ const value = typeof y !== "number"
594
+ ? String(y)
595
+ : dollars
596
+ ? formatValue(y, "dollars")
597
+ : amountText(y, type, undefined);
598
+ return `${String(calendarYear(x, firstPlanYear))}: ${value}`;
599
+ })
600
+ .join(", ");
601
+ if (!dollars)
602
+ return text;
603
+ return `${text} (${type === "today$" ? "in today's dollars" : "in future dollars"})`;
604
+ }
605
+ /**
606
+ * When an event starts or ends, in the words the app names it by, with the
607
+ * date it falls on when that is fixed. A string modifier ("include" or
608
+ * "exclude") says whether the named point's own year belongs to the event,
609
+ * and is shown as stored. `withDate: false` leaves the date out.
610
+ */
611
+ function timingText(reference, ctx, withDate = true) {
612
+ if (!isTiming(reference))
613
+ return undefined;
614
+ const fixed = reference.type === "date" || reference.type === "year";
615
+ const when = timingWhen(reference, ctx);
616
+ let text;
617
+ if (fixed && when) {
618
+ text = whenText(when);
619
+ }
620
+ else if (reference.type === "keyword" && typeof reference.value === "string") {
621
+ text = words(reference.value);
622
+ }
623
+ else {
624
+ text = startLabel(reference, ctx.milestones);
625
+ }
626
+ if (text === undefined)
627
+ return undefined;
628
+ const notes = [];
629
+ if (withDate && when && !fixed)
630
+ notes.push(whenText(when));
631
+ if (reference.modifier === "include")
632
+ notes.push("included");
633
+ if (reference.modifier === "exclude")
634
+ notes.push("excluded");
635
+ return notes.length > 0 ? `${text} (${notes.join(", ")})` : text;
636
+ }
637
+ /** The year, and month when stored, that a start or end reference falls on. */
638
+ function timingWhen(reference, ctx) {
639
+ switch (reference.type) {
640
+ case "date":
641
+ case "year":
642
+ return parseWhen(reference.value, reference.type === "date");
643
+ case "milestone": {
644
+ const base = ctx.milestoneDates.get(String(reference.value));
645
+ if (!base)
646
+ return undefined;
647
+ return typeof reference.modifier === "number"
648
+ ? { ...base, year: base.year + reference.modifier }
649
+ : base;
650
+ }
651
+ case "keyword":
652
+ if (reference.value === "now")
653
+ return { year: ctx.currentYear };
654
+ if (reference.value === "endOfPlan")
655
+ return planEnd(ctx);
656
+ return undefined;
657
+ default:
658
+ return undefined;
659
+ }
660
+ }
661
+ /**
662
+ * The plan's last year: the plan year that holds the household's latest
663
+ * life expectancy, per the data model note on alignment.
664
+ */
665
+ function planEnd(ctx) {
666
+ const years = ["lifeExpectancy", "spouseLifeExpectancy"]
667
+ .map((id) => ctx.milestoneDates.get(id)?.year)
668
+ .filter((year) => year !== undefined);
669
+ return years.length > 0 ? { year: Math.max(...years) } : undefined;
670
+ }
671
+ /** A stored "YYYY-MM-DD" date as its year and, when `withMonth`, its month. */
672
+ function parseWhen(value, withMonth) {
673
+ const match = typeof value === "string" ? /^(\d{4})-(\d{2})/.exec(value) : null;
674
+ if (!match)
675
+ return undefined;
676
+ const year = Number(match[1]);
677
+ const month = Number(match[2]);
678
+ return withMonth && month >= 1 && month <= 12 ? { year, month } : { year };
679
+ }
680
+ /** A year, with the month's short name before it when the month is 1 to 12. */
681
+ function whenText(when) {
682
+ const month = when.month === undefined ? undefined : MONTHS[when.month - 1];
683
+ return month === undefined ? String(when.year) : `${month.slice(0, 3)} ${when.year}`;
684
+ }
685
+ function criteriaOf(milestone) {
686
+ return Array.isArray(milestone.criteria)
687
+ ? milestone.criteria
688
+ : milestone.criteria && typeof milestone.criteria === "object"
689
+ ? [milestone.criteria]
690
+ : [];
691
+ }
692
+ /**
693
+ * When each milestone falls, by id, for the milestones whose single
694
+ * criterion fixes a date: a date, a year, an age, or another such milestone
695
+ * with an optional offset in years. A milestone reached by a condition, such
696
+ * as net worth, or by several criteria, has no fixed date.
697
+ */
698
+ function milestoneDates(plan, people) {
699
+ const byId = new Map();
700
+ for (const milestone of getEvents(plan.milestones)) {
701
+ const obj = milestone;
702
+ if (obj && typeof obj === "object" && typeof obj.id === "string")
703
+ byId.set(obj.id, obj);
704
+ }
705
+ const dates = new Map();
706
+ const visiting = new Set();
707
+ const resolve = (id) => {
708
+ if (dates.has(id))
709
+ return dates.get(id);
710
+ const milestone = byId.get(id);
711
+ if (!milestone || visiting.has(id))
712
+ return undefined;
713
+ visiting.add(id);
714
+ const criteria = criteriaOf(milestone);
715
+ const when = criteria.length === 1 ? criterionWhen(criteria[0], id) : undefined;
716
+ visiting.delete(id);
717
+ if (when)
718
+ dates.set(id, when);
719
+ return when;
720
+ };
721
+ const criterionWhen = (c, id) => {
722
+ if (!c || typeof c !== "object")
723
+ return undefined;
724
+ switch (c.type) {
725
+ case "date":
726
+ case "year":
727
+ return parseWhen(c.value, c.type === "date");
728
+ case "milestone": {
729
+ const base = resolve(String(c.value));
730
+ if (!base)
731
+ return undefined;
732
+ return typeof c.modifier === "number" ? { ...base, year: base.year + c.modifier } : base;
733
+ }
734
+ case "age": {
735
+ const age = Number(c.years ?? c.value);
736
+ const person = people.find((p) => p.role === criterionOwner(c, id));
737
+ if (!Number.isFinite(age) || person?.birthYear === undefined)
738
+ return undefined;
739
+ return { year: person.birthYear + age, month: person.birthMonth };
740
+ }
741
+ default:
742
+ return undefined;
743
+ }
744
+ };
745
+ for (const id of byId.keys())
746
+ resolve(id);
747
+ return dates;
748
+ }
749
+ /**
750
+ * Whose age an age criterion counts: its stored owner, or for the built-in
751
+ * life expectancy milestones, which store none, the person the id names.
752
+ */
753
+ function criterionOwner(criterion, milestoneId) {
754
+ if (typeof criterion.owner === "string" && criterion.owner !== "")
755
+ return criterion.owner;
756
+ return milestoneId.startsWith("spouse") ? "spouse" : "me";
757
+ }
758
+ /**
759
+ * The rate an account choice of "plan" takes from the plan settings, by
760
+ * choice field: the Stock Growth Rate and Stock Dividend Yield under Growth
761
+ * Rates, per the data model notes on investmentGrowthType and dividendType.
762
+ * A plan whose rates are not fixed points to its settings instead.
763
+ */
764
+ function planRates(plan) {
765
+ const rates = new Map();
766
+ const variables = plan.variables;
767
+ if (!variables || typeof variables !== "object")
768
+ return rates;
769
+ const fixed = variables.assumptionsMode === undefined || variables.assumptionsMode === "fixed";
770
+ const sources = [
771
+ ["investmentGrowthType", "investmentReturn"],
772
+ ["dividendType", "dividendRate"],
773
+ ];
774
+ for (const [field, source] of sources) {
775
+ const value = variables[source];
776
+ rates.set(field, fixed && typeof value === "number"
777
+ ? formatValue(value, "percentage points")
778
+ : "see Growth and inflation under Plan settings");
779
+ }
780
+ return rates;
781
+ }
782
+ /** One criterion of the milestone `milestoneId` in words. */
783
+ function criterionText(criterion, milestoneId, ctx) {
784
+ if (!criterion || typeof criterion !== "object" || Array.isArray(criterion)) {
785
+ return formatValue(criterion);
786
+ }
787
+ const c = criterion;
788
+ switch (c.type) {
789
+ case "age": {
790
+ const age = c.years ?? c.value;
791
+ const who = ctx.people.get(criterionOwner(c, milestoneId));
792
+ if (age === undefined)
793
+ return "age not set";
794
+ return who ? `${who} at age ${String(age)}` : `age ${String(age)}`;
795
+ }
796
+ case "netWorth":
797
+ return `Net worth reaches ${amountText(c.value, c.valueType, "dollars")}`;
798
+ case "totalDebt":
799
+ return `Total debt reaches ${amountText(c.value, c.valueType, "dollars")}`;
800
+ case "date":
801
+ case "year":
802
+ return "On a set date";
803
+ default:
804
+ return timingText({ type: c.type, value: c.value, ...(c.modifier !== undefined ? { modifier: c.modifier } : {}) }, ctx, false) ?? formatValue(c.value);
805
+ }
806
+ }
807
+ /** A number in the unit its basis names: a percent or dollars. */
808
+ function amountText(value, basis, units) {
809
+ if (value === undefined)
810
+ return "not set";
811
+ if (typeof value !== "number")
812
+ return formatValue(value, units);
813
+ switch (basis) {
814
+ case "%":
815
+ return formatValue(value, "percentage points");
816
+ case "$":
817
+ case "future$":
818
+ return `${formatValue(value, "dollars")} in future dollars`;
819
+ case "%-earnings":
820
+ return `${formatValue(value, "percentage points")} of earnings`;
821
+ case "today$":
822
+ return `${formatValue(value, "dollars")} in today's dollars`;
823
+ case "grow$":
824
+ return `${formatValue(value, "dollars")}, grown by its Change Over Time setting`;
825
+ default:
826
+ return formatValue(value, units);
827
+ }
828
+ }
829
+ function money(value) {
830
+ return value === undefined ? "not set" : formatValue(value, "dollars");
831
+ }
832
+ function ownerText(owner, ctx) {
833
+ if (typeof owner !== "string" || owner === "")
834
+ return "not set";
835
+ return ctx.people.get(owner) ?? owner;
836
+ }
837
+ function frequencyText(frequency) {
838
+ return typeof frequency === "string" && frequency !== "" ? words(frequency) : "not set";
839
+ }
840
+ /**
841
+ * An event's Change Over Time setting. A one-time event has none unless its
842
+ * amount grows ("grow$"), per the yearlyChange.type note in the data model.
843
+ */
844
+ function changeText(event) {
845
+ const change = event.yearlyChange;
846
+ if (!change || typeof change !== "object")
847
+ return "not set";
848
+ if (event.frequency === "once" && event.amountType !== "grow$")
849
+ return "n/a (one time)";
850
+ // An amount the plan does not store is unknown, not zero.
851
+ const percent = typeof change.amount === "number"
852
+ ? formatValue(change.amount, "percentage points")
853
+ : "percent not set";
854
+ let text;
855
+ switch (change.type) {
856
+ case "none":
857
+ text = "None";
858
+ break;
859
+ case "match-inflation":
860
+ text = "Match inflation";
861
+ break;
862
+ case "inflation+":
863
+ text = `Inflation + ${percent}`;
864
+ break;
865
+ case "inflation-":
866
+ text = `Inflation - ${percent}`;
867
+ break;
868
+ case "custom": {
869
+ const custom = change.custom;
870
+ text =
871
+ custom && Array.isArray(custom.data)
872
+ ? `Advanced: ${pointsText(custom.data, custom.type)}`
873
+ : "Advanced";
874
+ break;
875
+ }
876
+ default:
877
+ text =
878
+ typeof change.type === "string"
879
+ ? typeof change.amount === "number"
880
+ ? `${words(change.type)} ${percent} per year`
881
+ : `${words(change.type)}, percent not set`
882
+ : "not set";
883
+ }
884
+ if (change.limitEnabled === true && typeof change.limit === "number") {
885
+ text += `, maximum ${amountText(change.limit, change.limitType, "dollars")}`;
886
+ }
887
+ return text;
888
+ }
889
+ /** A timestamp as a local YYYY-MM-DD date, the day the user saw it happen. */
890
+ function dateText(value) {
891
+ if (typeof value !== "number" || !Number.isFinite(value))
892
+ return undefined;
893
+ const date = new Date(value);
894
+ if (Number.isNaN(date.getTime()))
895
+ return undefined;
896
+ const pad = (n) => String(n).padStart(2, "0");
897
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
898
+ }
899
+ function row(cells) {
900
+ return `| ${cells.map((text) => cell(text)).join(" | ")} |`;
901
+ }
902
+ //# sourceMappingURL=planReport.js.map