tauri-plugin-live-activity 0.2.0 → 0.3.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.
- package/README.ko.md +127 -449
- package/README.md +127 -453
- package/cli/bin.mjs +4 -0
- package/cli/ios.mjs +186 -0
- package/cli/main.mjs +69 -0
- package/cli/plist.mjs +83 -0
- package/cli/report.mjs +26 -0
- package/cli/setup.mjs +142 -0
- package/cli/steps.mjs +82 -0
- package/cli/widget-files.mjs +148 -0
- package/cli/xcodegen.mjs +187 -0
- package/dist-js/index.d.ts +8 -0
- package/dist-js/index.js +11 -0
- package/dist-js/layout.d.ts +14 -3
- package/dist-js/layout.js +18 -3
- package/dist-js/types.d.ts +67 -16
- package/package.json +5 -3
package/cli/bin.mjs
ADDED
package/cli/ios.mjs
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// The iOS part of setup: Info.ios.plist, the widget files in gen/apple with the fonts and images it
|
|
2
|
+
// bundles, the XcodeGen spec that adds the widget extension, the App Group, the plugin's Swift package
|
|
3
|
+
// and the regenerated Xcode project.
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { cpSync, existsSync, readdirSync } from 'node:fs';
|
|
6
|
+
import { join, relative, resolve, sep } from 'node:path';
|
|
7
|
+
import { newPlist, setTrueKey } from './plist.mjs';
|
|
8
|
+
import { SetupError, parseJson, readText, step, tail, which, writeFile } from './steps.mjs';
|
|
9
|
+
import { assetSteps, bundledFonts, fontSteps } from './widget-files.mjs';
|
|
10
|
+
import { SPEC_FILE, WIDGET, addInclude, appGroupOf, readProject, widgetSpec, writtenBySetup } from './xcodegen.mjs';
|
|
11
|
+
|
|
12
|
+
const TEMPLATES = ['LiveActivityWidget.swift', 'LiveActivityActionIntent.swift', 'LiveActivityCustomRegistry.swift', 'Info.plist'];
|
|
13
|
+
/** The app's own file: created once from the template and never written again. */
|
|
14
|
+
const CUSTOM_VIEWS = 'LiveActivityCustomViews.swift';
|
|
15
|
+
const GROUP = /^group\.[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*$/;
|
|
16
|
+
const PLIST_KEY = 'NSSupportsLiveActivities';
|
|
17
|
+
// Left out of the copy of Tauri's Swift API, as the plugin's build script does.
|
|
18
|
+
const NOT_COPIED = ['.build', 'Package.resolved', 'Tests'];
|
|
19
|
+
|
|
20
|
+
export function iosSteps(context) {
|
|
21
|
+
const { srcTauri, platform, show } = context;
|
|
22
|
+
if (platform !== 'darwin') return [step('skipped', 'iOS', 'needs a Mac with Xcode')];
|
|
23
|
+
const apple = join(srcTauri, 'gen', 'apple');
|
|
24
|
+
const specPath = join(apple, 'project.yml');
|
|
25
|
+
const yaml = readText(specPath);
|
|
26
|
+
if (yaml === undefined) {
|
|
27
|
+
return [step('skipped', 'iOS', 'no src-tauri/gen/apple yet: run `tauri ios init`, then run setup again')];
|
|
28
|
+
}
|
|
29
|
+
const project = readProject(yaml);
|
|
30
|
+
const plist = infoPlistStep(context);
|
|
31
|
+
if (project.widget) {
|
|
32
|
+
const detail = `already has a widget extension, ${project.widget}; add the plugin's widget to it by hand (docs/ios-integration.md)`;
|
|
33
|
+
const { files, appGroup } = context;
|
|
34
|
+
const given = [files.fonts.length && '--font', files.assets.length && '--asset', appGroup && '--app-group'].filter(Boolean);
|
|
35
|
+
const left = given.length === 0 ? [] : [step('todo', show(specPath), `${given.join(', ')} not applied: that widget is yours to give fonts, images and an App Group (docs/ios-integration.md)`)];
|
|
36
|
+
return [plist, step('skipped', show(specPath), detail), ...left];
|
|
37
|
+
}
|
|
38
|
+
if (!project.appTarget) {
|
|
39
|
+
const detail = `no target named ${project.name ?? '<name>'}_iOS, so setup did not add the widget; see docs/usage.md`;
|
|
40
|
+
return [plist, step('todo', show(specPath), detail)];
|
|
41
|
+
}
|
|
42
|
+
const widget = join(apple, WIDGET);
|
|
43
|
+
const appGroup = appGroupFor(context, apple, project);
|
|
44
|
+
const include = includeStep(context, specPath, yaml);
|
|
45
|
+
// XcodeGen lists the files of a folder when it generates, so a new widget file also needs a run.
|
|
46
|
+
const projectSteps = [
|
|
47
|
+
...templateSteps(context, apple), customViewsStep(context, widget), ...fontSteps(context, widget), ...assetSteps(context, widget),
|
|
48
|
+
specStep(context, apple, project, { fonts: bundledFonts(context, widget), appGroup }), include,
|
|
49
|
+
];
|
|
50
|
+
return [plist, ...projectSteps, swiftPackageStep(context), xcodegenStep(context, apple, specPath, projectSteps, include)];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The App Group of `--app-group`: the group it names, or `group.<app identifier>`. A spec that setup wrote
|
|
55
|
+
* with a group keeps it on later runs.
|
|
56
|
+
*/
|
|
57
|
+
function appGroupFor({ appGroup, config }, apple, project) {
|
|
58
|
+
const kept = appGroupOf(readText(join(apple, SPEC_FILE)));
|
|
59
|
+
const group = typeof appGroup === 'string' ? appGroup : kept ?? (appGroup ? `group.${project.bundleId ?? config.identifier}` : undefined);
|
|
60
|
+
if (group !== undefined && !GROUP.test(group)) {
|
|
61
|
+
throw new SetupError(`The App Group ${JSON.stringify(group)} must be "group." followed by letters, digits, '-' and '.'.`);
|
|
62
|
+
}
|
|
63
|
+
return group;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** LiveActivityCustomViews.swift belongs to the app: created once, then never written again. */
|
|
67
|
+
function customViewsStep({ plugin, show }, widget) {
|
|
68
|
+
const path = join(widget, CUSTOM_VIEWS);
|
|
69
|
+
if (readText(path) !== undefined) return step('unchanged', show(path));
|
|
70
|
+
const stub = readText(join(plugin.dir, 'templates', 'ios', CUSTOM_VIEWS));
|
|
71
|
+
if (stub === undefined) throw new SetupError(`The plugin crate at ${plugin.dir} has no templates/ios/${CUSTOM_VIEWS}.`);
|
|
72
|
+
return step('created', show(path), 'yours, for custom views; setup never changes it again', writeFile(path, stub));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Tauri merges src-tauri/Info.ios.plist into the app's Info.plist when it builds. */
|
|
76
|
+
function infoPlistStep({ srcTauri, show }) {
|
|
77
|
+
const path = join(srcTauri, 'Info.ios.plist');
|
|
78
|
+
const text = readText(path);
|
|
79
|
+
if (text === undefined) return step('created', show(path), `${PLIST_KEY} = true`, writeFile(path, newPlist(PLIST_KEY)));
|
|
80
|
+
const result = setTrueKey(text, PLIST_KEY);
|
|
81
|
+
if (result.status === 'present') return step('unchanged', show(path));
|
|
82
|
+
if (result.status === 'added') return step('updated', show(path), `${PLIST_KEY} = true`, writeFile(path, result.text));
|
|
83
|
+
if (result.status === 'unreadable') {
|
|
84
|
+
return step('todo', show(path), `add ${PLIST_KEY} = YES to it; setup reads XML plists only`);
|
|
85
|
+
}
|
|
86
|
+
return step('kept', show(path), `it sets ${PLIST_KEY} to something other than true; Live Activities need true`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function templateSteps({ plugin, show }, apple) {
|
|
90
|
+
return TEMPLATES.map(name => {
|
|
91
|
+
const wanted = readText(join(plugin.dir, 'templates', 'ios', name));
|
|
92
|
+
if (wanted === undefined) throw new SetupError(`The plugin crate at ${plugin.dir} has no templates/ios/${name}.`);
|
|
93
|
+
const path = join(apple, WIDGET, name);
|
|
94
|
+
const current = readText(path);
|
|
95
|
+
if (current === undefined) return step('created', show(path), '', writeFile(path, wanted));
|
|
96
|
+
// XcodeGen writes the extension's Info.plist from the spec, so it differs from the template.
|
|
97
|
+
if (current === wanted || name === 'Info.plist') return step('unchanged', show(path));
|
|
98
|
+
return step('kept', show(path), "differs from the plugin's template; to take the template, delete it and run setup again");
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function specStep({ plugin, config, srcTauri, show }, apple, project, { fonts, appGroup }) {
|
|
103
|
+
const path = join(apple, SPEC_FILE);
|
|
104
|
+
const wanted = widgetSpec({
|
|
105
|
+
fonts,
|
|
106
|
+
appGroup,
|
|
107
|
+
// XcodeGen writes the entitlements file from the spec, so the App Group goes into the spec, at the app's path.
|
|
108
|
+
appEntitlements: project.entitlements ?? `${project.appTarget}/${project.appTarget}.entitlements`,
|
|
109
|
+
pluginVersion: plugin.version,
|
|
110
|
+
packagePath: join(plugin.dir, 'ios'),
|
|
111
|
+
appTarget: project.appTarget,
|
|
112
|
+
bundleId: `${project.bundleId ?? config.identifier}.widget`,
|
|
113
|
+
...appVersions(config, srcTauri),
|
|
114
|
+
teamGroup: project.settingGroups.includes('app'),
|
|
115
|
+
});
|
|
116
|
+
const current = readText(path);
|
|
117
|
+
if (current === undefined) {
|
|
118
|
+
return step('created', show(path), 'the widget extension, and the button intent and custom views in both targets', writeFile(path, wanted));
|
|
119
|
+
}
|
|
120
|
+
if (current === wanted) return step('unchanged', show(path));
|
|
121
|
+
if (!writtenBySetup(current)) {
|
|
122
|
+
return step('kept', show(path), 'it was changed by hand; delete it and run setup again to have it written anew');
|
|
123
|
+
}
|
|
124
|
+
return step('updated', show(path), 'for the current plugin and app version', writeFile(path, wanted));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The `version` of Cargo.toml's [package] section. */
|
|
128
|
+
function cargoVersion(text = '') {
|
|
129
|
+
let inPackage = false;
|
|
130
|
+
for (const line of text.split('\n')) {
|
|
131
|
+
if (/^\s*\[/.test(line)) inPackage = /^\s*\[package\]\s*$/.test(line);
|
|
132
|
+
else if (inPackage && /^\s*version\s*=/.test(line)) return /"([^"]+)"/.exec(line)?.[1];
|
|
133
|
+
}
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The app's version where Tauri reads it, so that the extension's version matches the app's. */
|
|
138
|
+
function appVersions(config, srcTauri) {
|
|
139
|
+
const fromFile = typeof config.version === 'string' && config.version.endsWith('.json');
|
|
140
|
+
const version = fromFile ? parseJson(readText(resolve(srcTauri, config.version)) ?? '')?.version
|
|
141
|
+
: config.version ?? cargoVersion(readText(join(srcTauri, 'Cargo.toml')));
|
|
142
|
+
const short = /^\d+(\.\d+){0,2}/.exec(String(version ?? ''))?.[0];
|
|
143
|
+
return short ? { appVersion: short, buildVersion: String(config.bundle?.iOS?.bundleVersion ?? short) } : {};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function includeStep({ show }, specPath, yaml) {
|
|
147
|
+
const result = addInclude(yaml, SPEC_FILE);
|
|
148
|
+
if (result.status === 'present') return step('unchanged', show(specPath));
|
|
149
|
+
if (result.status === 'added') return step('updated', show(specPath), `includes ${SPEC_FILE}`, writeFile(specPath, result.text));
|
|
150
|
+
return step('todo', show(specPath), `add ${SPEC_FILE} to its include list`);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The plugin's Swift package refers to Tauri's at ../.tauri/tauri-api, which the plugin's iOS build copies there. */
|
|
154
|
+
function swiftPackageStep({ plugin, show }) {
|
|
155
|
+
const target = join(plugin.dir, '.tauri', 'tauri-api');
|
|
156
|
+
if (existsSync(join(target, 'Package.swift'))) return step('unchanged', show(target));
|
|
157
|
+
const source = plugin.tauriDir && join(plugin.tauriDir, 'mobile', 'ios-api');
|
|
158
|
+
if (!source || !existsSync(join(source, 'Package.swift'))) {
|
|
159
|
+
const detail = "the plugin's Swift package needs Tauri's Swift API here. Build the Rust code for iOS once to make it: "
|
|
160
|
+
+ 'cargo build --target aarch64-apple-ios-sim (x86_64-apple-ios on an Intel Mac) in src-tauri';
|
|
161
|
+
return step('todo', show(target), detail);
|
|
162
|
+
}
|
|
163
|
+
const copied = path => !NOT_COPIED.some(name => relative(source, path) === name || relative(source, path).startsWith(name + sep));
|
|
164
|
+
const detail = "Tauri's Swift API for the plugin's Swift package, as the plugin's iOS build copies it";
|
|
165
|
+
return step('created', show(target), detail, () => cpSync(source, target, { recursive: true, filter: copied }));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function generatedWithWidget(apple) {
|
|
169
|
+
return readdirSync(apple).filter(name => name.endsWith('.xcodeproj'))
|
|
170
|
+
.some(name => readText(join(apple, name, 'project.pbxproj'))?.includes(WIDGET));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function xcodegenStep({ env, show }, apple, specPath, projectSteps, include) {
|
|
174
|
+
const command = `xcodegen generate --spec ${show(specPath)}`;
|
|
175
|
+
if (include.status === 'todo') return step('skipped', 'Xcode project', 'waits for the include in project.yml');
|
|
176
|
+
const changed = projectSteps.some(item => item.status === 'created' || item.status === 'updated');
|
|
177
|
+
if (!changed && generatedWithWidget(apple)) return step('unchanged', 'Xcode project');
|
|
178
|
+
const xcodegen = which('xcodegen', env);
|
|
179
|
+
if (!xcodegen) return step('todo', 'Xcode project', `XcodeGen is not on PATH. Install it (brew install xcodegen), then run: ${command}`);
|
|
180
|
+
return step('ran', command, '', () => {
|
|
181
|
+
const result = spawnSync(xcodegen, ['generate', '--spec', specPath], { cwd: apple, env, encoding: 'utf8' });
|
|
182
|
+
if (result.status === 0) return undefined;
|
|
183
|
+
const output = tail(result.stderr || result.stdout || result.error?.message);
|
|
184
|
+
return step('todo', 'Xcode project', `xcodegen failed: ${output}. Fix it, then run: ${command}`);
|
|
185
|
+
});
|
|
186
|
+
}
|
package/cli/main.mjs
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// The command line of `npx tauri-plugin-live-activity`.
|
|
2
|
+
import { formatReport } from './report.mjs';
|
|
3
|
+
import { SetupError, setup } from './setup.mjs';
|
|
4
|
+
|
|
5
|
+
const USAGE = `Usage: npx tauri-plugin-live-activity setup [--dry-run] [--ios-only] [--font <file>]... [--asset <file>]... [--app-group[=<id>]]
|
|
6
|
+
|
|
7
|
+
Run it in the folder of a Tauri 2 app after \`cargo add\` and \`npm i\`. It grants the plugin's
|
|
8
|
+
permissions, sets the Android minimum to API 26 and, on a Mac, adds the Live Activity widget
|
|
9
|
+
extension to src-tauri/gen/apple. Run it after \`tauri ios init\`, and again if that folder is
|
|
10
|
+
ever made from scratch.
|
|
11
|
+
|
|
12
|
+
--dry-run show what would change, and write nothing
|
|
13
|
+
--ios-only do only the iOS part: leave the capabilities and tauri.conf.json alone
|
|
14
|
+
--font <file> bundle a .ttf, .otf or .ttc font in the widget extension, for a style's fontFamily
|
|
15
|
+
--asset <file> put a .png, .jpg, .pdf or .svg image in the widget's asset catalog, for image('<name>');
|
|
16
|
+
name@2x.png and name@3x.png are scales of the asset name
|
|
17
|
+
--app-group[=<id>] give the app and the widget extension an App Group, group.<app identifier> unless
|
|
18
|
+
named, so writeImage can share images; later runs keep it
|
|
19
|
+
`;
|
|
20
|
+
|
|
21
|
+
const FLAGS = { '--dry-run': 'dryRun', '--ios-only': 'iosOnly' };
|
|
22
|
+
const FILES = { '--font': 'fonts', '--asset': 'assets' };
|
|
23
|
+
const HELP = new Set(['help', '--help', '-h']);
|
|
24
|
+
|
|
25
|
+
/** The options of `setup`, or the argument it does not take and why. */
|
|
26
|
+
function parseOptions(args) {
|
|
27
|
+
const options = { fonts: [], assets: [] };
|
|
28
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
29
|
+
const [name, inline] = args[index].split(/=(.*)/s);
|
|
30
|
+
if (Object.hasOwn(FLAGS, args[index])) options[FLAGS[args[index]]] = true;
|
|
31
|
+
else if (name === '--app-group') options.appGroup = inline ?? true;
|
|
32
|
+
else if (Object.hasOwn(FILES, name)) {
|
|
33
|
+
const file = inline ?? args[(index += 1)];
|
|
34
|
+
if (!file) return { error: `${name} needs a file.` };
|
|
35
|
+
options[FILES[name]].push(file);
|
|
36
|
+
} else return { error: `Unknown option ${args[index]}.` };
|
|
37
|
+
}
|
|
38
|
+
return { options };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Runs the command and returns its exit status: 0 done, 1 something left to do or an error, 2 usage. */
|
|
42
|
+
export function main(argv, {
|
|
43
|
+
cwd = process.cwd(), env = process.env, platform = process.platform,
|
|
44
|
+
out = text => process.stdout.write(text), err = text => process.stderr.write(text),
|
|
45
|
+
} = {}) {
|
|
46
|
+
const [command, ...rest] = argv;
|
|
47
|
+
if (command === undefined || HELP.has(command) || (command === 'setup' && rest.some(arg => HELP.has(arg)))) {
|
|
48
|
+
out(USAGE);
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
if (command !== 'setup') {
|
|
52
|
+
err(`Unknown command ${command}.\n\n${USAGE}`);
|
|
53
|
+
return 2;
|
|
54
|
+
}
|
|
55
|
+
const { options, error } = parseOptions(rest);
|
|
56
|
+
if (error) {
|
|
57
|
+
err(`${error}\n\n${USAGE}`);
|
|
58
|
+
return 2;
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
const result = setup({ cwd, env, platform, ...options });
|
|
62
|
+
out(formatReport(result));
|
|
63
|
+
return result.steps.some(item => item.status === 'todo') ? 1 : 0;
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (!(error instanceof SetupError)) throw error;
|
|
66
|
+
err(`${error.message}\n`);
|
|
67
|
+
return 1;
|
|
68
|
+
}
|
|
69
|
+
}
|
package/cli/plist.mjs
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// Just enough of XML property lists to set one Boolean key of the root dictionary.
|
|
2
|
+
|
|
3
|
+
const TAG = /<(\/?)([A-Za-z]+)[^>]*?(\/?)>/g;
|
|
4
|
+
|
|
5
|
+
/** A new plist whose root dictionary holds `key` = true. */
|
|
6
|
+
export function newPlist(key) {
|
|
7
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
8
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
9
|
+
<plist version="1.0">
|
|
10
|
+
<dict>
|
|
11
|
+
\t<key>${key}</key>
|
|
12
|
+
\t<true/>
|
|
13
|
+
</dict>
|
|
14
|
+
</plist>
|
|
15
|
+
`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Comments become spaces of the same length, so that positions still match the original text. */
|
|
19
|
+
function blankComments(text) {
|
|
20
|
+
return text.replace(/<!--[\s\S]*?-->/g, comment => ' '.repeat(comment.length));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Where the root dictionary opens and closes, and the value tag of each key at its top level. */
|
|
24
|
+
function scanRoot(scan) {
|
|
25
|
+
const plist = scan.indexOf('<plist');
|
|
26
|
+
if (plist === -1) return undefined;
|
|
27
|
+
const tags = [...scan.slice(plist).matchAll(TAG)].map(match => ({
|
|
28
|
+
index: plist + match.index, end: plist + match.index + match[0].length,
|
|
29
|
+
closing: match[1] === '/', name: match[2], empty: match[3] === '/',
|
|
30
|
+
}));
|
|
31
|
+
const root = tags.find(tag => tag.name !== 'plist');
|
|
32
|
+
if (root?.name !== 'dict' || root.closing) return undefined;
|
|
33
|
+
if (root.empty) return { root, close: undefined, keys: new Map() };
|
|
34
|
+
return { root, ...rootEntries(scan, tags.slice(tags.indexOf(root) + 1)) };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function rootEntries(scan, tags) {
|
|
38
|
+
const keys = new Map();
|
|
39
|
+
let depth = 0;
|
|
40
|
+
let pendingKey;
|
|
41
|
+
for (const tag of tags) {
|
|
42
|
+
if (depth === 0 && tag.closing && tag.name === 'dict') return { close: tag, keys };
|
|
43
|
+
if (depth === 0 && !tag.closing && tag.name === 'key') {
|
|
44
|
+
pendingKey = scan.slice(tag.end, scan.indexOf('</key>', tag.end)).trim();
|
|
45
|
+
} else if (depth === 0 && !tag.closing && pendingKey !== undefined) {
|
|
46
|
+
keys.set(pendingKey, tag);
|
|
47
|
+
pendingKey = undefined;
|
|
48
|
+
}
|
|
49
|
+
if ((tag.name === 'dict' || tag.name === 'array') && !tag.empty) depth += tag.closing ? -1 : 1;
|
|
50
|
+
}
|
|
51
|
+
return { close: undefined, keys };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Inserts the entry before the root's `</dict>`: on its own line when that tag starts a line, indented
|
|
56
|
+
* like the first key of the root (`afterRoot` is the text after the root's opening tag).
|
|
57
|
+
*/
|
|
58
|
+
function insertEntry(text, afterRoot, close, key) {
|
|
59
|
+
const lineStart = text.lastIndexOf('\n', close.index - 1) + 1;
|
|
60
|
+
if (!/^[ \t]*$/.test(text.slice(lineStart, close.index))) {
|
|
61
|
+
return `${text.slice(0, close.index)}<key>${key}</key><true/>${text.slice(close.index)}`;
|
|
62
|
+
}
|
|
63
|
+
const indent = afterRoot.match(/\n([ \t]*)<key>/)?.[1] || '\t';
|
|
64
|
+
return `${text.slice(0, lineStart)}${indent}<key>${key}</key>\n${indent}<true/>\n${text.slice(lineStart)}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Makes `key` true in the root dictionary of an XML plist. Status: `present` (already true), `added`
|
|
69
|
+
* (with the new `text`), `false` or `other` (the key has another value, left as it is) or `unreadable`.
|
|
70
|
+
*/
|
|
71
|
+
export function setTrueKey(text, key) {
|
|
72
|
+
const scan = blankComments(text);
|
|
73
|
+
const root = scanRoot(scan);
|
|
74
|
+
if (!root) return { status: 'unreadable' };
|
|
75
|
+
const value = root.keys.get(key);
|
|
76
|
+
if (value) return { status: value.name === 'true' ? 'present' : value.name === 'false' ? 'false' : 'other' };
|
|
77
|
+
if (root.root.empty) {
|
|
78
|
+
const opened = `<dict>\n\t<key>${key}</key>\n\t<true/>\n</dict>`;
|
|
79
|
+
return { status: 'added', text: text.slice(0, root.root.index) + opened + text.slice(root.root.end) };
|
|
80
|
+
}
|
|
81
|
+
if (!root.close) return { status: 'unreadable' };
|
|
82
|
+
return { status: 'added', text: insertEntry(text, scan.slice(root.root.end), root.close, key) };
|
|
83
|
+
}
|
package/cli/report.mjs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// The summary that setup prints.
|
|
2
|
+
|
|
3
|
+
const DONE = { created: 'created', updated: 'updated', ran: 'ran', kept: 'kept', skipped: 'skipped' };
|
|
4
|
+
const WOULD = { created: 'would create', updated: 'would update', ran: 'would run', kept: 'would keep', skipped: 'would skip' };
|
|
5
|
+
|
|
6
|
+
function line(item, dryRun) {
|
|
7
|
+
const label = (dryRun ? WOULD : DONE)[item.status];
|
|
8
|
+
return ` ${label.padEnd(dryRun ? 12 : 8)} ${item.path}${item.detail ? ` (${item.detail})` : ''}`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function formatReport({ dryRun, version, steps, notes }) {
|
|
12
|
+
const shown = steps.filter(item => Object.hasOwn(DONE, item.status));
|
|
13
|
+
const todo = steps.filter(item => item.status === 'todo');
|
|
14
|
+
const unchanged = steps.length - shown.length - todo.length;
|
|
15
|
+
const lines = [`tauri-plugin-live-activity ${version} setup`, ''];
|
|
16
|
+
if (dryRun) lines.push('Dry run: nothing was written.', '');
|
|
17
|
+
if (shown.length === 0 && todo.length === 0) lines.push('Everything was set up already.');
|
|
18
|
+
lines.push(...shown.map(item => line(item, dryRun)));
|
|
19
|
+
if (shown.length > 0 && unchanged > 0) lines.push(` ${unchanged} other ${unchanged === 1 ? 'step' : 'steps'} needed no change.`);
|
|
20
|
+
if (todo.length > 0) lines.push('', 'To do:', ...todo.map(item => ` ${item.path}: ${item.detail}`));
|
|
21
|
+
if (steps.some(item => item.status === 'updated' && item.path.endsWith('project.yml'))) {
|
|
22
|
+
lines.push('', 'If src-tauri/gen/apple is ever made from scratch, run setup again: the new project.yml lacks the include.');
|
|
23
|
+
}
|
|
24
|
+
for (const note of notes) lines.push('', note.kind === 'register' ? `Next: ${note.text}` : note.text);
|
|
25
|
+
return `${lines.join('\n')}\n`;
|
|
26
|
+
}
|
package/cli/setup.mjs
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// `npx tauri-plugin-live-activity setup`: what the README's install steps need, done in an app's folder.
|
|
2
|
+
// Every step first works out what to change; a dry run stops there.
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { iosSteps } from './ios.mjs';
|
|
7
|
+
import { SetupError, display, jsonLike, parseJson, readText, step, tail, writeFile } from './steps.mjs';
|
|
8
|
+
import { widgetFiles } from './widget-files.mjs';
|
|
9
|
+
|
|
10
|
+
export { SetupError } from './steps.mjs';
|
|
11
|
+
|
|
12
|
+
export const CRATE = 'tauri-plugin-live-activity';
|
|
13
|
+
/** `default` reads; the others allow the commands that change activities. */
|
|
14
|
+
export const PERMISSIONS = [
|
|
15
|
+
'live-activity:default',
|
|
16
|
+
...['request-permissions', 'start', 'update', 'end', 'start-layout', 'update-layout', 'end-layout', 'write-image']
|
|
17
|
+
.map(command => `live-activity:allow-${command}`),
|
|
18
|
+
];
|
|
19
|
+
// The plugin's Android library needs API 26: Tauri's Jackson runtime fails below it.
|
|
20
|
+
const MIN_SDK = 26;
|
|
21
|
+
const NPM_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Sets up the app in `cwd` (its folder or its src-tauri folder) and returns the steps with their
|
|
25
|
+
* status, and notes for the person who runs it. `fonts` and `assets` are files for the widget
|
|
26
|
+
* extension; `appGroup` is true or the name of an App Group. Throws SetupError when it cannot start.
|
|
27
|
+
*/
|
|
28
|
+
export function setup({
|
|
29
|
+
cwd = process.cwd(), env = process.env, dryRun = false, iosOnly = false, platform = process.platform,
|
|
30
|
+
fonts = [], assets = [], appGroup = undefined,
|
|
31
|
+
} = {}) {
|
|
32
|
+
const files = widgetFiles(cwd, { fonts, assets });
|
|
33
|
+
const app = findApp(cwd);
|
|
34
|
+
const plugin = findPlugin(app, env);
|
|
35
|
+
const context = { ...app, plugin, env, platform, files, appGroup, show: path => display(cwd, path) };
|
|
36
|
+
const planned = [...(iosOnly ? [] : [capabilitiesStep(context), ...androidSteps(context)]), ...iosSteps(context)];
|
|
37
|
+
const steps = dryRun ? planned : planned.map(apply);
|
|
38
|
+
return { dryRun, version: plugin.version, steps: steps.map(({ effect, ...rest }) => rest), notes: notes(context) };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function apply(planned) {
|
|
42
|
+
if (!planned.effect) return planned;
|
|
43
|
+
try {
|
|
44
|
+
return planned.effect() ?? planned;
|
|
45
|
+
} catch (error) {
|
|
46
|
+
return step('todo', planned.path, `could not write it: ${error.message}`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function findApp(cwd) {
|
|
51
|
+
const srcTauri = [join(cwd, 'src-tauri'), cwd].find(folder => existsSync(join(folder, 'tauri.conf.json')));
|
|
52
|
+
if (!srcTauri) {
|
|
53
|
+
const other = [join(cwd, 'src-tauri'), cwd].flatMap(folder => ['tauri.conf.json5', 'Tauri.toml'].map(name => join(folder, name)))
|
|
54
|
+
.find(existsSync);
|
|
55
|
+
if (other) throw new SetupError(`Setup reads tauri.conf.json, and this app has ${display(cwd, other)}. docs/usage.md has the steps by hand.`);
|
|
56
|
+
throw new SetupError('No src-tauri/tauri.conf.json here. Run this in the folder of a Tauri 2 app.');
|
|
57
|
+
}
|
|
58
|
+
const configPath = join(srcTauri, 'tauri.conf.json');
|
|
59
|
+
const configText = readFileSync(configPath, 'utf8');
|
|
60
|
+
const config = parseJson(configText);
|
|
61
|
+
if (typeof config !== 'object' || config === null) throw new SetupError(`${display(cwd, configPath)} is not valid JSON.`);
|
|
62
|
+
if (!existsSync(join(srcTauri, 'Cargo.toml'))) throw new SetupError('No src-tauri/Cargo.toml next to tauri.conf.json.');
|
|
63
|
+
return { srcTauri, configPath, configText, config };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The plugin crate's folder from `cargo metadata`, and the folder of the `tauri` crate it uses. */
|
|
67
|
+
function findPlugin({ srcTauri }, env) {
|
|
68
|
+
const args = ['metadata', '--format-version', '1', '--manifest-path', join(srcTauri, 'Cargo.toml')];
|
|
69
|
+
const result = spawnSync(env.CARGO || 'cargo', args, { env, encoding: 'utf8', maxBuffer: 1024 ** 3 });
|
|
70
|
+
if (result.error?.code === 'ENOENT') throw new SetupError('cargo was not found. Install Rust from https://rustup.rs, then run this again.');
|
|
71
|
+
if (result.error) throw new SetupError(`cargo metadata could not run: ${result.error.message}`);
|
|
72
|
+
if (result.status !== 0) throw new SetupError(`cargo metadata failed: ${tail(result.stderr)}`);
|
|
73
|
+
const metadata = parseJson(result.stdout);
|
|
74
|
+
if (!Array.isArray(metadata?.packages)) throw new SetupError('cargo metadata printed something that is not its JSON.');
|
|
75
|
+
const crate = metadata.packages.find(item => item.name === CRATE);
|
|
76
|
+
if (!crate) {
|
|
77
|
+
throw new SetupError(`${CRATE} is not a dependency of src-tauri/Cargo.toml yet. Add it first:\n cargo add ${CRATE} --manifest-path src-tauri/Cargo.toml`);
|
|
78
|
+
}
|
|
79
|
+
const tauriId = metadata.resolve?.nodes?.find(node => node.id === crate.id)?.deps?.find(dep => dep.name === 'tauri')?.pkg;
|
|
80
|
+
const tauri = metadata.packages.find(item => (tauriId ? item.id === tauriId : item.name === 'tauri'));
|
|
81
|
+
return { version: crate.version, dir: dirname(crate.manifest_path), tauriDir: tauri && dirname(tauri.manifest_path) };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Adds the plugin's permissions to the app's capability: default.json, or the only capability file. */
|
|
85
|
+
function capabilitiesStep({ srcTauri, show }) {
|
|
86
|
+
const folder = join(srcTauri, 'capabilities');
|
|
87
|
+
const files = existsSync(folder) ? readdirSync(folder).filter(name => name.endsWith('.json')) : [];
|
|
88
|
+
const name = files.includes('default.json') ? 'default.json' : files.length === 1 ? files[0] : undefined;
|
|
89
|
+
const list = PERMISSIONS.join(', ');
|
|
90
|
+
if (!name) return step('todo', show(folder), `add these permissions to the capability of your window: ${list}`);
|
|
91
|
+
const path = join(folder, name);
|
|
92
|
+
const text = readFileSync(path, 'utf8');
|
|
93
|
+
const capability = parseJson(text);
|
|
94
|
+
const valid = typeof capability === 'object' && capability !== null && Array.isArray(capability.permissions ?? []);
|
|
95
|
+
if (!valid) return step('todo', show(path), `not valid JSON with a permissions list; add these permissions to it: ${list}`);
|
|
96
|
+
const present = new Set((capability.permissions ?? []).map(item => (typeof item === 'string' ? item : item?.identifier)));
|
|
97
|
+
const missing = PERMISSIONS.filter(permission => !present.has(permission));
|
|
98
|
+
if (missing.length === 0) return step('unchanged', show(path));
|
|
99
|
+
const next = { ...capability, permissions: [...(capability.permissions ?? []), ...missing] };
|
|
100
|
+
return step('updated', show(path), `${missing.length} permissions added`, writeFile(path, jsonLike(text, next)));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Tauri writes minSdk into gen/android when it creates it, from bundle.android.minSdkVersion (24 by default). */
|
|
104
|
+
function androidSteps(context) {
|
|
105
|
+
const gradle = gradleStep(context);
|
|
106
|
+
return [minSdkConfigStep(context), ...(gradle ? [gradle] : [])];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function minSdkConfigStep({ configPath, configText, config, show }) {
|
|
110
|
+
const current = config.bundle?.android?.minSdkVersion;
|
|
111
|
+
if (Number.isInteger(current) && current >= MIN_SDK) return step('unchanged', show(configPath));
|
|
112
|
+
const android = { ...config.bundle?.android, minSdkVersion: MIN_SDK };
|
|
113
|
+
const text = jsonLike(configText, { ...config, bundle: { ...config.bundle, android } });
|
|
114
|
+
return step('updated', show(configPath), `bundle.android.minSdkVersion = ${MIN_SDK}, as the plugin needs Android 8`, writeFile(configPath, text));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function gradleStep({ srcTauri, show }) {
|
|
118
|
+
const path = join(srcTauri, 'gen', 'android', 'app', 'build.gradle.kts');
|
|
119
|
+
const gradle = readText(path);
|
|
120
|
+
if (gradle === undefined) return undefined;
|
|
121
|
+
const match = /^([ \t]*minSdk[ \t]*=[ \t]*)(\d+)[ \t]*$/m.exec(gradle);
|
|
122
|
+
if (!match) return step('todo', show(path), `set minSdk to ${MIN_SDK}`);
|
|
123
|
+
if (Number(match[2]) >= MIN_SDK) return step('unchanged', show(path));
|
|
124
|
+
const at = match.index + match[1].length;
|
|
125
|
+
return step('updated', show(path), `minSdk = ${MIN_SDK}`, writeFile(path, `${gradle.slice(0, at)}${MIN_SDK}${gradle.slice(at + match[2].length)}`));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const minor = version => /^\d+\.\d+/.exec(version)?.[0];
|
|
129
|
+
|
|
130
|
+
function notes({ srcTauri, plugin }) {
|
|
131
|
+
const sources = join(srcTauri, 'src');
|
|
132
|
+
const registered = existsSync(sources) && readdirSync(sources, { recursive: true })
|
|
133
|
+
.filter(name => String(name).endsWith('.rs'))
|
|
134
|
+
.some(name => readFileSync(join(sources, String(name)), 'utf8').includes('tauri_plugin_live_activity::init'));
|
|
135
|
+
return [
|
|
136
|
+
...(registered ? [] : [{ kind: 'register', text: 'add .plugin(tauri_plugin_live_activity::init()) to tauri::Builder in src-tauri/src/lib.rs.' }]),
|
|
137
|
+
...(minor(plugin.version) === minor(NPM_VERSION) ? [] : [{
|
|
138
|
+
kind: 'version',
|
|
139
|
+
text: `The npm package ${NPM_VERSION} and the crate ${plugin.version} differ: use the same minor version of both.`,
|
|
140
|
+
}]),
|
|
141
|
+
];
|
|
142
|
+
}
|
package/cli/steps.mjs
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Shared helpers of the setup steps. A step is `{ status, path, detail }` plus an optional `effect`
|
|
2
|
+
// that writes it; a dry run reports the steps without running their effects.
|
|
3
|
+
import { accessSync, constants, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { delimiter, dirname, isAbsolute, join, relative, sep } from 'node:path';
|
|
6
|
+
|
|
7
|
+
/** A problem that stops setup, with a message for the person who ran it. */
|
|
8
|
+
export class SetupError extends Error {
|
|
9
|
+
name = 'SetupError';
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Status: created, updated, ran, kept, skipped, todo or unchanged. */
|
|
13
|
+
export function step(status, path, detail = '', effect = undefined) {
|
|
14
|
+
return effect ? { status, path, detail, effect } : { status, path, detail };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function readText(path) {
|
|
18
|
+
try {
|
|
19
|
+
return readFileSync(path, 'utf8');
|
|
20
|
+
} catch (error) {
|
|
21
|
+
// ENOTDIR: a file stands where a folder of the path should be, so the file is not there either.
|
|
22
|
+
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return undefined;
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function parseJson(text) {
|
|
28
|
+
try {
|
|
29
|
+
return JSON.parse(text);
|
|
30
|
+
} catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** An effect that writes `text` to `path`, creating its folder. */
|
|
36
|
+
export function writeFile(path, text) {
|
|
37
|
+
return () => {
|
|
38
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
39
|
+
writeFileSync(path, text);
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** JSON in the indent of the original text, with a final newline when it had one. */
|
|
44
|
+
export function jsonLike(original, value) {
|
|
45
|
+
const indent = /\n([ \t]+)"/.exec(original)?.[1] ?? ' ';
|
|
46
|
+
return JSON.stringify(value, null, indent) + (original.endsWith('\n') ? '\n' : '');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The last lines of a tool's output, on one line. */
|
|
50
|
+
export function tail(text = '') {
|
|
51
|
+
return text.split('\n').map(line => line.trim()).filter(Boolean).slice(-5).join(' ');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A path for messages: relative inside the folder setup runs in, otherwise absolute with `~` for home. */
|
|
55
|
+
export function display(cwd, path) {
|
|
56
|
+
const inside = relative(cwd, path);
|
|
57
|
+
if (inside === '') return '.';
|
|
58
|
+
if (!inside.startsWith('..') && !isAbsolute(inside)) return inside.split(sep).join('/');
|
|
59
|
+
const home = homedir();
|
|
60
|
+
return path.startsWith(home + sep) ? `~/${relative(home, path).split(sep).join('/')}` : path;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The executable `name` on the PATH of `env`, or undefined. */
|
|
64
|
+
export function which(name, env) {
|
|
65
|
+
const extensions = process.platform === 'win32' ? (env.PATHEXT ?? '.EXE;.CMD').split(';') : [''];
|
|
66
|
+
for (const folder of (env.PATH ?? '').split(delimiter).filter(Boolean)) {
|
|
67
|
+
for (const extension of extensions) {
|
|
68
|
+
const candidate = join(folder, name + extension);
|
|
69
|
+
if (isExecutable(candidate)) return candidate;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function isExecutable(path) {
|
|
76
|
+
try {
|
|
77
|
+
accessSync(path, constants.X_OK);
|
|
78
|
+
return statSync(path).isFile();
|
|
79
|
+
} catch {
|
|
80
|
+
return false; // Missing or not executable: keep looking along PATH.
|
|
81
|
+
}
|
|
82
|
+
}
|