shelfready 0.0.0-stage → 0.1.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.
Files changed (49) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +77 -2
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +272 -0
  6. package/dist/core/appPrivacy.d.ts +20 -0
  7. package/dist/core/appPrivacy.js +73 -0
  8. package/dist/core/check.d.ts +15 -0
  9. package/dist/core/check.js +151 -0
  10. package/dist/core/checklist.d.ts +44 -0
  11. package/dist/core/checklist.js +176 -0
  12. package/dist/core/facts.d.ts +103 -0
  13. package/dist/core/facts.js +97 -0
  14. package/dist/core/knowledge.d.ts +29 -0
  15. package/dist/core/knowledge.js +35 -0
  16. package/dist/core/legalView.d.ts +6 -0
  17. package/dist/core/legalView.js +39 -0
  18. package/dist/core/migrate.d.ts +24 -0
  19. package/dist/core/migrate.js +66 -0
  20. package/dist/core/online.d.ts +20 -0
  21. package/dist/core/online.js +76 -0
  22. package/dist/core/pages.d.ts +17 -0
  23. package/dist/core/pages.js +124 -0
  24. package/dist/core/scan.d.ts +55 -0
  25. package/dist/core/scan.js +215 -0
  26. package/dist/index.d.ts +10 -0
  27. package/dist/index.js +11 -0
  28. package/knowledge/sdks/adaptysdk-ios.yaml +29 -0
  29. package/knowledge/sdks/alamofire.yaml +15 -0
  30. package/knowledge/sdks/amplitude-swift.yaml +32 -0
  31. package/knowledge/sdks/analytics-swift.yaml +39 -0
  32. package/knowledge/sdks/bugsnag-cocoa.yaml +42 -0
  33. package/knowledge/sdks/dd-sdk-ios.yaml +60 -0
  34. package/knowledge/sdks/facebook-ios-sdk.yaml +120 -0
  35. package/knowledge/sdks/firebase-ios-sdk.yaml +115 -0
  36. package/knowledge/sdks/googlesignin-ios.yaml +65 -0
  37. package/knowledge/sdks/kingfisher.yaml +15 -0
  38. package/knowledge/sdks/lottie-ios.yaml +18 -0
  39. package/knowledge/sdks/mixpanel-swift.yaml +19 -0
  40. package/knowledge/sdks/onesignal-ios-sdk.yaml +122 -0
  41. package/knowledge/sdks/posthog-ios.yaml +43 -0
  42. package/knowledge/sdks/purchases-ios.yaml +24 -0
  43. package/knowledge/sdks/realm-swift.yaml +24 -0
  44. package/knowledge/sdks/sdwebimage.yaml +15 -0
  45. package/knowledge/sdks/sentry-cocoa.yaml +32 -0
  46. package/knowledge/sdks/supabase-swift.yaml +19 -0
  47. package/knowledge/sdks/superwall-ios.yaml +22 -0
  48. package/knowledge/sdks/swiftsdk.yaml +29 -0
  49. package/package.json +60 -4
