tauri-plugin-live-activity 0.10.1 → 0.10.3

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/cli/steps.mjs CHANGED
@@ -3,80 +3,96 @@
3
3
  import { accessSync, constants, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
5
  import { delimiter, dirname, isAbsolute, join, relative, sep } from 'node:path';
6
-
7
6
  /** A problem that stops setup, with a message for the person who ran it. */
8
7
  export class SetupError extends Error {
9
- name = 'SetupError';
8
+ name = 'SetupError';
10
9
  }
11
-
12
10
  /** Status: created, updated, removed, 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 };
11
+ export function step(status, path, detail = '', effect) {
12
+ return effect ? { status, path, detail, effect } : { status, path, detail };
15
13
  }
16
-
14
+ /** The `code` of an error, as the errors of Node's file system and of a process that could not start carry one. */
15
+ export function errorCode(error) {
16
+ return typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string' ? error.code : undefined;
17
+ }
18
+ /** The text of the file at `path`, or undefined when there is no such file. */
17
19
  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
- }
20
+ try {
21
+ return readFileSync(path, 'utf8');
22
+ }
23
+ catch (error) {
24
+ // ENOTDIR: a file stands where a folder of the path should be, so the file is not there either.
25
+ const code = errorCode(error);
26
+ if (code === 'ENOENT' || code === 'ENOTDIR')
27
+ return undefined;
28
+ throw error;
29
+ }
25
30
  }
26
-
31
+ /** What `text` holds as JSON, or undefined when it is not JSON. The value is checked where it is read. */
27
32
  export function parseJson(text) {
28
- try {
29
- return JSON.parse(text);
30
- } catch {
31
- return undefined;
32
- }
33
+ try {
34
+ return JSON.parse(text);
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ /** True for a JSON object: a value with members by name. A list is none. */
41
+ export function isRecord(value) {
42
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
43
+ }
44
+ /** True for a JSON array. */
45
+ export function isList(value) {
46
+ return Array.isArray(value);
47
+ }
48
+ /** The member at `keys` of parsed JSON: undefined where a value on the way is no object, or has no such member. */
49
+ export function member(value, ...keys) {
50
+ return keys.reduce((current, key) => (isRecord(current) ? current[key] : undefined), value);
33
51
  }
34
-
35
52
  /** An effect that writes `text` to `path`, creating its folder. */
36
53
  export function writeFile(path, text) {
37
- return () => {
38
- mkdirSync(dirname(path), { recursive: true });
39
- writeFileSync(path, text);
40
- };
54
+ return () => {
55
+ mkdirSync(dirname(path), { recursive: true });
56
+ writeFileSync(path, text);
57
+ };
41
58
  }
42
-
43
59
  /** JSON in the indent of the original text, with a final newline when it had one. */
44
60
  export function jsonLike(original, value) {
45
- const indent = /\n([ \t]+)"/.exec(original)?.[1] ?? ' ';
46
- return JSON.stringify(value, null, indent) + (original.endsWith('\n') ? '\n' : '');
61
+ const indent = /\n([ \t]+)"/.exec(original)?.[1] ?? ' ';
62
+ return JSON.stringify(value, null, indent) + (original.endsWith('\n') ? '\n' : '');
47
63
  }
48
-
49
64
  /** The last lines of a tool's output, on one line. */
50
65
  export function tail(text = '') {
51
- return text.split('\n').map(line => line.trim()).filter(Boolean).slice(-5).join(' ');
66
+ return text.split('\n').map(line => line.trim()).filter(Boolean).slice(-5).join(' ');
52
67
  }
53
-
54
68
  /** A path for messages: relative inside the folder setup runs in, otherwise absolute with `~` for home. */
55
69
  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;
70
+ const inside = relative(cwd, path);
71
+ if (inside === '')
72
+ return '.';
73
+ if (!inside.startsWith('..') && !isAbsolute(inside))
74
+ return inside.split(sep).join('/');
75
+ const home = homedir();
76
+ return path.startsWith(home + sep) ? `~/${relative(home, path).split(sep).join('/')}` : path;
61
77
  }
62
-
63
78
  /** The executable `name` on the PATH of `env`, or undefined. */
64
79
  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;
80
+ const extensions = process.platform === 'win32' ? (env.PATHEXT ?? '.EXE;.CMD').split(';') : [''];
81
+ for (const folder of (env.PATH ?? '').split(delimiter).filter(Boolean)) {
82
+ for (const extension of extensions) {
83
+ const candidate = join(folder, name + extension);
84
+ if (isExecutable(candidate))
85
+ return candidate;
86
+ }
70
87
  }
71
- }
72
- return undefined;
88
+ return undefined;
73
89
  }
