@legendapp/spark 0.0.1-next.4 → 0.0.1-next.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/customize.ts +2 -0
- package/html.ts +1 -0
- package/markdown.ts +1 -0
- package/package.json +22 -13
- package/patches/dependencies.json +10 -4
- package/patches/react-native-enriched-html@1.1.1.patch +854 -0
- package/patches/{react-native-enriched-markdown@1.0.2.patch → react-native-enriched-markdown@1.1.1.patch} +2560 -1983
- package/schema.json +104 -0
- package/skills/spark/SKILL.md +56 -0
- package/skills/spark/UPGRADING.md +254 -0
- package/vendor/node_modules/@legendapp/spark-ai/package.json +4 -4
- package/vendor/node_modules/@legendapp/spark-ai/src/invocation-command.cjs +11 -0
- package/vendor/node_modules/@legendapp/spark-ai/src/invocation-command.d.cts +2 -0
- package/vendor/node_modules/@legendapp/spark-ai/src/invocations.ts +2 -19
- package/vendor/node_modules/@legendapp/spark-audio/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-auth-session/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-cli/dist/add-desktop.js +4 -4
- package/vendor/node_modules/@legendapp/spark-cli/dist/build.js +3 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/create.js +31 -11
- package/vendor/node_modules/@legendapp/spark-cli/dist/customize-ai.cjs +108 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/customize-artifacts.js +315 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/customize-cli.cjs +75 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/customize-github.cjs +133 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/customize-policy.cjs +102 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/customize-provider.cjs +2 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/customize-worker.cjs +273 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/dependency-pins.js +54 -29
- package/vendor/node_modules/@legendapp/spark-cli/dist/dev-command.js +2 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/enriched-html-pins.js +128 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/expo-dev-patch.cjs +30 -1
- package/vendor/node_modules/@legendapp/spark-cli/dist/index.js +16 -7
- package/vendor/node_modules/@legendapp/spark-cli/dist/init-template.d.cts +1 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/js-runtime.cjs +96 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/migration-helpers.cjs +152 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/migration-helpers.d.cts +15 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/migrations.cjs +184 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/migrations.d.cts +16 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/native-patch-preflight.js +2 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/package-manager-config.js +41 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/package-manager.js +13 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/project-version.js +12 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/project.js +40 -9
- package/vendor/node_modules/@legendapp/spark-cli/dist/release.json +19 -19
- package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-bootstrap.ps1 +87 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-bootstrap.sh +107 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-downloads.tsv +13 -0
- package/vendor/node_modules/@legendapp/spark-cli/dist/sdk-install.js +8 -3
- package/vendor/node_modules/@legendapp/spark-cli/dist/upgrade.js +102 -0
- package/vendor/node_modules/@legendapp/spark-cli/package.json +6 -4
- package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/.claude/skills/spark/SKILL.md +9 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/AGENTS.md +4 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/CLAUDE.md +4 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/README.md +15 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/package.json +46 -2
- package/vendor/node_modules/@legendapp/spark-cli/templates/universal/.claude/skills/spark/SKILL.md +9 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/universal/AGENTS.md +4 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/universal/CLAUDE.md +4 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/universal/README.md +15 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/universal/package.json +45 -2
- package/vendor/node_modules/@legendapp/spark-cli/templates/windows/.claude/skills/spark/SKILL.md +9 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/windows/AGENTS.md +4 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/windows/CLAUDE.md +4 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/windows/README.md +15 -0
- package/vendor/node_modules/@legendapp/spark-cli/templates/windows/package.json +46 -2
- package/vendor/node_modules/@legendapp/spark-clipboard/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-codex/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-commands/package.json +6 -6
- package/vendor/node_modules/@legendapp/spark-context-menu/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-desktop-app/macos/RNDesktopApp.mm +14 -1
- package/vendor/node_modules/@legendapp/spark-desktop-app/package.json +2 -2
- package/vendor/node_modules/@legendapp/spark-desktop-app/src/customize-hooks.ts +17 -0
- package/vendor/node_modules/@legendapp/spark-desktop-app/src/customize.ts +117 -0
- package/vendor/node_modules/@legendapp/spark-desktop-config/app.plugin.cjs +20 -1
- package/vendor/node_modules/@legendapp/spark-desktop-config/config.cjs +3 -2
- package/vendor/node_modules/@legendapp/spark-desktop-config/config.d.cts +14 -0
- package/vendor/node_modules/@legendapp/spark-desktop-config/customize-provider.cjs +16 -0
- package/vendor/node_modules/@legendapp/spark-desktop-config/customize.cjs +16 -0
- package/vendor/node_modules/@legendapp/spark-desktop-config/package.json +4 -4
- package/vendor/node_modules/@legendapp/spark-desktop-config/schema.json +104 -0
- package/vendor/node_modules/@legendapp/spark-desktop-host/SparkCustomize.mm +517 -0
- package/vendor/node_modules/@legendapp/spark-desktop-host/package.json +4 -3
- package/vendor/node_modules/@legendapp/spark-desktop-links/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/RNDesktopShortcuts.mm +3 -1
- package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/keyboard-manager/RNKeyboardManager.h +3 -0
- package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/keyboard-manager/RNKeyboardManager.mm +1 -1
- package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-desktop-windows/macos/window-manager/RNWindowManager.mm +5 -4
- package/vendor/node_modules/@legendapp/spark-desktop-windows/package.json +4 -4
- package/vendor/node_modules/@legendapp/spark-desktop-windows/src/api.ts +62 -25
- package/vendor/node_modules/@legendapp/spark-desktop-windows/src/macos-adapter.ts +7 -5
- package/vendor/node_modules/@legendapp/spark-documents/package.json +8 -8
- package/vendor/node_modules/@legendapp/spark-drag-drop/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-file-dialog/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-file-system/macos/SparkFileMutations.h +1 -0
- package/vendor/node_modules/@legendapp/spark-file-system/macos/SparkFileMutations.mm +11 -10
- package/vendor/node_modules/@legendapp/spark-file-system/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-global-shortcuts/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-html/package.json +24 -0
- package/vendor/node_modules/@legendapp/spark-html/src/Html.tsx +22 -0
- package/vendor/node_modules/@legendapp/spark-html/src/HtmlInput.tsx +102 -0
- package/vendor/node_modules/@legendapp/spark-html/src/index.ts +4 -0
- package/vendor/node_modules/@legendapp/spark-html/src/types.ts +4 -0
- package/vendor/node_modules/@legendapp/spark-markdown/package.json +24 -0
- package/vendor/node_modules/@legendapp/spark-markdown/src/Markdown.tsx +24 -0
- package/vendor/node_modules/@legendapp/spark-markdown/src/MarkdownInput.tsx +111 -0
- package/vendor/node_modules/@legendapp/spark-markdown/src/index.ts +4 -0
- package/vendor/node_modules/@legendapp/spark-message-dialog/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-native-menu/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-notifications/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-processes/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-rich-text/package.json +18 -0
- package/vendor/node_modules/@legendapp/spark-rich-text/src/components.tsx +52 -0
- package/vendor/node_modules/@legendapp/spark-rich-text/src/index.ts +4 -0
- package/vendor/node_modules/@legendapp/spark-rich-text/src/types.ts +24 -0
- package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputShortcuts.macos.ts +55 -0
- package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputShortcuts.ts +13 -0
- package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputValue.ts +14 -0
- package/vendor/node_modules/@legendapp/spark-rich-text/src/value.ts +16 -0
- package/vendor/node_modules/@legendapp/spark-secure-storage/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-settings/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-settings-ui/package.json +5 -5
- package/vendor/node_modules/@legendapp/spark-sqlite/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-system/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-tray/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-ui/macos/appkit-split-view/RNSidebarSplitViewComponent.mm +102 -14
- package/vendor/node_modules/@legendapp/spark-ui/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-ui/src/appkit-split-view/SidebarSplitViewNativeComponent.ts +5 -0
- package/vendor/node_modules/@legendapp/spark-ui/src/appkit-split-view/index.tsx +12 -4
- package/vendor/node_modules/@legendapp/spark-updates/package.json +3 -3
- package/vendor/node_modules/@legendapp/spark-webview/package.json +2 -2
- package/vendor/node_modules/@legendapp/spark-window-options/package.json +1 -1
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// GitHub publication stays in Spark's trusted toolkit, outside the AI workspace.
|
|
2
|
+
const crypto = require('node:crypto');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const worker = require('./customize-worker.cjs');
|
|
5
|
+
const fail = (code, message) => Object.assign(new Error(message), { code });
|
|
6
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
7
|
+
async function request(url, body, token, fetcher = fetch) {
|
|
8
|
+
const response = await fetcher(url, {
|
|
9
|
+
method: body === undefined ? 'GET' : 'POST', redirect: 'error', signal: AbortSignal.timeout(30000),
|
|
10
|
+
headers: { Accept: url.startsWith('https://github.com/login/') ? 'application/json' : 'application/vnd.github+json', 'Content-Type': 'application/json', 'X-GitHub-Api-Version': '2022-11-28', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
|
11
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
12
|
+
});
|
|
13
|
+
let value;
|
|
14
|
+
try { value = await response.json(); } catch { throw fail('E_INVALID_DATA', 'GitHub returned invalid JSON'); }
|
|
15
|
+
if (!response.ok) throw fail(response.status === 401 || response.status === 403 ? 'E_PERMISSION_DENIED' : 'E_NATIVE', `GitHub request failed (${response.status})`);
|
|
16
|
+
if (!value || typeof value !== 'object') throw fail('E_INVALID_DATA', 'GitHub returned invalid data');
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
function clientId(value) { if (typeof value !== 'string' || !/^[A-Za-z0-9_.-]+$/.test(value)) throw fail('E_INVALID_ARGUMENT', 'Configure customize.githubClientId with a device-flow-enabled GitHub OAuth app'); return value; }
|
|
20
|
+
async function begin(id, fetcher) {
|
|
21
|
+
const value = await request('https://github.com/login/device/code', { client_id: clientId(id), scope: 'public_repo' }, undefined, fetcher);
|
|
22
|
+
if (typeof value.device_code !== 'string' || !value.device_code || typeof value.user_code !== 'string' || !value.user_code || value.verification_uri !== 'https://github.com/login/device' || !Number.isSafeInteger(value.expires_in) || value.expires_in <= 0 || !Number.isSafeInteger(value.interval) || value.interval <= 0) throw fail('E_INVALID_DATA', 'GitHub returned invalid device authorization');
|
|
23
|
+
return { clientId: id, deviceCode: value.device_code, userCode: value.user_code, verificationUri: value.verification_uri, expiresIn: value.expires_in, expiresAt: Date.now() + value.expires_in * 1000, interval: value.interval };
|
|
24
|
+
}
|
|
25
|
+
async function complete(session, { fetcher, wait = sleep, now = Date.now } = {}) {
|
|
26
|
+
clientId(session.clientId);
|
|
27
|
+
if (typeof session.deviceCode !== 'string' || !session.deviceCode || !Number.isFinite(session.expiresAt) || !Number.isSafeInteger(session.interval) || session.interval <= 0) throw fail('E_INVALID_ARGUMENT', 'Start GitHub authorization first');
|
|
28
|
+
let interval = session.interval * 1000;
|
|
29
|
+
while (now() < session.expiresAt) {
|
|
30
|
+
if (now() + interval >= session.expiresAt) break;
|
|
31
|
+
await wait(interval);
|
|
32
|
+
const value = await request('https://github.com/login/oauth/access_token', { client_id: session.clientId, device_code: session.deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' }, undefined, fetcher);
|
|
33
|
+
if (typeof value.access_token === 'string' && value.access_token) return { token: value.access_token };
|
|
34
|
+
if (value.error === 'slow_down') interval += 5000;
|
|
35
|
+
else if (value.error !== 'authorization_pending') throw fail(value.error === 'expired_token' ? 'E_TIMEOUT' : 'E_PERMISSION_DENIED', 'GitHub device authorization was denied or expired');
|
|
36
|
+
}
|
|
37
|
+
throw fail('E_TIMEOUT', 'GitHub device authorization expired');
|
|
38
|
+
}
|
|
39
|
+
function blobHash(base64) { const bytes = Buffer.from(base64, 'base64'); return crypto.createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex'); }
|
|
40
|
+
function repositoryPath(prefix, name) {
|
|
41
|
+
if (typeof name !== 'string' || !name || typeof (prefix ?? '') !== 'string' || [prefix || '', name].some(part => part && (part.startsWith('/') || part.includes('\\') || part.split('/').some(segment => !segment || segment === '.' || segment === '..' || segment === '.git')))) throw fail('E_INVALID_DATA', 'Invalid repository patch path');
|
|
42
|
+
return path.posix.join(prefix || '', name);
|
|
43
|
+
}
|
|
44
|
+
async function submit(directory, options, token, { fetcher, wait = sleep } = {}) {
|
|
45
|
+
if (!token) throw fail('E_PERMISSION_DENIED', 'Sign in to GitHub before submitting');
|
|
46
|
+
if (options && Object.keys(options).some(key => key !== 'title')) throw fail('E_UNSUPPORTED_OPTION', 'Unknown pull request option');
|
|
47
|
+
if (!options || typeof options.title !== 'string' || !options.title.trim() || options.title.length > 256) throw fail('E_INVALID_ARGUMENT', 'Enter a PR title of at most 256 characters');
|
|
48
|
+
const manifest = worker.read(path.join(directory, 'manifest.json'));
|
|
49
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(manifest.repository || '')) throw fail('E_INVALID_DATA', 'Customize release has no target repository');
|
|
50
|
+
const ready = worker.verify(directory); // Only publish the exact candidate that passed build/review checks.
|
|
51
|
+
const source = ready.candidate === 'work' ? path.join(directory, 'work') : worker.safe(path.join(directory, 'candidates'), ready.candidate);
|
|
52
|
+
const changes = worker.patch(worker.snapshot(path.join(directory, 'base')), worker.snapshot(source));
|
|
53
|
+
if (!changes.length) throw fail('E_INVALID_ARGUMENT', 'There are no changes to submit');
|
|
54
|
+
for (const change of changes) change.repositoryPath = repositoryPath(manifest.repositoryDirectory, change.path);
|
|
55
|
+
const state = worker.read(path.join(directory, 'state.json'));
|
|
56
|
+
const relevant = new Set();
|
|
57
|
+
const current = state.history?.find(item => item.candidate === ready.candidate);
|
|
58
|
+
for (const id of current?.ancestors || []) relevant.add(id);
|
|
59
|
+
if (current) relevant.add(current.id);
|
|
60
|
+
const prompts = [...(state.inheritedPrompts || []), ...(state.history || []).filter(item => item.status === 'accepted' || relevant.has(item.id))].map(item => item.prompt).filter(value => typeof value === 'string' && value);
|
|
61
|
+
const patch = worker.reviewPatch(changes.map(change => ({ ...change, path: change.repositoryPath })));
|
|
62
|
+
const body = `Submitted from ${manifest.project} ${manifest.version}.\n\n## User prompts\n\n${prompts.map(prompt => `> ${prompt.replace(/\n/g, '\n> ')}`).join('\n\n')}\n\n## Patch\n\n\`\`\`diff\n${patch.replace(/\`\`\`/g, '\`\`\u200b\`')}\n\`\`\``;
|
|
63
|
+
if (body.length > 60000) throw fail('E_INVALID_ARGUMENT', 'Prompt and patch exceed GitHub PR body limit');
|
|
64
|
+
let repo = manifest.repository;
|
|
65
|
+
const api = endpoint => `https://api.github.com/${endpoint}`;
|
|
66
|
+
const get = endpoint => request(api(endpoint), undefined, token, fetcher);
|
|
67
|
+
const post = (endpoint, body) => request(api(endpoint), body, token, fetcher);
|
|
68
|
+
const [user, upstream] = await Promise.all([get('user'), get(`repos/${repo}`)]);
|
|
69
|
+
if (!/^[\w-]+$/.test(user.login || '') || typeof upstream.full_name !== 'string' || upstream.full_name.toLowerCase() !== repo.toLowerCase() || typeof upstream.default_branch !== 'string' || !upstream.default_branch || upstream.private !== false) throw fail('E_INVALID_DATA', 'GitHub returned an invalid public target repository');
|
|
70
|
+
repo = upstream.full_name;
|
|
71
|
+
const ref = await get(`repos/${repo}/git/ref/heads/${encodeURIComponent(upstream.default_branch)}`);
|
|
72
|
+
const sha = ref.object?.sha;
|
|
73
|
+
if (!/^[a-f0-9]{40}$/.test(sha || '')) throw fail('E_INVALID_DATA', 'GitHub returned an invalid base commit');
|
|
74
|
+
const commit = await get(`repos/${repo}/git/commits/${sha}`);
|
|
75
|
+
if (!/^[a-f0-9]{40}$/.test(commit.tree?.sha || '')) throw fail('E_INVALID_DATA', 'GitHub returned an invalid base tree');
|
|
76
|
+
const tree = await get(`repos/${repo}/git/trees/${commit.tree.sha}?recursive=1`);
|
|
77
|
+
if (tree.truncated || !Array.isArray(tree.tree)) throw fail('E_INVALID_DATA', 'GitHub base tree is incomplete; cannot safely submit');
|
|
78
|
+
const entries = new Map(tree.tree.map(item => [item.path, item]));
|
|
79
|
+
for (const change of changes) {
|
|
80
|
+
const entry = entries.get(change.repositoryPath);
|
|
81
|
+
if (change.before === null ? !!entry : !entry || entry.type !== 'blob' || !['100644', '100755'].includes(entry.mode) || entry.sha !== blobHash(change.before)) throw fail('E_INVALID_DATA', `Upstream changed ${change.repositoryPath}; update the app before submitting`);
|
|
82
|
+
const parts = change.repositoryPath.split('/');
|
|
83
|
+
for (let count = 1; count < parts.length; count++) {
|
|
84
|
+
const parent = entries.get(parts.slice(0, count).join('/'));
|
|
85
|
+
if (parent && parent.type !== 'tree') throw fail('E_INVALID_DATA', `Upstream changed the directory for ${change.repositoryPath}; update the app before submitting`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
let destination = repo;
|
|
89
|
+
if (repo.split('/')[0].toLowerCase() !== user.login.toLowerCase()) {
|
|
90
|
+
const fork = await post(`repos/${repo}/forks`, { default_branch_only: true });
|
|
91
|
+
if (fork.owner?.login !== user.login || !/^[\w.-]+\/[\w.-]+$/.test(fork.full_name || '') || fork.parent?.full_name?.toLowerCase() !== repo.toLowerCase()) throw fail('E_INVALID_DATA', 'GitHub returned an unrelated fork');
|
|
92
|
+
destination = fork.full_name;
|
|
93
|
+
// Fork creation is asynchronous. Bound the wait and only retry reads.
|
|
94
|
+
let available = false;
|
|
95
|
+
for (let attempt = 0; attempt < 12; attempt++) {
|
|
96
|
+
try { await get(`repos/${destination}/git/commits/${sha}`); available = true; break; }
|
|
97
|
+
catch (error) { if (error.code !== 'E_NATIVE') throw error; if (attempt < 11) await wait(5000); }
|
|
98
|
+
}
|
|
99
|
+
if (!available) throw fail('E_TIMEOUT', 'GitHub fork is not ready; retry submission later');
|
|
100
|
+
}
|
|
101
|
+
const files = [];
|
|
102
|
+
for (const change of changes) {
|
|
103
|
+
let blob = null;
|
|
104
|
+
if (change.after !== null) {
|
|
105
|
+
const result = await post(`repos/${destination}/git/blobs`, { encoding: 'base64', content: change.after });
|
|
106
|
+
if (!/^[a-f0-9]{40}$/.test(result.sha || '')) throw fail('E_INVALID_DATA', 'GitHub returned an invalid blob');
|
|
107
|
+
blob = result.sha;
|
|
108
|
+
}
|
|
109
|
+
files.push({ path: change.repositoryPath, mode: entries.get(change.repositoryPath)?.mode || '100644', type: 'blob', sha: blob });
|
|
110
|
+
}
|
|
111
|
+
const newTree = await post(`repos/${destination}/git/trees`, { base_tree: commit.tree.sha, tree: files });
|
|
112
|
+
if (!/^[a-f0-9]{40}$/.test(newTree.sha || '')) throw fail('E_INVALID_DATA', 'GitHub returned an invalid tree');
|
|
113
|
+
const newCommit = await post(`repos/${destination}/git/commits`, { message: options.title.trim(), tree: newTree.sha, parents: [sha] });
|
|
114
|
+
if (!/^[a-f0-9]{40}$/.test(newCommit.sha || '')) throw fail('E_INVALID_DATA', 'GitHub returned an invalid commit');
|
|
115
|
+
const branch = `spark-customize-${crypto.randomUUID()}`;
|
|
116
|
+
await post(`repos/${destination}/git/refs`, { ref: `refs/heads/${branch}`, sha: newCommit.sha });
|
|
117
|
+
const result = await post(`repos/${repo}/pulls`, { title: options.title.trim(), body, head: `${user.login}:${branch}`, base: upstream.default_branch, maintainer_can_modify: true });
|
|
118
|
+
if (typeof result.html_url !== 'string' || !result.html_url.startsWith(`https://github.com/${repo}/pull/`) || !Number.isSafeInteger(result.number)) throw fail('E_INVALID_DATA', 'GitHub returned an invalid pull request');
|
|
119
|
+
return { url: result.html_url, number: result.number, repository: repo, branch };
|
|
120
|
+
}
|
|
121
|
+
module.exports = { begin, complete, submit, blobHash, repositoryPath };
|
|
122
|
+
if (require.main === module) {
|
|
123
|
+
(async () => {
|
|
124
|
+
const [command, directory] = process.argv.slice(2);
|
|
125
|
+
const input = JSON.parse(process.env.SPARK_CUSTOMIZE_GITHUB_REQUEST || '{}');
|
|
126
|
+
let result;
|
|
127
|
+
if (command === 'begin') result = await begin(input.clientId);
|
|
128
|
+
else if (command === 'complete') result = await complete(input);
|
|
129
|
+
else if (command === 'submit') result = await submit(directory, input, process.env.SPARK_CUSTOMIZE_GITHUB_TOKEN);
|
|
130
|
+
else throw fail('E_INVALID_ARGUMENT', 'Unknown GitHub customize operation');
|
|
131
|
+
console.log(JSON.stringify(result));
|
|
132
|
+
})().catch(error => { console.error(JSON.stringify({ error: error.code || 'E_NATIVE', message: error.code ? error.message : 'GitHub operation failed' })); process.exitCode = 1; });
|
|
133
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
const fs = require('node:fs');
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
// Configuration is executable input to compilation, never customize app source.
|
|
4
|
+
function isBuildConfig(file) {
|
|
5
|
+
const name = path.posix.basename(file);
|
|
6
|
+
return /(?:^|\/)(?:scripts|plugins|transforms)(?:\/|$)/i.test(file) || /(?:^|\.)config(?:\.|$)/i.test(name) || /^(?:app\.json|package\.json|tsconfig.*|jsconfig.*|babel\..*|metro\..*|\.babelrc.*)$/.test(name);
|
|
7
|
+
}
|
|
8
|
+
function isFixed(file, trustedFiles = []) {
|
|
9
|
+
return trustedFiles.includes(file) || isBuildConfig(file) || /(?:^|\/)(?:\.|(?:macos|ios|android|windows|Pods)(?:\/|$))/i.test(file) ||
|
|
10
|
+
/^(?:package\.json|app\.json|\.babelrc.*|babel\..*|metro\..*|tsconfig.*|jsconfig.*|.*lock.*|.*\.(?:sh|bash|zsh|ps1|rb|podspec))$/i.test(path.posix.basename(file));
|
|
11
|
+
}
|
|
12
|
+
function assertCustomizeChanges(before, after, trustedFiles = []) {
|
|
13
|
+
for (const file of Object.keys({ ...before, ...after })) {
|
|
14
|
+
if (before[file] !== after[file] && isFixed(file, trustedFiles)) throw new Error(`Build/native/dependency configuration is fixed: ${file}`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
// Run only when publishing the signed source snapshot. Follow local executable
|
|
18
|
+
// imports so a transform cannot be edited indirectly through an innocuous name.
|
|
19
|
+
function collectTrustedFiles(root) {
|
|
20
|
+
const ts = require('typescript');
|
|
21
|
+
const trusted = new Set();
|
|
22
|
+
function visit(file) {
|
|
23
|
+
file = file.split(path.sep).join('/');
|
|
24
|
+
if (trusted.has(file)) return;
|
|
25
|
+
trusted.add(file);
|
|
26
|
+
if (/\.json$/.test(file) || /^\.babelrc$/.test(path.basename(file))) {
|
|
27
|
+
const parsed = ts.parseConfigFileTextToJson(file, fs.readFileSync(path.join(root, file), 'utf8'));
|
|
28
|
+
if (parsed.error) throw new Error(`Invalid build configuration JSON: ${file}`);
|
|
29
|
+
const data = parsed.config;
|
|
30
|
+
function jsonDependencies(value, key = '') {
|
|
31
|
+
if (typeof value === 'string' && value.startsWith('.') && ['plugins', 'presets', 'extends', 'babelTransformerPath', 'transformerPath'].includes(key)) dependency(value);
|
|
32
|
+
else if (Array.isArray(value)) for (const item of value) jsonDependencies(item, key);
|
|
33
|
+
else if (value && typeof value === 'object') for (const [name, item] of Object.entries(value)) jsonDependencies(item, name);
|
|
34
|
+
}
|
|
35
|
+
jsonDependencies(data); return;
|
|
36
|
+
}
|
|
37
|
+
if (!/\.[cm]?[jt]sx?$/.test(file)) return;
|
|
38
|
+
const tree = ts.createSourceFile(file, fs.readFileSync(path.join(root, file), 'utf8'), ts.ScriptTarget.Latest, true);
|
|
39
|
+
function dependency(specifier) {
|
|
40
|
+
if (!specifier.startsWith('.') && !path.isAbsolute(specifier)) return; // frozen toolkit dependency
|
|
41
|
+
const target = path.resolve(root, path.dirname(file), specifier);
|
|
42
|
+
if (!target.startsWith(path.resolve(root) + path.sep)) throw new Error(`Build configuration imports outside the snapshot: ${file}`);
|
|
43
|
+
const packageFile = path.join(target, 'package.json');
|
|
44
|
+
const packageEntry = fs.existsSync(packageFile) && fs.statSync(target).isDirectory() ? JSON.parse(fs.readFileSync(packageFile, 'utf8')).main : undefined;
|
|
45
|
+
if (packageEntry) visit(path.relative(root, packageFile));
|
|
46
|
+
const resolved = [target, ...(packageEntry ? [path.resolve(target, packageEntry)] : []), ...['.js', '.cjs', '.mjs', '.ts', '.tsx', '.json', '/index.js', '/index.ts'].map(suffix => target + suffix)].find(name => fs.existsSync(name) && fs.statSync(name).isFile());
|
|
47
|
+
if (!resolved) throw new Error(`Missing build configuration dependency in snapshot: ${file} -> ${specifier}`);
|
|
48
|
+
if (!resolved.startsWith(path.resolve(root) + path.sep)) throw new Error(`Build configuration dependency escapes snapshot: ${file}`);
|
|
49
|
+
if (fs.lstatSync(resolved).isSymbolicLink()) throw new Error(`Build configuration dependency is a symlink: ${file}`);
|
|
50
|
+
visit(path.relative(root, resolved));
|
|
51
|
+
}
|
|
52
|
+
const variables = new Map();
|
|
53
|
+
function collect(node) {
|
|
54
|
+
if (ts.isVariableDeclaration(node) && (node.parent.flags & ts.NodeFlags.Const) && ts.isIdentifier(node.name) && node.initializer) variables.set(node.name.text, node.initializer);
|
|
55
|
+
ts.forEachChild(node, collect);
|
|
56
|
+
}
|
|
57
|
+
collect(tree);
|
|
58
|
+
function fixedTarget(node, seen = new Set()) {
|
|
59
|
+
if (ts.isParenthesizedExpression(node)) return fixedTarget(node.expression, seen);
|
|
60
|
+
if (ts.isIdentifier(node) && variables.has(node.text) && !seen.has(node.text)) return fixedTarget(variables.get(node.text), new Set([...seen, node.text]));
|
|
61
|
+
if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken) return fixedTarget(node.right, seen);
|
|
62
|
+
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.expression.getText(tree) === 'path' && ['join', 'resolve'].includes(node.expression.name.text)) {
|
|
63
|
+
const last = node.arguments.at(-1);
|
|
64
|
+
return last && ts.isStringLiteralLike(last) && /(?:^|\.)config\.[cm]?[jt]s$/.test(last.text) && path.basename(last.text) === last.text;
|
|
65
|
+
}
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
function walk(node) {
|
|
69
|
+
if (ts.isStringLiteralLike(node) && node.text.startsWith('.')) {
|
|
70
|
+
let owner = node.parent;
|
|
71
|
+
while (ts.isArrayLiteralExpression(owner)) owner = owner.parent;
|
|
72
|
+
if (ts.isPropertyAssignment(owner) && ['plugins', 'presets', 'extends', 'babelTransformerPath', 'transformerPath'].includes(owner.name.getText(tree).replace(/['"]/g, ''))) dependency(node.text);
|
|
73
|
+
const target = path.resolve(root, path.dirname(file), node.text);
|
|
74
|
+
const candidates = fs.existsSync(target) && fs.statSync(target).isDirectory() ? [] : path.extname(target) ? [target] : [target, ...['.js', '.cjs', '.mjs', '.ts', '.tsx', '/index.js', '/index.ts'].map(suffix => target + suffix)];
|
|
75
|
+
for (const name of candidates) {
|
|
76
|
+
if (!name.startsWith(path.resolve(root) + path.sep)) throw new Error(`Build configuration references outside the snapshot: ${file}`);
|
|
77
|
+
if (fs.existsSync(name)) dependency('./' + path.relative(path.dirname(path.join(root, file)), name));
|
|
78
|
+
else trusted.add(path.relative(root, name).split(path.sep).join('/'));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
let specifier;
|
|
82
|
+
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier) specifier = node.moduleSpecifier;
|
|
83
|
+
if (ts.isCallExpression(node) && ((ts.isIdentifier(node.expression) && node.expression.text === 'require') || node.expression.kind === ts.SyntaxKind.ImportKeyword || (ts.isPropertyAccessExpression(node.expression) && node.expression.expression.getText(tree) === 'require' && node.expression.name.text === 'resolve'))) specifier = node.arguments[0];
|
|
84
|
+
if (specifier) {
|
|
85
|
+
if (ts.isStringLiteralLike(specifier)) dependency(specifier.text);
|
|
86
|
+
else if (!fixedTarget(specifier)) throw new Error(`Build configuration must use static imports or a fixed config basename: ${file}`);
|
|
87
|
+
}
|
|
88
|
+
ts.forEachChild(node, walk);
|
|
89
|
+
}
|
|
90
|
+
walk(tree);
|
|
91
|
+
}
|
|
92
|
+
function scan(directory = '') {
|
|
93
|
+
for (const name of fs.readdirSync(path.join(root, directory))) {
|
|
94
|
+
const relative = path.join(directory, name), info = fs.lstatSync(path.join(root, relative));
|
|
95
|
+
if (info.isSymbolicLink()) throw new Error(`Source snapshot contains a symlink: ${relative}`);
|
|
96
|
+
if (info.isDirectory()) { if (name !== 'node_modules') scan(relative); }
|
|
97
|
+
else if (isBuildConfig(relative.split(path.sep).join('/'))) visit(relative);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
scan(); return [...trusted].sort();
|
|
101
|
+
}
|
|
102
|
+
module.exports = { isBuildConfig, isFixed, assertCustomizeChanges, collectTrustedFiles };
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
// Downloadable customize worker. No toolchain code is linked into the application.
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const crypto = require('node:crypto');
|
|
5
|
+
const { createRequire } = require('node:module');
|
|
6
|
+
const { spawn } = require('node:child_process');
|
|
7
|
+
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
|
|
8
|
+
const read = file => JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
9
|
+
function write(file, value) {
|
|
10
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
11
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
12
|
+
fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
|
|
13
|
+
fs.renameSync(temporary, file);
|
|
14
|
+
}
|
|
15
|
+
function safe(root, relative) {
|
|
16
|
+
if (typeof relative !== 'string' || !relative || path.isAbsolute(relative) || relative.split(/[\\/]/).some(p => !p || p === '.' || p === '..' || p === 'node_modules' || p.startsWith('.spark'))) throw new Error('Invalid workspace path');
|
|
17
|
+
const file = path.join(root, relative);
|
|
18
|
+
let current = root;
|
|
19
|
+
for (const part of relative.split('/')) {
|
|
20
|
+
current = path.join(current, part);
|
|
21
|
+
if (fs.existsSync(current) && fs.lstatSync(current).isSymbolicLink()) throw new Error('Workspace symlinks are not editable');
|
|
22
|
+
}
|
|
23
|
+
return file;
|
|
24
|
+
}
|
|
25
|
+
function snapshot(root) {
|
|
26
|
+
const result = {};
|
|
27
|
+
function visit(relative) {
|
|
28
|
+
for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true }).sort((a,b) => a.name.localeCompare(b.name))) {
|
|
29
|
+
if (['node_modules', '.spark', '.expo', '.threaded-runtime', '.git'].includes(entry.name)) continue;
|
|
30
|
+
const name = path.posix.join(relative, entry.name), file = path.join(root, name);
|
|
31
|
+
if (entry.isSymbolicLink()) throw new Error(`Source symlink: ${name}`);
|
|
32
|
+
if (entry.isDirectory()) visit(name);
|
|
33
|
+
else if (entry.isFile()) result[name] = fs.readFileSync(file).toString('base64');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
visit(''); return result;
|
|
37
|
+
}
|
|
38
|
+
function restore(root, files) {
|
|
39
|
+
fs.mkdirSync(root, { recursive: true });
|
|
40
|
+
for (const [name, bytes] of Object.entries(files)) {
|
|
41
|
+
const file = safe(root, name); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, Buffer.from(bytes, 'base64'));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function patch(base, modified) {
|
|
45
|
+
return Object.keys({ ...base, ...modified }).sort().filter(name => base[name] !== modified[name]).map(name => ({ path: name, before: base[name] ?? null, after: modified[name] ?? null }));
|
|
46
|
+
}
|
|
47
|
+
function text(bytes) {
|
|
48
|
+
const value = Buffer.from(bytes, 'base64');
|
|
49
|
+
if (value.includes(0)) return undefined;
|
|
50
|
+
const decoded = value.toString('utf8');
|
|
51
|
+
return Buffer.from(decoded).equals(value) ? decoded : undefined;
|
|
52
|
+
}
|
|
53
|
+
function reviewPatch(changes) {
|
|
54
|
+
const { createTwoFilesPatch } = require('diff');
|
|
55
|
+
return changes.map(change => {
|
|
56
|
+
const before = change.before === null ? '' : text(change.before), after = change.after === null ? '' : text(change.after);
|
|
57
|
+
return before === undefined || after === undefined ? `${change.path}: binary file changed\n` : createTwoFilesPatch(change.path, change.path, before, after);
|
|
58
|
+
}).join('\n');
|
|
59
|
+
}
|
|
60
|
+
function mergeText(base, ours, theirs) {
|
|
61
|
+
const { diffArrays } = require('diff');
|
|
62
|
+
const lines = value => value.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
63
|
+
const original = lines(base);
|
|
64
|
+
function edits(value) {
|
|
65
|
+
let offset = 0, pending;
|
|
66
|
+
const output = [];
|
|
67
|
+
for (const part of diffArrays(original, lines(value))) {
|
|
68
|
+
if (!part.added && !part.removed) { if (pending) output.push(pending); pending = undefined; offset += part.count; }
|
|
69
|
+
else {
|
|
70
|
+
pending ??= { start: offset, end: offset, lines: [] };
|
|
71
|
+
if (part.removed) { offset += part.count; pending.end = offset; }
|
|
72
|
+
else pending.lines.push(...part.value);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (pending) output.push(pending);
|
|
76
|
+
return output;
|
|
77
|
+
}
|
|
78
|
+
const left = edits(ours), right = edits(theirs), all = [...left];
|
|
79
|
+
for (const edit of right) {
|
|
80
|
+
let identical = false;
|
|
81
|
+
for (const existing of left) {
|
|
82
|
+
if (JSON.stringify(edit) === JSON.stringify(existing)) { identical = true; break; }
|
|
83
|
+
// Adjacent changes can be merged; insertions at a changed boundary are conservative conflicts.
|
|
84
|
+
if (Math.max(edit.start, existing.start) < Math.min(edit.end, existing.end) ||
|
|
85
|
+
(edit.start === edit.end && edit.start >= existing.start && edit.start <= existing.end) ||
|
|
86
|
+
(existing.start === existing.end && existing.start >= edit.start && existing.start <= edit.end)) return undefined;
|
|
87
|
+
}
|
|
88
|
+
if (!identical) all.push(edit);
|
|
89
|
+
}
|
|
90
|
+
let output = '', offset = 0;
|
|
91
|
+
for (const edit of all.sort((a,b) => a.start - b.start)) { output += original.slice(offset, edit.start).join('') + edit.lines.join(''); offset = edit.end; }
|
|
92
|
+
return output + original.slice(offset).join('');
|
|
93
|
+
}
|
|
94
|
+
function merge(base, ours, theirs) {
|
|
95
|
+
const files = {}, conflicts = [];
|
|
96
|
+
for (const name of Object.keys({ ...base, ...ours, ...theirs }).sort()) {
|
|
97
|
+
const b = base[name], o = ours[name], t = theirs[name];
|
|
98
|
+
let value;
|
|
99
|
+
if (o === b || o === t) value = t;
|
|
100
|
+
else if (t === b) value = o;
|
|
101
|
+
else if (b !== undefined && o !== undefined && t !== undefined && [b,o,t].every(v => text(v) !== undefined)) {
|
|
102
|
+
const merged = mergeText(text(b), text(o), text(t));
|
|
103
|
+
if (merged !== undefined) value = Buffer.from(merged).toString('base64');
|
|
104
|
+
else conflicts.push(name);
|
|
105
|
+
} else conflicts.push(name);
|
|
106
|
+
// Keep the new upstream file in conflicts. Original and modified versions remain in the request.
|
|
107
|
+
if (conflicts.at(-1) === name) value = t;
|
|
108
|
+
if (value !== undefined) files[name] = value;
|
|
109
|
+
}
|
|
110
|
+
return { files, conflicts };
|
|
111
|
+
}
|
|
112
|
+
function validateManifest(manifest) {
|
|
113
|
+
if (manifest.schema !== 1 || !/^[a-f0-9]{64}$/.test(manifest.release) || manifest.runtime?.platform !== 'macos' || manifest.runtime?.mode !== 'release' || !manifest.project || !manifest.version) throw new Error('Invalid customize manifest');
|
|
114
|
+
for (const asset of [manifest.source, manifest.toolkit]) if (!asset || !/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/releases\/download\/[\w.-]+\/[\w.-]+$/.test(asset.url) || !/^[a-f0-9]{64}$/.test(asset.sha256) || !Number.isSafeInteger(asset.size) || asset.size <= 0) throw new Error('Invalid customize asset');
|
|
115
|
+
if (manifest.projectRoot !== undefined && manifest.projectRoot !== '.') safe('/snapshot', manifest.projectRoot);
|
|
116
|
+
safe('/snapshot', manifest.entry);
|
|
117
|
+
return manifest;
|
|
118
|
+
}
|
|
119
|
+
function prepare(manifest, source, toolkit, support) {
|
|
120
|
+
validateManifest(manifest);
|
|
121
|
+
const directory = path.join(support, 'releases', manifest.release);
|
|
122
|
+
if (fs.existsSync(path.join(directory, 'state.json'))) {
|
|
123
|
+
const accepting = path.join(directory, 'accepting.json');
|
|
124
|
+
if (fs.existsSync(accepting)) {
|
|
125
|
+
const pending = read(accepting);
|
|
126
|
+
for (const file of [pending.backup, pending.staged]) if (path.dirname(file) !== directory) throw new Error('Invalid acceptance recovery path');
|
|
127
|
+
if (!fs.existsSync(path.join(directory, 'work')) && fs.existsSync(pending.backup)) fs.renameSync(pending.backup, path.join(directory, 'work'));
|
|
128
|
+
fs.rmSync(accepting, { force: true });
|
|
129
|
+
}
|
|
130
|
+
const state = read(path.join(directory, 'state.json'));
|
|
131
|
+
if (state.toolkit !== toolkit) { state.toolkit = toolkit; write(path.join(directory, 'state.json'), state); }
|
|
132
|
+
return directory;
|
|
133
|
+
}
|
|
134
|
+
const stage = `${directory}.pending-${process.pid}`;
|
|
135
|
+
fs.mkdirSync(stage, { recursive: true });
|
|
136
|
+
try {
|
|
137
|
+
const base = snapshot(source);
|
|
138
|
+
restore(path.join(stage, 'base'), base); restore(path.join(stage, 'work'), base);
|
|
139
|
+
write(path.join(stage, 'manifest.json'), manifest);
|
|
140
|
+
write(path.join(stage, 'state.json'), { schema: 1, toolkit, created: new Date().toISOString(), history: [], status: 'original' });
|
|
141
|
+
fs.mkdirSync(path.dirname(directory), { recursive: true }); fs.renameSync(stage, directory);
|
|
142
|
+
} finally { fs.rmSync(stage, { recursive: true, force: true }); }
|
|
143
|
+
return directory;
|
|
144
|
+
}
|
|
145
|
+
function migrate(from, to) {
|
|
146
|
+
const previous = read(path.join(from, 'manifest.json')), current = read(path.join(to, 'manifest.json'));
|
|
147
|
+
if (previous.project !== current.project || previous.release === current.release) throw new Error('Migration requires two releases of the same app');
|
|
148
|
+
const state = read(path.join(to, 'state.json'));
|
|
149
|
+
if (state.history.length || state.migration) throw new Error('This release already has edits or a migration; preserve it before preparing another');
|
|
150
|
+
const base = snapshot(path.join(from, 'base')), ours = snapshot(path.join(from, 'work')), theirs = snapshot(path.join(to, 'base'));
|
|
151
|
+
const result = merge(base, ours, theirs);
|
|
152
|
+
const id = crypto.randomUUID(), candidate = path.join(to, 'candidates', id);
|
|
153
|
+
restore(candidate, result.files);
|
|
154
|
+
const history = read(path.join(from, 'state.json')).history;
|
|
155
|
+
state.inheritedPrompts = [...(read(path.join(from, 'state.json')).inheritedPrompts ?? []), ...history.filter(item => item.status === 'accepted').map(item => ({ prompt: item.prompt, baseRelease: item.baseRelease, patch: item.patch }))];
|
|
156
|
+
const request = { schema: 1, kind: 'migration', from: previous.release, to: current.release,
|
|
157
|
+
prompts: [...state.inheritedPrompts, ...history.filter(item => item.status !== 'accepted')].map(item => ({ prompt: item.prompt, status: item.status, patch: item.patch })), patch: patch(base, ours),
|
|
158
|
+
upstream: patch(base, theirs), conflicts: result.conflicts };
|
|
159
|
+
write(path.join(to, 'migration.json'), request);
|
|
160
|
+
fs.writeFileSync(path.join(to, 'review.txt'), 'Migration from ' + previous.version + ' to ' + current.version + '\n\nConflicts: ' + (result.conflicts.join(', ') || 'none') + '\n\nContributing prompts\n\n' + state.inheritedPrompts.map(item => item.prompt).join('\n\n') + '\n\nChanges from accepted source\n\n' + reviewPatch(patch(snapshot(path.join(to, 'work')), result.files)));
|
|
161
|
+
state.migration = { from: previous.release, candidate: id, conflicts: result.conflicts, status: 'needs-review' };
|
|
162
|
+
write(path.join(to, 'state.json'), state);
|
|
163
|
+
return state.migration;
|
|
164
|
+
}
|
|
165
|
+
const children = new Set();
|
|
166
|
+
async function execute(command, args, options = {}) {
|
|
167
|
+
return new Promise((resolve, reject) => {
|
|
168
|
+
const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], ...options });
|
|
169
|
+
children.add(child); child.once('close', () => children.delete(child));
|
|
170
|
+
let output = '';
|
|
171
|
+
for (const stream of [child.stdout, child.stderr]) stream.on('data', value => { output = (output + value).slice(-20000); });
|
|
172
|
+
child.on('error', reject);
|
|
173
|
+
child.on('close', code => code === 0 ? resolve(output) : reject(new Error(`${path.basename(command)} exited ${code}\n${output}`)));
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
function attachDependencies(workspace, toolkit) {
|
|
177
|
+
const modules = path.join(workspace, 'node_modules');
|
|
178
|
+
if (!fs.existsSync(modules)) fs.symlinkSync(path.join(toolkit, 'node_modules'), modules);
|
|
179
|
+
}
|
|
180
|
+
async function build(directory, candidate = 'work') {
|
|
181
|
+
fs.rmSync(path.join(directory, 'ready.json'), { force: true });
|
|
182
|
+
const state = read(path.join(directory, 'state.json')), manifest = validateManifest(read(path.join(directory, 'manifest.json')));
|
|
183
|
+
const workspace = candidate === 'work' ? path.join(directory, 'work') : safe(path.join(directory, 'candidates'), candidate);
|
|
184
|
+
const toolkit = state.toolkit, metadata = read(path.join(toolkit, 'toolkit.json'));
|
|
185
|
+
if (metadata.arch !== process.arch || metadata.framework !== manifest.runtime.framework || hash(fs.readFileSync(path.join(toolkit, 'hermesc'))) !== metadata.compiler) throw new Error('Incompatible customize toolkit');
|
|
186
|
+
require('./customize-policy.cjs').assertCustomizeChanges(snapshot(path.join(directory, 'base')), snapshot(workspace), manifest.customize?.trustedFiles);
|
|
187
|
+
attachDependencies(workspace, toolkit);
|
|
188
|
+
const project = !manifest.projectRoot || manifest.projectRoot === '.' ? workspace : safe(workspace, manifest.projectRoot);
|
|
189
|
+
attachDependencies(project, toolkit);
|
|
190
|
+
const req = createRequire(path.join(project, 'package.json'));
|
|
191
|
+
const expoPackage = req.resolve('expo/package.json'), expo = read(expoPackage);
|
|
192
|
+
const bin = path.resolve(path.dirname(expoPackage), typeof expo.bin === 'string' ? expo.bin : expo.bin.expo);
|
|
193
|
+
const id = crypto.randomUUID(), output = path.join(directory, 'builds', id);
|
|
194
|
+
fs.mkdirSync(output, { recursive: true });
|
|
195
|
+
const env = { ...process.env, CI: '1', NODE_ENV: 'production', SPARK_PLATFORM: 'macos', EXPO_NO_TELEMETRY: '1' };
|
|
196
|
+
// Discover worker roots using the same two-pass pipeline as Spark's release build.
|
|
197
|
+
// One worker avoids Bun's jest-worker fork/IPC incompatibility and keeps memory bounded.
|
|
198
|
+
const args = ['export:embed', '--platform', 'macos', '--entry-file', manifest.entry, '--bundle-output', path.join(output, 'app.js'), '--sourcemap-output', path.join(output, 'app.map'), '--assets-dest', output, '--dev', 'false', '--minify', 'true', '--max-workers', '1'];
|
|
199
|
+
await execute(process.execPath, [bin, ...args], { cwd: project, env: { ...env, SPARK_RUNTIME_DISCOVERY: '1' } });
|
|
200
|
+
const sources = read(path.join(output, 'app.map')).sources;
|
|
201
|
+
const roots = sources.map(source => fs.existsSync(path.resolve(project, source)) ? path.resolve(project, source) : path.resolve(project, source.replace(/^\//, ''))).filter(file => fs.existsSync(file) && /\.[jt]sx?$/.test(file) && !file.endsWith('.d.ts'));
|
|
202
|
+
const runtimeSources = path.join(output, 'runtime-sources.json');
|
|
203
|
+
write(runtimeSources, { enabled: sources.some(source => source.includes('@react-native-runtimes/core/') && !source.endsWith('secondary-runtime-polyfill.js')), roots });
|
|
204
|
+
await execute(process.execPath, [bin, ...args], { cwd: project, env: { ...env, SPARK_RUNTIME_SOURCES: runtimeSources } });
|
|
205
|
+
// A production edit may only import native modules present in the frozen shell.
|
|
206
|
+
const selected = manifest.runtime.modules;
|
|
207
|
+
for (const source of read(path.join(output, 'app.map')).sources) {
|
|
208
|
+
const file = fs.existsSync(path.resolve(project, source)) ? path.resolve(project, source) : path.resolve(project, source.replace(/^\//, ''));
|
|
209
|
+
if (!fs.existsSync(file)) continue;
|
|
210
|
+
let folder = path.dirname(fs.realpathSync(file));
|
|
211
|
+
while (folder !== path.dirname(folder)) {
|
|
212
|
+
const packageFile = path.join(folder, 'package.json');
|
|
213
|
+
if (fs.existsSync(packageFile)) {
|
|
214
|
+
const pkg = read(packageFile);
|
|
215
|
+
if ((pkg.codegenConfig || pkg.spark?.nativeModules || fs.existsSync(path.join(folder, 'expo-module.config.json'))) && !selected[pkg.name]) throw new Error(`Native module is not available in this shell: ${pkg.name}`);
|
|
216
|
+
break;
|
|
217
|
+
}
|
|
218
|
+
folder = path.dirname(folder);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
await execute(path.join(toolkit, 'hermesc'), ['-O', '-emit-binary', '-out', path.join(output, 'main.jsbundle'), path.join(output, 'app.js')]);
|
|
222
|
+
const record = { schema: 1, release: manifest.release, fingerprint: manifest.runtime.fingerprint, build: id, bundleHash: hash(fs.readFileSync(path.join(output, 'main.jsbundle'))), candidate, sourceHash: hash(JSON.stringify(snapshot(workspace))) };
|
|
223
|
+
write(path.join(directory, 'ready.json'), record);
|
|
224
|
+
return record;
|
|
225
|
+
}
|
|
226
|
+
function verify(directory) {
|
|
227
|
+
const ready = read(path.join(directory, 'ready.json'));
|
|
228
|
+
const manifest = validateManifest(read(path.join(directory, 'manifest.json')));
|
|
229
|
+
const workspace = ready.candidate === 'work' ? path.join(directory, 'work') : safe(path.join(directory, 'candidates'), ready.candidate);
|
|
230
|
+
if (ready.release !== manifest.release || ready.sourceHash !== hash(JSON.stringify(snapshot(workspace)))) throw new Error('Source changed after validation; rebuild before accepting');
|
|
231
|
+
if (ready.fingerprint !== manifest.runtime.fingerprint || !/^[a-f0-9-]{36}$/.test(ready.build) || hash(fs.readFileSync(path.join(directory, 'builds', ready.build, 'main.jsbundle'))) !== ready.bundleHash) throw new Error('Compiled candidate is incompatible or corrupted');
|
|
232
|
+
return ready;
|
|
233
|
+
}
|
|
234
|
+
function accept(directory) {
|
|
235
|
+
const ready = verify(directory);
|
|
236
|
+
const workspace = ready.candidate === 'work' ? path.join(directory, 'work') : safe(path.join(directory, 'candidates'), ready.candidate);
|
|
237
|
+
const state = read(path.join(directory, 'state.json'));
|
|
238
|
+
if (ready.candidate !== 'work') {
|
|
239
|
+
const staged = path.join(directory, 'accept-' + crypto.randomUUID());
|
|
240
|
+
fs.cpSync(workspace, staged, { recursive: true, verbatimSymlinks: true });
|
|
241
|
+
const backup = path.join(directory, 'work-before-' + crypto.randomUUID());
|
|
242
|
+
write(path.join(directory, 'accepting.json'), { backup, staged });
|
|
243
|
+
fs.renameSync(path.join(directory, 'work'), backup);
|
|
244
|
+
try { fs.renameSync(staged, path.join(directory, 'work')); fs.rmSync(path.join(directory, 'accepting.json'), { force: true }); }
|
|
245
|
+
catch (error) { fs.rmSync(path.join(directory, 'work'), { recursive: true, force: true }); fs.renameSync(backup, path.join(directory, 'work')); throw error; }
|
|
246
|
+
const event = state.history.find(item => item.candidate === ready.candidate);
|
|
247
|
+
for (const item of state.history) if (item.candidate === ready.candidate || event?.ancestors?.includes(item.id)) item.status = 'accepted';
|
|
248
|
+
if (state.migration?.candidate === ready.candidate) state.migration.status = 'accepted';
|
|
249
|
+
}
|
|
250
|
+
state.status = 'customized';
|
|
251
|
+
write(path.join(directory, 'patch.json'), patch(snapshot(path.join(directory, 'base')), snapshot(path.join(directory, 'work'))));
|
|
252
|
+
write(path.join(directory, 'state.json'), state);
|
|
253
|
+
// Native host owns activation/recovery. Never modify a signed application from the worker.
|
|
254
|
+
return ready;
|
|
255
|
+
}
|
|
256
|
+
module.exports = { reviewPatch, safe, snapshot, restore, patch, merge, mergeText, validateManifest, prepare, migrate, execute, build, verify, accept, read, write, hash };
|
|
257
|
+
if (require.main === module) {
|
|
258
|
+
const initialize = require('./js-runtime.cjs').initializeRuntime;
|
|
259
|
+
(async () => {
|
|
260
|
+
await initialize();
|
|
261
|
+
for (const signal of ['SIGTERM','SIGINT']) process.once(signal, () => { for (const child of children) child.kill(signal); setTimeout(() => process.exit(signal === 'SIGINT' ? 130 : 143), 300).unref(); });
|
|
262
|
+
const [command, ...args] = process.argv.slice(2);
|
|
263
|
+
let result;
|
|
264
|
+
if (command === 'prepare') result = prepare(read(args[0]), args[1], args[2], args[3]);
|
|
265
|
+
else if (command === 'migrate') result = migrate(args[0], args[1]);
|
|
266
|
+
else if (command === 'build') result = await build(args[0], args[1]);
|
|
267
|
+
else if (command === 'verify') result = verify(args[0]);
|
|
268
|
+
else if (command === 'accept') result = accept(args[0]);
|
|
269
|
+
else if (command === 'prompt') result = await require('./customize-ai.cjs').prompt(args[0], read(args[1]));
|
|
270
|
+
else throw new Error('Expected prepare, migrate, prompt, build, verify, or accept');
|
|
271
|
+
console.log(JSON.stringify(result));
|
|
272
|
+
})().catch(error => { console.error(error.message); process.exitCode = 1; });
|
|
273
|
+
}
|