@@ -0,0 +1,39 @@
1
+ import { impressumLines, needsImpressum, pageURL } from "./facts.js";
2
+ /** Escape a string for a Swift string literal. */
3
+ const swift = (s) => JSON.stringify(s);
4
+ /**
5
+ * A SwiftUI `LegalView` so the Impressum and links are reachable inside the app,
6
+ * which German law expects for commercial apps (the App Store listing alone isn't enough).
7
+ */
8
+ export function legalView(facts) {
9
+ const p = facts.publisher;
10
+ const lines = p.trader
11
+ ? impressumLines(facts).map(({ label, value }) => (label ? `${label}: ${value}` : value))
12
+ : [`${p.brand || p.name} ist ein privates, nicht-kommerzielles Projekt.`, p.email];
13
+ const impressumSection = needsImpressum(facts)
14
+ ? `
15
+ Section("Impressum") {
16
+ ${lines.map((l) => ` Text(${swift(l)})`).join("\n")}
17
+ }
18
+ `
19
+ : "";
20
+ return `// Generated by \`shelf pages --swiftui\` from shelfready.yaml. Regenerate instead of editing.
21
+ import SwiftUI
22
+
23
+ struct LegalView: View {
24
+ var body: some View {
25
+ List {${impressumSection}
26
+ Section("Links") {
27
+ Link("Privacy policy", destination: URL(string: ${swift(pageURL(facts, "privacy"))})!)
28
+ Link("Support", destination: URL(string: ${swift(pageURL(facts, "support"))})!)${needsImpressum(facts) ? `\n Link("Impressum (web)", destination: URL(string: ${swift(pageURL(facts, "impressum"))})!)` : ""}
29
+ }
30
+ }
31
+ .navigationTitle(${swift(needsImpressum(facts) ? "Impressum & Privacy" : "Privacy & Support")})
32
+ }
33
+ }
34
+
35
+ #Preview {
36
+ NavigationStack { LegalView() }
37
+ }
38
+ `;
39
+ }
@@ -0,0 +1,24 @@
1
+ import { type Document } from "yaml";
2
+ /**
3
+ * Schema versions of shelfready.yaml.
4
+ *
5
+ * When the shelf library changes the file format, add a migration here and bump CURRENT_VERSION.
6
+ * Migrations edit the YAML document in place, so the developer's comments, order and wording survive.
7
+ * `shelf migrate` writes the result; every other command migrates in memory and warns.
8
+ */
9
+ export declare const CURRENT_VERSION = 2;
10
+ export interface MigrationResult {
11
+ doc: Document;
12
+ from: number;
13
+ to: number;
14
+ notes: string[];
15
+ /** The migrated file, in the original's list style so the diff shows only real changes. */
16
+ text: string;
17
+ }
18
+ /** True if block lists are indented under their key (`key:\n - x`), false for `key:\n- x`. */
19
+ export declare function usesIndentedLists(text: string): boolean;
20
+ export declare class NewerSchemaError extends Error {
21
+ }
22
+ /** Parse shelfready.yaml text and bring it up to CURRENT_VERSION without touching the file. */
23
+ export declare function migrateText(text: string, source?: string): MigrationResult;
24
+ export declare function migrateFile(path: string): MigrationResult;
@@ -0,0 +1,66 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { parseDocument } from "yaml";
3
+ /**
4
+ * Schema versions of shelfready.yaml.
5
+ *
6
+ * When the shelf library changes the file format, add a migration here and bump CURRENT_VERSION.
7
+ * Migrations edit the YAML document in place, so the developer's comments, order and wording survive.
8
+ * `shelf migrate` writes the result; every other command migrates in memory and warns.
9
+ */
10
+ export const CURRENT_VERSION = 2;
11
+ const setIfMissing = (doc, path, value, note, notes) => {
12
+ if (!doc.hasIn(path)) {
13
+ doc.setIn(path, doc.createNode(value));
14
+ notes.push(note);
15
+ }
16
+ };
17
+ const MIGRATIONS = [
18
+ {
19
+ to: 2,
20
+ summary: "Voice (I/we), support.askFor, explicit DE/AT trader fields",
21
+ apply(doc) {
22
+ const notes = [];
23
+ setIfMissing(doc, ["publisher", "voice"], "we", 'publisher.voice: "we". Set it to "I" if you work alone.', notes);
24
+ setIfMissing(doc, ["support", "faq"], [], "support.faq: []. Add the questions from your current support page.", notes);
25
+ setIfMissing(doc, ["support", "askFor"], "your device model and iOS version", 'support.askFor: what bug reports should include, e.g. "your iPhone model and iOS version".', notes);
26
+ const country = String(doc.getIn(["publisher", "country"]) ?? "").toUpperCase();
27
+ if (doc.getIn(["publisher", "trader"]) === true && (country === "DE" || country === "AT")) {
28
+ for (const field of ["phone", "contactURL", "vatId", "legalForm", "representative"]) {
29
+ setIfMissing(doc, ["publisher", field], "", `publisher.${field}: "" (Impressum detail for DE/AT traders).`, notes);
30
+ }
31
+ setIfMissing(doc, ["publisher", "register"], { court: "", number: "" }, "publisher.register: court and number for companies.", notes);
32
+ }
33
+ return notes;
34
+ },
35
+ },
36
+ ];
37
+ /** True if block lists are indented under their key (`key:\n - x`), false for `key:\n- x`. */
38
+ export function usesIndentedLists(text) {
39
+ const m = /^( *)[^\s#-][^:\n]*:\s*\n( *)- /m.exec(text);
40
+ return m ? m[2].length > m[1].length : true;
41
+ }
42
+ export class NewerSchemaError extends Error {
43
+ }
44
+ /** Parse shelfready.yaml text and bring it up to CURRENT_VERSION without touching the file. */
45
+ export function migrateText(text, source = "shelfready.yaml") {
46
+ const doc = parseDocument(text);
47
+ if (doc.errors.length)
48
+ throw new Error(`${source}: ${doc.errors[0].message}`);
49
+ const from = Number(doc.get("version"));
50
+ if (!Number.isInteger(from) || from < 1)
51
+ throw new Error(`${source}: missing or invalid version`);
52
+ if (from > CURRENT_VERSION) {
53
+ throw new NewerSchemaError(`${source} uses schema version ${from}, but this shelf only knows up to ${CURRENT_VERSION}. Update shelf.`);
54
+ }
55
+ const notes = [];
56
+ for (const m of MIGRATIONS.filter((m) => m.to > from).sort((a, b) => a.to - b.to)) {
57
+ const changes = m.apply(doc);
58
+ doc.set("version", m.to);
59
+ notes.push(`v${m.to}: ${m.summary}`, ...changes.map((c) => ` - ${c}`));
60
+ }
61
+ const text2 = from === CURRENT_VERSION ? text : doc.toString({ lineWidth: 100, indentSeq: usesIndentedLists(text) });
62
+ return { doc, from, to: CURRENT_VERSION, notes, text: text2 };
63
+ }
64
+ export function migrateFile(path) {
65
+ return migrateText(readFileSync(path, "utf8"), path);
66
+ }
@@ -0,0 +1,20 @@
1
+ import type { Finding } from "./check.js";
2
+ import { type Facts } from "./facts.js";
3
+ type FetchLike = (url: string, init?: {
4
+ signal?: AbortSignal;
5
+ redirect?: "follow";
6
+ headers?: Record<string, string>;
7
+ }) => Promise<{
8
+ ok: boolean;
9
+ status: number;
10
+ url: string;
11
+ text(): Promise<string>;
12
+ }>;
13
+ /** Visible text of an HTML page, normalised so typographic quotes and entities compare equal. */
14
+ export declare function pageText(html: string): string;
15
+ /**
16
+ * `shelf check --online`: are the pages live, and do they show what shelfready.yaml says?
17
+ * Catches dead URLs (App Review rejects them) and stale deployments.
18
+ */
19
+ export declare function checkOnline(facts: Facts, fetchFn?: FetchLike, timeoutMs?: number): Promise<Finding[]>;
20
+ export {};
@@ -0,0 +1,76 @@
1
+ import { needsImpressum, pageURL } from "./facts.js";
2
+ /** Visible text of an HTML page, normalised so typographic quotes and entities compare equal. */
3
+ export function pageText(html) {
4
+ return html
5
+ .replace(/<(script|style)[\s\S]*?<\/\1>/gi, " ")
6
+ .replace(/<[^>]+>/g, " ")
7
+ .replace(/&nbsp;/g, " ")
8
+ .replace(/&amp;/g, "&")
9
+ .replace(/&quot;/g, '"')
10
+ .replace(/&#39;|&#x27;|&rsquo;|&lsquo;|[‘’]/g, "'")
11
+ .replace(/&ldquo;|&rdquo;|[“”]/g, '"')
12
+ .replace(/&#8250;|&rsaquo;/g, "›")
13
+ .replace(/&hellip;|&#8230;/g, "…")
14
+ .replace(/&[a-z]+;|&#\d+;/gi, " ")
15
+ .replace(/\s+/g, " ")
16
+ .trim()
17
+ .toLowerCase();
18
+ }
19
+ /** Markdown inline formatting removed, for matching against rendered text. */
20
+ const plain = (md) => pageText(md.replace(/[*_`]/g, "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1"));
21
+ /**
22
+ * `shelf check --online`: are the pages live, and do they show what shelfready.yaml says?
23
+ * Catches dead URLs (App Review rejects them) and stale deployments.
24
+ */
25
+ export async function checkOnline(facts, fetchFn = fetch, timeoutMs = 10_000) {
26
+ const findings = [];
27
+ const add = (level, rule, message) => findings.push({ level, rule, message });
28
+ if (!facts.pages.baseURL) {
29
+ add("error", "online.baseURL", "pages.baseURL is empty, so there is nothing to check online.");
30
+ return findings;
31
+ }
32
+ const pages = [
33
+ {
34
+ name: "privacy",
35
+ expect: [
36
+ { text: facts.app.name, what: "the app name" },
37
+ { text: facts.pages.policyUpdated, what: `the policy date ${facts.pages.policyUpdated}` },
38
+ ],
39
+ },
40
+ {
41
+ name: "support",
42
+ expect: [
43
+ { text: facts.publisher.email, what: "the contact email" },
44
+ ...facts.support.faq.map((f) => ({ text: f.q, what: `FAQ "${f.q}"` })),
45
+ ],
46
+ },
47
+ ];
48
+ if (needsImpressum(facts))
49
+ pages.push({ name: "impressum", expect: [{ text: facts.publisher.email, what: "the contact email" }] });
50
+ await Promise.all(pages.map(async ({ name, expect }) => {
51
+ const url = pageURL(facts, name);
52
+ if (!/^https:\/\//.test(url))
53
+ return add("error", `online.${name}`, `${name} URL must be absolute https, got "${url}".`);
54
+ const controller = new AbortController();
55
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
56
+ try {
57
+ const res = await fetchFn(url, { signal: controller.signal, redirect: "follow", headers: { "user-agent": "shelfready-check" } });
58
+ if (!res.ok)
59
+ return add("error", `online.${name}`, `${url} returned HTTP ${res.status}.`);
60
+ const text = pageText(await res.text());
61
+ const missing = expect.filter((e) => !text.includes(plain(e.text))).map((e) => e.what);
62
+ if (missing.length)
63
+ add("warn", `online.${name}.stale`, `${url} is live but doesn't show ${missing.join(", ")}. Redeploy the generated page?`);
64
+ else
65
+ add("ok", `online.${name}`, `${url} is live and up to date.`);
66
+ }
67
+ catch (e) {
68
+ const reason = e.name === "AbortError" ? `no response within ${timeoutMs / 1000}s` : e.message;
69
+ add("error", `online.${name}`, `${url} unreachable: ${reason}.`);
70
+ }
71
+ finally {
72
+ clearTimeout(timer);
73
+ }
74
+ }));
75
+ return findings.sort((a, b) => a.rule.localeCompare(b.rule));
76
+ }
@@ -0,0 +1,17 @@
1
+ import { type Facts } from "./facts.js";
2
+ /**
3
+ * Page templates. Draft wording, generalised from the Half Batch site (kipple).
4
+ * Must be reviewed by a lawyer before ShelfReady is offered to others; output is not legal advice.
5
+ */
6
+ export interface Page {
7
+ file: string;
8
+ title: string;
9
+ /** Path relative to the app's base URL, e.g. "privacy/". */
10
+ path: string;
11
+ markdown: string;
12
+ }
13
+ export declare function renderPages(facts: Facts): Page[];
14
+ export declare function privacyPolicy(facts: Facts): Page;
15
+ export declare function supportPage(facts: Facts): Page;
16
+ /** German-language Impressum (§ 5 DDG for DE, § 5 ECG for AT), with an English notice. */
17
+ export declare function impressum(facts: Facts): Page;
@@ -0,0 +1,124 @@
1
+ import { CATEGORY, PURPOSE } from "./appPrivacy.js";
2
+ import { impressumLines, needsImpressum, pageURL } from "./facts.js";
3
+ import { lookup, sdkCollects } from "./knowledge.js";
4
+ const CATEGORY_LABEL = {
5
+ NAME: "Name", EMAIL_ADDRESS: "Email address", PHONE_NUMBER: "Phone number", PHYSICAL_ADDRESS: "Physical address",
6
+ OTHER_CONTACT_INFO: "Other contact info", HEALTH: "Health", FITNESS: "Fitness", PAYMENT_INFORMATION: "Payment info",
7
+ CREDIT_AND_FRAUD: "Credit info", OTHER_FINANCIAL_INFO: "Other financial info", PRECISE_LOCATION: "Precise location",
8
+ COARSE_LOCATION: "Coarse location", SENSITIVE_INFO: "Sensitive info", CONTACTS: "Contacts",
9
+ EMAILS_OR_TEXT_MESSAGES: "Emails or text messages", PHOTOS_OR_VIDEOS: "Photos or videos", AUDIO: "Audio data",
10
+ GAMEPLAY_CONTENT: "Gameplay content", CUSTOMER_SUPPORT: "Customer support", OTHER_USER_CONTENT: "Other user content",
11
+ BROWSING_HISTORY: "Browsing history", SEARCH_HISTORY: "Search history", USER_ID: "User ID", DEVICE_ID: "Device ID",
12
+ PURCHASE_HISTORY: "Purchase history", PRODUCT_INTERACTION: "Product interaction", ADVERTISING_DATA: "Advertising data",
13
+ OTHER_USAGE_DATA: "Other usage data", CRASH_DATA: "Crash data", PERFORMANCE_DATA: "Performance data",
14
+ OTHER_DIAGNOSTIC_DATA: "Other diagnostic data", OTHER_DATA: "Other data",
15
+ };
16
+ const PURPOSE_LABEL = {
17
+ THIRD_PARTY_ADVERTISING: "third-party advertising", DEVELOPERS_ADVERTISING: "the developer's own advertising",
18
+ ANALYTICS: "analytics", PRODUCT_PERSONALIZATION: "personalisation", APP_FUNCTIONALITY: "making the app work",
19
+ OTHER_PURPOSES: "other purposes",
20
+ };
21
+ /** First-person words for the publisher's voice. */
22
+ function voice(facts) {
23
+ return facts.publisher.voice === "I"
24
+ ? { We: "I", we: "I", us: "me", our: "my" }
25
+ : { We: "We", we: "we", us: "us", our: "our" };
26
+ }
27
+ export function renderPages(facts) {
28
+ const pages = [privacyPolicy(facts), supportPage(facts)];
29
+ // A shared Impressum (impressumURL) lives elsewhere, e.g. on the studio site.
30
+ if (needsImpressum(facts) && !facts.pages.impressumURL)
31
+ pages.push(impressum(facts));
32
+ return pages;
33
+ }
34
+ function by(facts) {
35
+ return facts.publisher.brand || facts.publisher.name || "the developer";
36
+ }
37
+ function contactLine(facts) {
38
+ const p = facts.publisher;
39
+ const who = p.trader && p.name ? `${p.name}${p.brand ? ` (${p.brand})` : ""}` : by(facts);
40
+ const impressumLink = needsImpressum(facts) ? `, see the [Impressum](${pageURL(facts, "impressum")})` : "";
41
+ return `${who}, [${p.email}](mailto:${p.email})${impressumLink}`;
42
+ }
43
+ export function privacyPolicy(facts) {
44
+ const { app, data } = facts;
45
+ const w = voice(facts);
46
+ const none = data.collected.length === 0 && !data.tracking;
47
+ const lines = [`# ${app.name} privacy policy`, "", `_Last updated: ${facts.pages.policyUpdated}_`, ""];
48
+ lines.push(app.tagline ? `${app.name} is ${app.tagline}, made by ${by(facts)}.` : `${app.name} is an app by ${by(facts)}.`, "");
49
+ lines.push("## The short version", "");
50
+ if (none) {
51
+ lines.push(`${app.name} doesn't collect, store or share any of your data. There are no accounts, no analytics, no ads and no tracking.`, "");
52
+ }
53
+ else {
54
+ lines.push(`${app.name} collects the data listed below${data.tracking ? ", and some of it is used to track you across apps and websites owned by other companies" : ", and none of it is used to track you"}.`, "");
55
+ }
56
+ for (const note of facts.privacyNotes)
57
+ lines.push(`## ${note.heading}`, "", note.body.trim(), "");
58
+ lines.push(`## Data ${w.we} collect`, "");
59
+ if (data.collected.length === 0) {
60
+ const noSDKs = data.packages.length === 0 ? ` ${app.name} contains no third-party SDKs, analytics or crash-reporting services.` : "";
61
+ lines.push(`None.${noSDKs || ` ${app.name} doesn't collect personal data.`}`);
62
+ lines.push("If you've agreed to share analytics with app developers in iOS Settings, Apple may give the developer anonymous crash reports.", "");
63
+ }
64
+ else {
65
+ lines.push("| Data | Used for | Linked to you | Used to track you |", "|---|---|---|---|");
66
+ for (const item of data.collected) {
67
+ const category = CATEGORY[item.type];
68
+ const label = (category && CATEGORY_LABEL[category]) ?? item.type;
69
+ const purposes = item.purposes.map((p) => PURPOSE_LABEL[PURPOSE[p] ?? ""] ?? p).join(", ") || "—";
70
+ lines.push(`| ${label} | ${purposes} | ${item.linked ? "Yes" : "No"} | ${item.tracking ? "Yes" : "No"} |`);
71
+ }
72
+ lines.push("");
73
+ }
74
+ const services = data.packages.map((p) => lookup(p)).filter((e) => e !== undefined && sdkCollects(e).length > 0);
75
+ if (services.length) {
76
+ lines.push("## Third-party services", "", `${app.name} includes these services, which collect data as described in their own privacy manifests:`, "");
77
+ for (const s of services) {
78
+ const labels = [...new Set(sdkCollects(s).map((c) => CATEGORY_LABEL[CATEGORY[c.type] ?? ""] ?? c.type))];
79
+ lines.push(`- **${s.name}** (${s.vendor}): ${labels.join(", ").toLowerCase()}`);
80
+ }
81
+ lines.push("");
82
+ }
83
+ if (facts.pages.sitePrivacyURL) {
84
+ lines.push("## This website", "", `For the website itself, see the [website privacy notice](${facts.pages.sitePrivacyURL}).`, "");
85
+ }
86
+ lines.push("## Your rights", "", none
87
+ ? `Because ${app.name} doesn't collect personal data, there's nothing held about you to access, correct or delete. If you have questions about your rights under the GDPR, contact ${w.us} below.`
88
+ : `Under the GDPR you can ask to access, correct or delete your personal data, restrict or object to its use, and complain to a data protection authority. Contact ${w.us} below to make a request.`, "", "## Children", "", none ? `${app.name} doesn't collect data from anyone, including children.` : `${app.name} isn't directed at children under 13, and ${w.we} don't knowingly collect their data.`, "", "## Changes", "", "If this policy changes, the new version will be posted at this address, with a new date above.", "", "## Contact", "", contactLine(facts), "");
89
+ return { file: "privacy.md", title: `${app.name} privacy policy`, path: "privacy/", markdown: lines.join("\n") };
90
+ }
91
+ export function supportPage(facts) {
92
+ const { app, publisher, support } = facts;
93
+ const w = voice(facts);
94
+ const lines = [
95
+ `# ${app.name} support`,
96
+ "",
97
+ `Questions, bugs or ideas: email **[${publisher.email}](mailto:${publisher.email})**. ${w.We} usually reply ${support.replyTime}.`,
98
+ "",
99
+ `Please include ${support.askFor || "your device model and iOS version"}, and what you expected to happen.`,
100
+ "",
101
+ ];
102
+ if (support.faq.length > 0) {
103
+ lines.push("## Frequently asked questions", "");
104
+ for (const { q, a } of support.faq)
105
+ lines.push(`**${q}**`, a.trim(), "");
106
+ }
107
+ lines.push("## Privacy", "", `See the [${app.name} privacy policy](${pageURL(facts, "privacy")}).`, "");
108
+ return { file: "support.md", title: `${app.name} support`, path: "support/", markdown: lines.join("\n") };
109
+ }
110
+ /** German-language Impressum (§ 5 DDG for DE, § 5 ECG for AT), with an English notice. */
111
+ export function impressum(facts) {
112
+ const p = facts.publisher;
113
+ const law = p.country.toUpperCase() === "AT" ? "§ 5 ECG" : "§ 5 DDG";
114
+ const lines = [];
115
+ if (p.trader) {
116
+ lines.push("# Impressum", "", `## Angaben gemäß ${law}`, "", impressumLines(facts)
117
+ .map(({ label, value }) => (label ? `${label}: ${value.includes("@") ? `[${value}](mailto:${value})` : value}` : value))
118
+ .join(" \n"), "", "## Verantwortlich für den Inhalt", "", `${p.representative || p.name}, Anschrift wie oben.`, "", "---", "", "## Legal notice (English)", "", `${facts.app.name} is provided by ${[p.name, p.address.street, p.address.city, p.address.country].filter(Boolean).join(", ")}. Contact: ${p.email}.`, "");
119
+ }
120
+ else {
121
+ lines.push("# Contact", "", `${by(facts)} is a private, non-commercial project. ${facts.app.name} is free, with no in-app purchases, ads or tracking.`, "", `Email: [${p.email}](mailto:${p.email})`, "", "## Impressum", "", `${by(facts)} ist ein privates, nicht-kommerzielles Projekt ohne Gewinnabsicht. ${facts.app.name} ist kostenlos, ohne In-App-Käufe, Werbung oder Tracking.`, "", `Kontakt: [${p.email}](mailto:${p.email})`, "");
122
+ }
123
+ return { file: "impressum.md", title: "Impressum", path: "impressum/", markdown: lines.join("\n") };
124
+ }
@@ -0,0 +1,55 @@
1
+ /** What `shelf scan` finds in an app repository. Everything comes from files on disk. */
2
+ export interface ScanResult {
3
+ root: string;
4
+ xcodeProjects: string[];
5
+ bundleIdentifiers: string[];
6
+ displayNames: string[];
7
+ /** Purpose strings (e.g. NSCameraUsageDescription) from Info.plist files and build settings. */
8
+ purposeStrings: Record<string, string>;
9
+ privacyManifests: PrivacyManifest[];
10
+ packages: ResolvedPackage[];
11
+ /** ITSAppUsesNonExemptEncryption from Info.plist or build settings; undefined if not declared. */
12
+ usesNonExemptEncryption?: boolean;
13
+ }
14
+ export interface PrivacyManifest {
15
+ path: string;
16
+ tracking: boolean;
17
+ trackingDomains: string[];
18
+ collectedDataTypes: CollectedDataType[];
19
+ accessedAPIs: AccessedAPI[];
20
+ }
21
+ export interface CollectedDataType {
22
+ type: string;
23
+ linked: boolean;
24
+ tracking: boolean;
25
+ purposes: string[];
26
+ }
27
+ export interface AccessedAPI {
28
+ category: string;
29
+ reasons: string[];
30
+ }
31
+ export interface ResolvedPackage {
32
+ identity: string;
33
+ location: string;
34
+ version?: string;
35
+ }
36
+ type Dict = Record<string, unknown>;
37
+ export declare function scan(rootPath: string): ScanResult;
38
+ export declare function privacyManifest(dict: Dict, path: string): PrivacyManifest;
39
+ /** Supports Package.resolved v1 (`object.pins`) and v2/v3 (`pins`). */
40
+ export declare function readResolvedPackages(file: string): ResolvedPackage[];
41
+ /** CocoaPods: top-level entries under PODS, e.g. " - FirebaseAnalytics (10.0.0):". */
42
+ export declare function readPodfileLock(file: string): ResolvedPackage[];
43
+ /** Carthage: lines like `github "Alamofire/Alamofire" "5.8.0"`. */
44
+ export declare function readCartfileResolved(file: string): ResolvedPackage[];
45
+ /**
46
+ * Minimal reader for the build settings that matter in `project.pbxproj`.
47
+ * Projects with GENERATE_INFOPLIST_FILE keep purpose strings here as INFOPLIST_KEY_*.
48
+ */
49
+ export declare function parseBuildSettings(text: string): {
50
+ bundleIdentifiers: Set<string>;
51
+ displayNames: Set<string>;
52
+ purposeStrings: Record<string, string>;
53
+ usesNonExemptEncryption: boolean | undefined;
54
+ };
55
+ export {};
@@ -0,0 +1,215 @@
1
+ import { readdirSync, readFileSync, existsSync, statSync } from "node:fs";
2
+ import { join, relative, resolve } from "node:path";
3
+ import { parse as parsePlist, parseBinary } from "plist";
4
+ /** Folders that never hold source of truth. */
5
+ const SKIPPED = new Set([".git", ".build", "build", "DerivedData", "Pods", "Carthage", "node_modules", ".swiftpm"]);
6
+ export function scan(rootPath) {
7
+ const root = resolve(rootPath);
8
+ if (!existsSync(root) || !statSync(root).isDirectory())
9
+ throw new Error(`Not a directory: ${rootPath}`);
10
+ const result = {
11
+ root,
12
+ xcodeProjects: [],
13
+ bundleIdentifiers: [],
14
+ displayNames: [],
15
+ purposeStrings: {},
16
+ privacyManifests: [],
17
+ packages: [],
18
+ };
19
+ const bundleIDs = new Set();
20
+ const names = new Set();
21
+ const seenPackages = new Set();
22
+ for (const file of walk(root)) {
23
+ const name = file.split("/").pop() ?? "";
24
+ const rel = relative(root, file);
25
+ if (name.endsWith(".xcodeproj")) {
26
+ result.xcodeProjects.push(rel);
27
+ const pbx = join(file, "project.pbxproj");
28
+ if (existsSync(pbx)) {
29
+ const settings = parseBuildSettings(readFileSync(pbx, "utf8"));
30
+ settings.bundleIdentifiers.forEach((id) => bundleIDs.add(id));
31
+ settings.displayNames.forEach((n) => names.add(n));
32
+ for (const [k, v] of Object.entries(settings.purposeStrings))
33
+ result.purposeStrings[k] ??= v;
34
+ if (settings.usesNonExemptEncryption !== undefined)
35
+ result.usesNonExemptEncryption ||= settings.usesNonExemptEncryption;
36
+ }
37
+ }
38
+ else if (name === "Info.plist") {
39
+ const dict = readPlist(file);
40
+ if (!dict)
41
+ continue;
42
+ for (const [key, value] of Object.entries(dict)) {
43
+ if (key.endsWith("UsageDescription") && typeof value === "string")
44
+ result.purposeStrings[key] = value;
45
+ }
46
+ const id = dict.CFBundleIdentifier;
47
+ if (typeof id === "string" && !id.includes("$("))
48
+ bundleIDs.add(id);
49
+ if (typeof dict.ITSAppUsesNonExemptEncryption === "boolean")
50
+ result.usesNonExemptEncryption ||= dict.ITSAppUsesNonExemptEncryption;
51
+ const display = dict.CFBundleDisplayName;
52
+ if (typeof display === "string" && !display.includes("$("))
53
+ names.add(display);
54
+ }
55
+ else if (name === "PrivacyInfo.xcprivacy") {
56
+ const dict = readPlist(file);
57
+ if (dict)
58
+ result.privacyManifests.push(privacyManifest(dict, rel));
59
+ }
60
+ else if (name === "Package.resolved" || name === "Podfile.lock" || name === "Cartfile.resolved") {
61
+ const found = name === "Package.resolved" ? readResolvedPackages(file) : name === "Podfile.lock" ? readPodfileLock(file) : readCartfileResolved(file);
62
+ for (const pkg of found) {
63
+ if (!seenPackages.has(pkg.identity)) {
64
+ seenPackages.add(pkg.identity);
65
+ result.packages.push(pkg);
66
+ }
67
+ }
68
+ }
69
+ }
70
+ result.xcodeProjects.sort();
71
+ result.bundleIdentifiers = [...bundleIDs].sort();
72
+ result.displayNames = [...names].sort();
73
+ result.privacyManifests.sort((a, b) => a.path.localeCompare(b.path));
74
+ result.packages.sort((a, b) => a.identity.localeCompare(b.identity));
75
+ return result;
76
+ }
77
+ /** Yields files and `.xcodeproj` bundles; doesn't descend into skipped folders or bundles. */
78
+ function* walk(dir) {
79
+ let entries;
80
+ try {
81
+ entries = readdirSync(dir, { withFileTypes: true });
82
+ }
83
+ catch {
84
+ return;
85
+ }
86
+ for (const entry of entries) {
87
+ if (entry.name.startsWith(".") && entry.name !== ".github")
88
+ continue;
89
+ const path = join(dir, entry.name);
90
+ if (entry.isDirectory()) {
91
+ if (entry.name.endsWith(".xcodeproj")) {
92
+ yield path;
93
+ // Package.resolved for Xcode projects lives inside the bundle.
94
+ const resolved = join(path, "project.xcworkspace/xcshareddata/swiftpm/Package.resolved");
95
+ if (existsSync(resolved))
96
+ yield resolved;
97
+ }
98
+ else if (!SKIPPED.has(entry.name) && !entry.name.endsWith(".xcworkspace")) {
99
+ yield* walk(path);
100
+ }
101
+ }
102
+ else {
103
+ yield path;
104
+ }
105
+ }
106
+ }
107
+ function readPlist(file) {
108
+ const isDict = (v) => !!v && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date);
109
+ const bytes = readFileSync(file);
110
+ try {
111
+ const parsed = bytes.subarray(0, 6).toString("latin1") === "bplist" ? parseBinary(bytes) : parsePlist(bytes.toString("utf8"));
112
+ return isDict(parsed) ? parsed : undefined;
113
+ }
114
+ catch {
115
+ return undefined; // malformed plist
116
+ }
117
+ }
118
+ const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
119
+ const dicts = (v) => (Array.isArray(v) ? v.filter((x) => !!x && typeof x === "object") : []);
120
+ export function privacyManifest(dict, path) {
121
+ return {
122
+ path,
123
+ tracking: dict.NSPrivacyTracking === true,
124
+ trackingDomains: strings(dict.NSPrivacyTrackingDomains),
125
+ collectedDataTypes: dicts(dict.NSPrivacyCollectedDataTypes).map((d) => ({
126
+ type: typeof d.NSPrivacyCollectedDataType === "string" ? d.NSPrivacyCollectedDataType : "unknown",
127
+ linked: d.NSPrivacyCollectedDataTypeLinked === true,
128
+ tracking: d.NSPrivacyCollectedDataTypeTracking === true,
129
+ purposes: strings(d.NSPrivacyCollectedDataTypePurposes),
130
+ })),
131
+ accessedAPIs: dicts(dict.NSPrivacyAccessedAPITypes).map((d) => ({
132
+ category: typeof d.NSPrivacyAccessedAPIType === "string" ? d.NSPrivacyAccessedAPIType : "unknown",
133
+ reasons: strings(d.NSPrivacyAccessedAPITypeReasons),
134
+ })),
135
+ };
136
+ }
137
+ /** Supports Package.resolved v1 (`object.pins`) and v2/v3 (`pins`). */
138
+ export function readResolvedPackages(file) {
139
+ let json;
140
+ try {
141
+ json = JSON.parse(readFileSync(file, "utf8"));
142
+ }
143
+ catch {
144
+ return [];
145
+ }
146
+ const pins = dicts(json.pins ?? json.object?.pins);
147
+ return pins.flatMap((pin) => {
148
+ const identity = typeof pin.identity === "string" ? pin.identity : typeof pin.package === "string" ? pin.package.toLowerCase() : undefined;
149
+ if (!identity)
150
+ return [];
151
+ const location = typeof pin.location === "string" ? pin.location : typeof pin.repositoryURL === "string" ? pin.repositoryURL : "";
152
+ const version = pin.state?.version;
153
+ return [{ identity, location, ...(typeof version === "string" ? { version } : {}) }];
154
+ });
155
+ }
156
+ /** CocoaPods: top-level entries under PODS, e.g. " - FirebaseAnalytics (10.0.0):". */
157
+ export function readPodfileLock(file) {
158
+ const pods = [];
159
+ let inPods = false;
160
+ for (const line of readFileSync(file, "utf8").split("\n")) {
161
+ if (/^\S/.test(line))
162
+ inPods = line.startsWith("PODS:");
163
+ else if (inPods) {
164
+ const m = /^ - "?([^\s"(]+)"?(?: \(([^)]+)\))?/.exec(line);
165
+ if (m) {
166
+ const identity = m[1].split("/")[0].toLowerCase();
167
+ if (!pods.some((p) => p.identity === identity))
168
+ pods.push({ identity, location: "cocoapods", ...(m[2] ? { version: m[2] } : {}) });
169
+ }
170
+ }
171
+ }
172
+ return pods;
173
+ }
174
+ /** Carthage: lines like `github "Alamofire/Alamofire" "5.8.0"`. */
175
+ export function readCartfileResolved(file) {
176
+ return readFileSync(file, "utf8").split("\n").flatMap((line) => {
177
+ const m = /^(github|git|binary) "([^"]+)" "([^"]+)"/.exec(line.trim());
178
+ if (!m)
179
+ return [];
180
+ const identity = m[2].replace(/\.git$/, "").split("/").pop().toLowerCase();
181
+ return [{ identity, location: m[2], version: m[3] }];
182
+ });
183
+ }
184
+ /**
185
+ * Minimal reader for the build settings that matter in `project.pbxproj`.
186
+ * Projects with GENERATE_INFOPLIST_FILE keep purpose strings here as INFOPLIST_KEY_*.
187
+ */
188
+ export function parseBuildSettings(text) {
189
+ const bundleIdentifiers = new Set();
190
+ const displayNames = new Set();
191
+ const purposeStrings = {};
192
+ let usesNonExemptEncryption;
193
+ for (const raw of text.split("\n")) {
194
+ const line = raw.trim();
195
+ const eq = line.indexOf("=");
196
+ if (eq < 0 || !line.endsWith(";"))
197
+ continue;
198
+ const key = line.slice(0, eq).trim();
199
+ let value = line.slice(eq + 1, -1).trim();
200
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"'))
201
+ value = value.slice(1, -1);
202
+ if (!value || value.includes("$("))
203
+ continue;
204
+ if (key === "PRODUCT_BUNDLE_IDENTIFIER")
205
+ bundleIdentifiers.add(value);
206
+ else if (key === "INFOPLIST_KEY_CFBundleDisplayName")
207
+ displayNames.add(value);
208
+ else if (key === "INFOPLIST_KEY_ITSAppUsesNonExemptEncryption")
209
+ usesNonExemptEncryption = (usesNonExemptEncryption ?? false) || /^(yes|true|1)$/i.test(value);
210
+ else if (key.startsWith("INFOPLIST_KEY_") && key.endsWith("UsageDescription")) {
211
+ purposeStrings[key.slice("INFOPLIST_KEY_".length)] = value;
212
+ }
213
+ }
214
+ return { bundleIdentifiers, displayNames, purposeStrings, usesNonExemptEncryption };
215
+ }
@@ -0,0 +1,10 @@
1
+ export * from "./core/scan.js";
2
+ export * from "./core/facts.js";
3
+ export * from "./core/appPrivacy.js";
4
+ export * from "./core/pages.js";
5
+ export * from "./core/legalView.js";
6
+ export * from "./core/check.js";
7
+ export * from "./core/migrate.js";
8
+ export * from "./core/online.js";
9
+ export * from "./core/checklist.js";
10
+ export * from "./core/knowledge.js";