74
-
75
90
  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
- }
91
+ try {
92
+ accessSync(path, constants.X_OK);
93
+ return statSync(path).isFile();
94
+ }
95
+ catch {
96
+ return false; // Missing or not executable: keep looking along PATH.
97
+ }
82
98
  }
@@ -3,8 +3,7 @@
3
3
  // extension's asset catalog, LiveActivityWidget/Assets.xcassets.
4
4
  import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from 'node:fs';
5
5
  import { basename, dirname, extname, join, resolve } from 'node:path';
6
- import { SetupError, parseJson, readText, step, writeFile } from './steps.mjs';
7
-
6
+ import { SetupError, isList, isRecord, member, parseJson, readText, step, writeFile } from './steps.mjs';
8
7
  export const FONTS = 'Fonts';
9
8
  export const CATALOG = 'Assets.xcassets';
10
9
  const FONT_TYPES = new Set(['.ttf', '.otf', '.ttc']);
@@ -14,135 +13,148 @@ const VECTOR_TYPES = new Set(['.pdf', '.svg']);
14
13
  const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
15
14
  const FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9 ._@-]{0,127}$/;
16
15
  const CATALOG_INFO = { info: { author: 'xcode', version: 1 } };
17
-
16
+ const SCALES = ['2x', '3x'];
18
17
  /**
19
18
  * The fonts and images named on the command line, checked before anything is written: each exists, is a
20
19
  * file of a kind the widget can use and has a name the bundle and a layout can carry.
21
20
  */
22
21
  export function widgetFiles(cwd, { fonts = [], assets = [] }) {
23
- const file = (given, kinds, what) => {
24
- const source = resolve(cwd, given);
25
- if (!existsSync(source) || !statSync(source).isFile()) throw new SetupError(`${given}: no such file.`);
26
- const kind = extname(source).toLowerCase();
27
- if (!kinds.has(kind)) throw new SetupError(`${given}: ${what} must be ${[...kinds].join(', ')}.`);
28
- if (!FILE_NAME.test(basename(source))) {
29
- throw new SetupError(`${given}: rename it to ASCII letters, digits, spaces, '.', '_', '@' and '-' first.`);
30
- }
31
- return { source, file: basename(source), kind };
32
- };
33
- const once = list => {
34
- const repeated = list.find((item, index) => list.findIndex(other => other.file === item.file) !== index);
35
- if (repeated) throw new SetupError(`${repeated.file} is named twice; the widget keeps one file of each name.`);
36
- return list;
37
- };
38
- return {
39
- fonts: once(fonts.map(given => file(given, FONT_TYPES, 'a font'))),
40
- assets: once(assets.map(given => {
41
- const image = file(given, IMAGE_TYPES, 'an image');
42
- const [, name, scale] = /^(.*?)(?:@([23])x)?$/.exec(basename(image.file, extname(image.file)));
43
- if (!NAME.test(name)) throw new SetupError(`${given}: the asset name ${JSON.stringify(name)} must be 1 to 64 ASCII letters, digits, '.', '_' or '-'.`);
44
- if (scale && VECTOR_TYPES.has(image.kind)) throw new SetupError(`${given}: a PDF or SVG image has one scale; drop the @${scale}x.`);
45
- return { ...image, name, scale: scale && `${scale}x` };
46
- })),
47
- };
22
+ const file = (given, kinds, what) => {
23
+ const source = resolve(cwd, given);
24
+ if (!existsSync(source) || !statSync(source).isFile())
25
+ throw new SetupError(`${given}: no such file.`);
26
+ const kind = extname(source).toLowerCase();
27
+ if (!kinds.has(kind))
28
+ throw new SetupError(`${given}: ${what} must be ${[...kinds].join(', ')}.`);
29
+ if (!FILE_NAME.test(basename(source))) {
30
+ throw new SetupError(`${given}: rename it to ASCII letters, digits, spaces, '.', '_', '@' and '-' first.`);
31
+ }
32
+ return { source, file: basename(source), kind };
33
+ };
34
+ const once = (list) => {
35
+ const repeated = list.find((item, index) => list.findIndex(other => other.file === item.file) !== index);
36
+ if (repeated)
37
+ throw new SetupError(`${repeated.file} is named twice; the widget keeps one file of each name.`);
38
+ return list;
39
+ };
40
+ return {
41
+ fonts: once(fonts.map(given => file(given, FONT_TYPES, 'a font'))),
42
+ assets: once(assets.map((given) => {
43
+ const image = file(given, IMAGE_TYPES, 'an image');
44
+ const base = basename(image.file, extname(image.file));
45
+ const scale = SCALES.find(item => base.endsWith(`@${item}`));
46
+ const name = scale ? base.slice(0, -(scale.length + 1)) : base;
47
+ if (!NAME.test(name))
48
+ throw new SetupError(`${given}: the asset name ${JSON.stringify(name)} must be 1 to 64 ASCII letters, digits, '.', '_' or '-'.`);
49
+ if (scale && VECTOR_TYPES.has(image.kind))
50
+ throw new SetupError(`${given}: a PDF or SVG image has one scale; drop the @${scale}.`);
51
+ return { ...image, name, scale };
52
+ })),
53
+ };
48
54
  }
