Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | 4x 4x 4x 4x 4x 293x 77x 31x 2x 2x 73x 79x 1x 30x 30x 30x 28x 30x 27x 27x 27x 27x 27x 2x 25x 25x 1x 97x 15x 25x 9x 24x 24x 3x 3x 27x 27x 27x 84x 27x 29x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 21x 27x 27x 22x 22x 22x 1x 21x 21x 21x 21x 21x 21x 21x 22x 21x 21x 1x 19x 19x 22x | /**
* Builds a plugin app's settings page into the config.html its pbw carries.
*
* A plugin app's settings page is a Clay page, written as a Clay config in src/config/index.ts the
* way a face writes its page, with an optional customClay beside it. The Pebble app opens a plugin's
* page from a file in the pbw rather than from a URL the phone builds, so the page is built here, once,
* into a single self-contained file.
*
* The config is bundled with esbuild the way the plugin's script is, so its imports resolve the same
* way, and then Clay builds the page as it would on a phone, with the phone's globals stood in. The
* page gets the framework's show and hide for its `visibleWhen` rows, then the framework's plugin
* settings code from ts/plugin-app/page.ts, then the plugin app's own customClay. The Clay components
* the config exports as `components` are registered too, the way a face passes them to
* `startPebbleApp`, so a page can hold the framework's location search. The settings code
* loads the saved settings from the plugin and saves them back to it, so the page gets a status row for
* it to report in, above the Save button, and a Save button when the config has none. Clay's own Save
* goes to a return address, which is pointed at an in-page hash so it can never close the page unsaved.
*
* A plugin settings page opens with no watch behind it, so a row that names watch capabilities is
* refused, since Clay has no watch to check them against.
*/
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { createRequire } from 'node:module';
import esbuild from 'esbuild';
import { combineCustomFns } from '../../ts/clay/custom-fn.ts';
import dependentVisibility from '../../ts/clay/dependent-visibility.ts';
import { borrowLooks, componentName } from '../../ts/clay/looks.ts';
import pageStyleComponent from '../../ts/clay/page-style-component.ts';
import { rowTypes, typesWithoutComponent } from '../../ts/clay/rows.ts';
import pluginSettingsPage from '../../ts/plugin-app/page.ts';
import { stubModuleLoad } from '../../ts/testing/module-load.ts';
import { APPINFO_REL, ENGINE, icaljsBundle, WORKSPACE } from '../shared/paths.ts';
import { ToolError } from '../shared/tool-error.ts';
import { isObject } from '../shared/values.ts';
import { icaljsPlugin } from './build-plugin.ts';
import { checkCustomClay, installHost } from './settings-page.ts';
import { reachesSite, readOwn } from '../manifest/permissions.ts';
import { LOCATION_GEOCODER_HOST, LOCATION_ZONE_HOST } from '../../ts/clay/location-hosts.ts';
import { settingsPageUrl, takePreviewLoaders } from '../../ts/clay/preview-pictures.ts';
import type { Permission } from '../manifest/permissions.ts';
import type { ClayConfigItem } from '../../ts/clay/types.ts';
/** Where a plugin app's settings page config starts, relative to the plugin app's folder. */
export const PLUGIN_CONFIG_ENTRY = path.join('src', 'config', 'index.ts');
/** The id of the row the settings code reports in. */
export const SAVE_STATUS_ID = 'paf-save-status';
/** Clay's return address on a phone, which a plugin app's page cannot use. */
const PHONE_RETURN = 'window.returnTo="pebblejs://close#"';
/** The in-page hash the page's return address points at in its place. */
const PAGE_RETURN = 'window.returnTo="#paf-save:"';
/** What a plugin app's src/config/index.ts exports. */
export interface PluginPageSource {
clayConfig: ClayConfigItem[];
customClay?: unknown;
/** Clay components the page's rows need beyond Clay's own, such as the framework's location search. */
components?: unknown[];
/** The plugin app's own usesPermissions, from its appinfo, which a location search needs Open-Meteo in. */
usesPermissions?: Permission[];
}
/** The type of the framework's location search row, which a refusal names the import for. */
const LOCATION_SEARCH = 'locationsearch';
/** Clay as the build uses it. */
type PageClay = { config: unknown[]; meta: unknown; components?: Record<string, unknown>; generateUrl(): string; registerComponent(component: unknown): void };
/** Clay's constructor, as the build loads it. */
type PageClayConstructor = new (config: unknown, customFn: unknown, options: unknown) => PageClay;
/** Whether any row on the page, inside sections too, matches. */
function anyItem(items: ClayConfigItem[], test: (item: ClayConfigItem) => boolean): boolean {
// Clay builds the rows of a list sitting where a row goes, so the list is looked into
return items.some((item) => (Array.isArray(item) ? anyItem(item, test) : test(item) || (item.items ? anyItem(item.items, test) : false)));
}
/** Puts the status row just above the first Save button, inside a section too, and says whether there was one. */
function placeStatus(items: ClayConfigItem[], status: ClayConfigItem): boolean {
const submit = items.findIndex((item) => item.type === 'submit');
if (submit !== -1) {
items.splice(submit, 0, status);
return true;
}
return items.some((item) => (item.items ? placeStatus(item.items, status) : false));
}
/**
* The rows a plugin app's page is built from: its own, a status row above its Save button, and a
* Save button at the foot when it has none.
*
* @param config The plugin app's Clay config.
* @param name The plugin app's name, which a refusal names.
* @return The rows to build the page from. The config passed in is left as it was.
*/
export function pluginPageItems(config: ClayConfigItem[], name: string): ClayConfigItem[] {
if (anyItem(config, (item) => (item as { capabilities?: unknown }).capabilities !== undefined)) {
throw new ToolError(`${name}'s settings page has a row that names watch capabilities, which a plugin's page cannot check, since it opens with no watch behind it. Take capabilities off the row`);
}
// a Clay config is plain data, so a copy through JSON leaves the plugin's own untouched
const items: ClayConfigItem[] = JSON.parse(JSON.stringify(config));
const status: ClayConfigItem = { type: 'text', id: SAVE_STATUS_ID, defaultValue: '' };
if (!placeStatus(items, status)) {
items.push(status, { type: 'submit', defaultValue: 'Save' });
}
return items;
}
/**
* Registers the plugin app's own components, with the Clay components the framework's rows take their
* look from ahead of them, as a face's page gets them.
*
* The location search draws Clay's text box and takes its look from that component's style, which a
* page with no text box of its own would never carry, so it gets Clay's from a spare Clay. borrowLooks
* in ts/clay/looks.ts does that for a face's page too. A plugin app passing its own text box keeps it.
*/
function registerComponents(Clay: PageClayConstructor, clay: PageClay, items: ClayConfigItem[], components: unknown[]): void {
borrowLooks(Clay, clay, rowTypes(items), components);
components.forEach((component) => clay.registerComponent(component));
}
/**
* Stops on a row no registered component draws. Clay stops building the page at that row in the
* webview, so the wearer would open a blank page with nothing said.
*
* A row with no type stops Clay the same way. It is named after any row type nothing draws, since
* that one says which component to export.
*/
function checkDrawn(clay: PageClay, items: ClayConfigItem[], name: string): void {
const undrawn = typesWithoutComponent(items, clay.components || {});
const missing = undrawn.find((type) => typeof type === 'string');
if (missing === LOCATION_SEARCH) {
throw new ToolError(`${name}'s settings page has a locationsearch row, which no component draws. Import the framework's location search from ts/clay/location-component.ts in src/config/index.ts and export it in components, as in export const components = [locationSearch]`);
}
Iif (missing !== undefined) {
throw new ToolError(`${name}'s settings page has a ${missing} row, which no component draws, so the page would open blank. Export the component that draws it in components from src/config/index.ts, or take the row off the page`);
}
if (undrawn.length) {
throw new ToolError(`${name}'s settings page has a row with no type, which Clay stops the page at, so the page would open blank. Give the row a type, or take it off the page`);
}
}
/**
* Stops on a location search the plugin app's usesPermissions give no way out to. The search calls
* Open-Meteo's geocoder from inside the page, and a row marked `timeZone: true` calls its forecast
* host as well for a picked place's zone. On Android the Pebble app holds the page to the sites the
* plugin lists, so a host left off fails there with nothing said. Each host the page's searches call
* is checked on its own, so `open-meteo.com`, each host by name, or an Internet entry naming no site
* all pass.
*/
function checkPickerSites(items: ClayConfigItem[], permissions: Permission[], name: string): void {
if (!anyItem(items, (item) => item.type === LOCATION_SEARCH)) {
return;
}
const zoned = anyItem(items, (item) => item.type === LOCATION_SEARCH && Boolean(item.timeZone));
const hosts = zoned ? [LOCATION_GEOCODER_HOST, LOCATION_ZONE_HOST] : [LOCATION_GEOCODER_HOST];
const missing = hosts.filter((host) => !reachesSite(permissions, host));
if (missing.length) {
const what = zoned ? 'a locationsearch row that takes a time zone' : 'a locationsearch row';
throw new ToolError(`${name}'s settings page has ${what}, which calls ${hosts.join(' and ')}, but its appinfo usesPermissions does not reach ${missing.join(' or ')} under Internet, so on Android the search fails. List "open-meteo.com", which covers ${zoned ? 'both' : 'it'}, or each host the search calls, in the domains of an Internet entry`);
}
}
/**
* Builds a plugin app's settings page as one self-contained HTML file.
*
* @param source The plugin app's Clay config, its optional customClay and components, and its own usesPermissions.
* @param name The plugin app's name, which a refusal names.
* @return The page's HTML.
*/
export function renderPluginPage(source: PluginPageSource, name: string): string {
// a theme picker's previews function comes off the page before Clay sees it, the way a face's does
const taken = takePreviewLoaders(source.clayConfig);
const items = pluginPageItems(taken.page, name);
const customFn = combineCustomFns([
{ code: anyItem(items, (item) => item.visibleWhen !== undefined) ? dependentVisibility : undefined, label: 'the framework\'s show and hide' },
{ code: pluginSettingsPage, label: 'the framework\'s plugin settings' },
{ code: source.customClay, label: 'the plugin app\'s customClay' },
]);
// Clay reads message_keys, Pebble, and localStorage as it loads and as it builds the page, and
// none of them exist under node, so each is stood in for the build and put back after it
const restoreHost = installHost({ platform: 'emery', settings: null }, null);
const restoreLoad = stubModuleLoad((id) => (id === 'message_keys' ? {} : undefined));
try {
const Clay = createRequire(path.join(ENGINE, 'package.json'))('@rebble/clay/src/js/index') as PageClayConstructor;
const clay = new Clay(items, customFn, { autoHandleEvents: false });
// the framework's rules for the whole page, the same ones a face's page carries. without them the
// Pebble Android app's head script puts Clay's component styles ahead of its base sheet, and a select
// row keeps the base padding, a gap under its value and at each side
clay.registerComponent(pageStyleComponent);
// the plugin app's own components go after the framework's rules, as a face's do, so a rule of
// its own at the same weight still wins
registerComponents(Clay, clay, items, source.components || []);
checkDrawn(clay, items, name);
checkPickerSites(items, source.usesPermissions || [], name);
// a plugin's page opens with no watch behind it, so each theme picker keeps the one list of shots
// it draws without one
clay.meta = { activeWatchInfo: null, accountToken: '', watchToken: '', userData: {} };
const url = settingsPageUrl(clay, taken.loaders);
const prefix = 'data:text/html;charset=utf-8,';
const html = url.startsWith(prefix) ? decodeURIComponent(url.slice(prefix.length)) : url;
Iif (!html.includes(PHONE_RETURN)) {
throw new ToolError(`Clay's page for ${name} does not set its return address where the build expects, so its Save could close the page unsaved. Check the @rebble/clay version the framework asks for`);
}
return html.replace(PHONE_RETURN, PAGE_RETURN);
} finally {
restoreLoad();
restoreHost();
}
}
/**
* Reads a plugin app's settings page config from its src/config/index.ts.
*
* The config is bundled with esbuild the way the plugin's script is, so a value it imports from the
* plugin's own code or the framework's resolves the same way, and then run under node.
*
* @param pluginDir The plugin app's folder.
* @param name The plugin app's name, which a refusal names.
* @return The Clay config and the optional customClay and components it exports, with the plugin
* app's own usesPermissions from its appinfo.
*/
export async function readPluginPage(pluginDir: string, name: string): Promise<PluginPageSource> {
const entry = path.resolve(pluginDir, PLUGIN_CONFIG_ENTRY);
const shown = PLUGIN_CONFIG_ENTRY.split(path.sep).join('/');
if (!fs.existsSync(entry)) {
throw new ToolError(`${name} names config.html as its settings page but has no ${shown}, which is where its page starts`);
}
let code: string;
try {
// a page that shares a file with the plugin's script can reach the iCal reader, whose ./icaljs only
// the build provides, so it is mapped here as it is for the script
const result = await esbuild.build({ entryPoints: [entry], absWorkingDir: WORKSPACE, bundle: true, write: false, format: 'cjs', platform: 'node', logLevel: 'silent', plugins: [icaljsPlugin(icaljsBundle())] });
code = result.outputFiles[0].text;
} catch (error) {
throw new ToolError(`${name}'s ${shown} did not bundle. ${error instanceof Error ? error.message : String(error)}`);
}
const module = { exports: {} as Record<string, unknown> };
try {
vm.runInThisContext(`(function (module, exports, require) {\n${code}\n})`, { filename: entry })(module, module.exports, createRequire(entry));
} catch (error) {
throw new ToolError(`${name}'s ${shown} stopped as it loaded. ${error instanceof Error ? error.message : String(error)}`);
}
const exported = isObject(module.exports) ? module.exports : {};
Iif (!Array.isArray(exported.clayConfig)) {
throw new ToolError(`${name}'s ${shown} has to export clayConfig, the page's Clay config as a list of rows`);
}
checkCustomClay(name, exported.customClay);
if (exported.components !== undefined && (!Array.isArray(exported.components) || exported.components.some((component) => typeof componentName(component) !== 'string'))) {
throw new ToolError(`${name}'s ${shown} exports components that are not a list of Clay components, each with a name. Export a list such as [locationSearch], or leave components out`);
}
// the build checks the rest of the appinfo, so only its permissions are read here
const appinfo = path.join(pluginDir, APPINFO_REL);
const declared = fs.existsSync(appinfo) ? (JSON.parse(fs.readFileSync(appinfo, 'utf8')) as { usesPermissions?: unknown }).usesPermissions : undefined;
return { clayConfig: exported.clayConfig as ClayConfigItem[], customClay: exported.customClay, components: exported.components as unknown[] | undefined, usesPermissions: readOwn(declared, name) };
}
|