49
-
50
55
  /** Copies `source` to `target`: created when absent, updated when its bytes differ, unchanged otherwise. */
51
56
  function copyStep(show, source, target, detail) {
52
- if (!existsSync(target)) return step('created', show(target), detail, copyEffect(source, target));
53
- if (readFileSync(source).equals(readFileSync(target))) return step('unchanged', show(target));
54
- return step('updated', show(target), detail, copyEffect(source, target));
57
+ if (!existsSync(target))
58
+ return step('created', show(target), detail, copyEffect(source, target));
59
+ if (readFileSync(source).equals(readFileSync(target)))
60
+ return step('unchanged', show(target));
61
+ return step('updated', show(target), detail, copyEffect(source, target));
55
62
  }
56
-
57
63
  const copyEffect = (source, target) => () => {
58
- mkdirSync(dirname(target), { recursive: true });
59
- copyFileSync(source, target);
64
+ mkdirSync(dirname(target), { recursive: true });
65
+ copyFileSync(source, target);
60
66
  };
61
-
62
67
  /** The steps that copy the fonts into the widget's Fonts folder. */
63
68
  export function fontSteps({ files, show }, widget) {
64
- return files.fonts.map(({ source, file }) => {
65
- const names = fontNames(readFileSync(source));
66
- const detail = names ? `fontFamily: ${[...new Set([names.postScript, names.family].filter(Boolean))].map(name => JSON.stringify(name)).join(' or ')}` : '';
67
- return copyStep(show, source, join(widget, FONTS, file), detail);
68
- });
69
+ return files.fonts.map(({ source, file }) => {
70
+ const names = fontNames(readFileSync(source));
71
+ const detail = names ? `fontFamily: ${[...new Set([names.postScript, names.family].filter(Boolean))].map(name => JSON.stringify(name)).join(' or ')}` : '';
72
+ return copyStep(show, source, join(widget, FONTS, file), detail);
73
+ });
69
74
  }
70
-
71
75
  /** The font files the widget bundles after this run: those in its Fonts folder and those being copied there. */
72
76
  export function bundledFonts({ files }, widget) {
73
- const folder = join(widget, FONTS);
74
- const present = existsSync(folder) ? readdirSync(folder).filter(name => FONT_TYPES.has(extname(name).toLowerCase())) : [];
75
- return [...new Set([...present, ...files.fonts.map(({ file }) => file)])].sort();
77
+ const folder = join(widget, FONTS);
78
+ const present = existsSync(folder) ? readdirSync(folder).filter(name => FONT_TYPES.has(extname(name).toLowerCase())) : [];
79
+ return [...new Set([...present, ...files.fonts.map(({ file }) => file)])].sort();
76
80
  }
77
-
78
81
  /** The steps that put the images into the widget's asset catalog, one image set per asset name. */
79
82
  export function assetSteps({ files, show }, widget) {
80
- if (files.assets.length === 0) return [];
81
- const catalog = join(widget, CATALOG);
82
- const root = join(catalog, 'Contents.json');
83
- const steps = existsSync(root) ? [] : [step('created', show(root), '', writeFile(root, catalogJson(CATALOG_INFO)))];
84
- const sets = Map.groupBy(files.assets, ({ name }) => name);
85
- for (const [name, images] of sets) {
86
- const folder = join(catalog, `${name}.imageset`);
87
- steps.push(...images.map(({ source, file }) => copyStep(show, source, join(folder, file), `the asset "${name}"`)));
88
- steps.push(contentsStep(show, join(folder, 'Contents.json'), images));
89
- }
90
- return steps;
83
+ if (files.assets.length === 0)
84
+ return [];
85
+ const catalog = join(widget, CATALOG);
86
+ const root = join(catalog, 'Contents.json');
87
+ const steps = existsSync(root) ? [] : [step('created', show(root), '', writeFile(root, catalogJson(CATALOG_INFO)))];
88
+ const sets = Map.groupBy(files.assets, ({ name }) => name);
89
+ for (const [name, images] of sets) {
90
+ const folder = join(catalog, `${name}.imageset`);
91
+ steps.push(...images.map(({ source, file }) => copyStep(show, source, join(folder, file), `the asset "${name}"`)));
92
+ steps.push(contentsStep(show, join(folder, 'Contents.json'), images));
93
+ }
94
+ return steps;
91
95
  }
92
-
93
96
  /** An image set's Contents.json with an entry for each image; entries already there stay as they are. */
94
97
  function contentsStep(show, path, images) {
95
- const text = readText(path);
96
- const current = text === undefined ? { images: [], ...CATALOG_INFO } : parseJson(text);
97
- if (!Array.isArray(current?.images)) return step('todo', show(path), `not an image set's Contents.json; add ${images.map(({ file }) => file).join(', ')} to it in Xcode`);
98
- const missing = images.filter(({ file }) => !current.images.some(entry => entry?.filename === file));
99
- if (missing.length === 0) return step('unchanged', show(path));
100
- const next = { ...current, images: [...current.images, ...missing.map(entry)] };
101
- return step(text === undefined ? 'created' : 'updated', show(path), '', writeFile(path, catalogJson(next)));
98
+ const text = readText(path);
99
+ const current = text === undefined ? { images: [], ...CATALOG_INFO } : parseJson(text);
100
+ const listed = member(current, 'images');
101
+ if (!isRecord(current) || !isList(listed))
102
+ return step('todo', show(path), `not an image set's Contents.json; add ${images.map(({ file }) => file).join(', ')} to it in Xcode`);
103
+ const missing = images.filter(({ file }) => !listed.some(item => member(item, 'filename') === file));
104
+ if (missing.length === 0)
105
+ return step('unchanged', show(path));
106
+ const next = { ...current, images: [...listed, ...missing.map(entry)] };
107
+ return step(text === undefined ? 'created' : 'updated', show(path), '', writeFile(path, catalogJson(next)));
102
108
  }
103
-
104
109
  /** The entry of an image: a bitmap at its scale or for any scale, a PDF or SVG kept as vector data. */
105
110
  function entry({ file, kind, scale }) {
106
- const vector = VECTOR_TYPES.has(kind) ? { properties: { 'preserves-vector-representation': true } } : {};
107
- return { filename: file, idiom: 'universal', ...vector, ...(scale && { scale }) };
111
+ const vector = VECTOR_TYPES.has(kind) ? { properties: { 'preserves-vector-representation': true } } : {};
112
+ return { filename: file, idiom: 'universal', ...vector, ...(scale && { scale }) };
108
113
  }
109
-
110
114
  /** JSON as Xcode writes an asset catalog: two spaces, and a space before each colon. */
111
- const catalogJson = value => `${JSON.stringify(value, null, 2).replace(/^(\s*"(?:[^"\\]|\\.)*"): /gm, '$1 : ')}\n`;
112
-
115
+ const catalogJson = (value) => `${JSON.stringify(value, null, 2).replace(/^(\s*"(?:[^"\\]|\\.)*"): /gm, '$1 : ')}\n`;
113
116
  /**
114
117
  * The family and PostScript names in the name table of a TrueType or OpenType font, for the report: they are
115
118
  * what a style's `fontFamily` takes. Undefined for a collection or a file it cannot read.
116
119
  */
117
120
  export function fontNames(bytes) {
118
- try {
119
- if (!['\0\u0001\0\0', 'OTTO', 'true'].includes(bytes.toString('latin1', 0, 4))) return undefined;
120
- for (let index = 0; index < bytes.readUInt16BE(4); index += 1) {
121
- const record = 12 + index * 16;
122
- if (bytes.toString('latin1', record, record + 4) !== 'name') continue;
123
- const offset = bytes.readUInt32BE(record + 8);
124
- return names(bytes.subarray(offset, offset + bytes.readUInt32BE(record + 12)));
121
+ try {
122
+ if (!['\0\u0001\0\0', 'OTTO', 'true'].includes(bytes.toString('latin1', 0, 4)))
123
+ return undefined;
124
+ for (let index = 0; index < bytes.readUInt16BE(4); index += 1) {
125
+ const record = 12 + index * 16;
126
+ if (bytes.toString('latin1', record, record + 4) !== 'name')
127
+ continue;
128
+ const offset = bytes.readUInt32BE(record + 8);
129
+ return names(bytes.subarray(offset, offset + bytes.readUInt32BE(record + 12)));
130
+ }
125
131
  }
126
- } catch (error) {
127
- if (!(error instanceof RangeError)) throw error;
128
- }
129
- return undefined;
132
+ catch (error) {
133
+ if (!(error instanceof RangeError))
134
+ throw error;
135
+ }
136
+ return undefined;
130
137
  }
131
-
132
138
  /** Name IDs 1 (family), 16 (typographic family) and 6 (PostScript), Windows Unicode before Macintosh Roman. */
133
139
  function names(table) {
134
- const strings = table.readUInt16BE(4);
135
- const found = {};
136
- for (let index = 0; index < table.readUInt16BE(2); index += 1) {
137
- const record = 6 + index * 12;
138
- const [platform, , , id, length, offset] = [0, 2, 4, 6, 8, 10].map(at => table.readUInt16BE(record + at));
139
- if (![1, 6, 16].includes(id) || (platform !== 3 && platform !== 1) || found[id]?.platform === 3) continue;
140
- const raw = table.subarray(strings + offset, strings + offset + length);
141
- if (raw.length !== length) throw new RangeError('name record outside the table');
142
- const text = platform === 3 ? Buffer.from(raw).swap16().toString('utf16le') : raw.toString('latin1');
143
- found[id] = { platform, text };
144
- }
145
- const family = (found[16] ?? found[1])?.text;
146
- const postScript = found[6]?.text;
147
- return family || postScript ? { family, postScript } : undefined;
140
+ const strings = table.readUInt16BE(4);
141
+ const found = {};
142
+ for (let index = 0; index < table.readUInt16BE(2); index += 1) {
143
+ const record = 6 + index * 12;
144
+ // A name record: its platform, its encoding and language, which are not read, then its name ID, length and offset.
145
+ const platform = table.readUInt16BE(record);
146
+ const id = table.readUInt16BE(record + 6);
147
+ const length = table.readUInt16BE(record + 8);
148
+ const offset = table.readUInt16BE(record + 10);
149
+ if (![1, 6, 16].includes(id) || (platform !== 3 && platform !== 1) || found[id]?.platform === 3)
150
+ continue;
151
+ const raw = table.subarray(strings + offset, strings + offset + length);
152
+ if (raw.length !== length)
153
+ throw new RangeError('name record outside the table');
154
+ const text = platform === 3 ? Buffer.from(raw).swap16().toString('utf16le') : raw.toString('latin1');
155
+ found[id] = { platform, text };
156
+ }
157
+ const family = (found[16] ?? found[1])?.text;
158
+ const postScript = found[6]?.text;
159
+ return family || postScript ? { family, postScript } : undefined;
148
160
  }