From a1a3edb4b41bfce373a952bf5ad820ba885f31c8 Mon Sep 17 00:00:00 2001 From: SylvainDruaux Date: Tue, 17 Nov 2026 17:00:35 +0100 Subject: [PATCH 1/2] feat(cms): suggest the Sanity project a site's config files name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Log in with Sanity" suggested a project only when a .env file named it (*SANITY_PROJECT_ID). Many sites write the id in code instead: a site with an embedded Studio typically has projectId in astro.config.mjs and in studio/sanity.config.ts or studio/sanity.cli.ts, so nothing was preselected. The suggestion now also reads a projectId string literal from astro.config.*, sanity.config.* and sanity.cli.*, at the root and in studio/, without running them. It reuses sanitySource.ts, so comments and ids built at run time (process.env…) do not count. The .env id comes first, and only a project the person belongs to is suggested, so a stale id is passed over. The dataset still comes from .env. Files, file size and ids are bounded. --- docs/contracts.md | 5 +- electron/content/sanityLogin.ts | 15 ++-- electron/content/sanityProjectSource.ts | 80 +++++++++++++++++++ test/electron/content/cmsConnections.test.js | 21 +++++ .../content/sanityProjectSource.test.js | 54 +++++++++++++ 5 files changed, 168 insertions(+), 7 deletions(-) create mode 100644 electron/content/sanityProjectSource.ts create mode 100644 test/electron/content/sanityProjectSource.test.js diff --git a/docs/contracts.md b/docs/contracts.md index 67d559899..411f05ec7 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -1666,7 +1666,10 @@ arrive in the query, in a `url` parameter, or in the fragment, which a page on t and returns once in the query. The id is exchanged for the person's login token, used only in the main process to list projects and datasets and to create a project key with the Editor role, then logged out. Only the key is kept. The sign-in page must be on `https://www.sanity.io`. -A suggestion comes from the site's `.env` (`*SANITY_PROJECT_ID`, `*SANITY_DATASET`). Sessions +A suggestion comes from the site's `.env` (`*SANITY_PROJECT_ID`, `*SANITY_DATASET`); when that +names none of the person's projects, from a `projectId: '…'` string literal in the site's `astro.config.*`, +`sanity.config.*` or `sanity.cli.*`, at the root or in `studio/`, read without running them. +Only a project the person belongs to is suggested. Sessions time out after five minutes. A role that cannot create keys is told to paste an Editor key instead. While Stacki previews a project with a Sanity connection, its dev server gets diff --git a/electron/content/sanityLogin.ts b/electron/content/sanityLogin.ts index a078d345a..80dd876fd 100644 --- a/electron/content/sanityLogin.ts +++ b/electron/content/sanityLogin.ts @@ -5,8 +5,8 @@ // sign-in page with that server as the place to come back to. // 2. Sanity redirects back with a one-time session id, exchanged for the // person's login token. -// 3. Their projects and datasets are listed; the one the site's own .env -// names is suggested. +// 3. Their projects and datasets are listed; the one the site's own .env or +// config files name is suggested. // 4. On their choice, a project key with the Editor role is created and kept // (encrypted, cmsConnectionStore.ts), and the login token is logged out. // @@ -25,6 +25,7 @@ import { described, type Described } from '../../shared/properties/i18n/messageR import { SANITY_LOGIN_TIMEOUT_MS, type SanityLoginRequest, type SanityLoginState, type SanityProjectChoice } from '../../shared/properties/cmsConnections'; import type { CmsConnectionStore } from './cmsConnectionStore'; import { SanityRequestError, createSanityEditorKey, sanityLoginURL, sanityLogout, sanityProjects, sanityTokenForSession } from './sanityApi'; +import { siteConfigProjectIds } from './sanityProjectSource'; const SUCCESS_PAGE = 'https://www.sanity.io/login/success'; // The .env lines read for a suggestion, and the longest file read for them. @@ -266,8 +267,9 @@ function failureProblem(error: unknown): Described { return message.length > 0 ? { message: message.slice(0, 900) } : described('cmsBackend.sanity.signInFailed'); } -// The project and dataset the site itself reads, from its .env files, when one -// of the person's projects has them. +// The project and dataset the site itself reads, when one of the person's +// projects has them: the project from its .env files, else from a `projectId` +// its config files write (sanityProjectSource.ts); the dataset from .env. function siteSuggestion(projectRoot: string, projects: readonly SanityProjectChoice[]) { const values = new Map(); for (const name of ENV_FILES) { @@ -276,9 +278,10 @@ function siteSuggestion(projectRoot: string, projects: readonly SanityProjectCho } } const pick = (suffix: string) => [...values].find(([key]) => /^(PUBLIC_|SANITY_STUDIO_|NEXT_PUBLIC_)?SANITY_/.test(key) && key.endsWith(suffix))?.[1]; - const projectId = pick('PROJECT_ID'); + const envProjectId = pick('PROJECT_ID'); + const candidates = envProjectId === undefined ? siteConfigProjectIds(projectRoot) : [envProjectId, ...siteConfigProjectIds(projectRoot)]; const dataset = pick('DATASET') ?? 'production'; - const project = projects.find((entry) => entry.id === projectId); + const project = candidates.map((id) => projects.find((entry) => entry.id === id)).find((entry) => entry !== undefined); return project && project.datasets.includes(dataset) ? { projectId: project.id, dataset } : undefined; } diff --git a/electron/content/sanityProjectSource.ts b/electron/content/sanityProjectSource.ts new file mode 100644 index 000000000..dc5fe2e80 --- /dev/null +++ b/electron/content/sanityProjectSource.ts @@ -0,0 +1,80 @@ +// The Sanity project a site names in its own config files, read without running +// them: a site often writes `projectId: '…'` in astro.config or in its Studio's +// sanity.config / sanity.cli rather than in a .env file. Comments and strings +// are skipped (sanitySource.ts), so a commented-out id does not count. A found +// id is only ever a suggestion matched against the person's own projects. + +import fs from 'node:fs'; +import path from 'node:path'; +import { assert } from '../../shared/core/assert'; +import { ownString, walk } from './sanitySource'; + +// The folders a site keeps its config in (the root, and an embedded Studio), the +// files read there, the longest file read, and the ids kept from one file. +const CONFIG_FOLDERS = ['', 'studio'] as const; +const CONFIG_FILES = [ + 'astro.config.mjs', + 'astro.config.ts', + 'astro.config.js', + 'astro.config.mts', + 'astro.config.cjs', + 'sanity.config.ts', + 'sanity.config.js', + 'sanity.config.mjs', + 'sanity.config.tsx', + 'sanity.config.jsx', + 'sanity.cli.ts', + 'sanity.cli.js', + 'sanity.cli.mjs', +] as const; +const CONFIG_BYTES_MAX = 256 * 1024; +const IDS_PER_FILE_MAX = 8; +// Sanity project ids are short lowercase letters and digits. +const PROJECT_ID = /^[a-z0-9]{1,32}$/; +const PROJECT_ID_KEY = /(?'`, at any depth, in order. */ +export function configProjectIds(source: string): readonly string[] { + const ids: string[] = []; + walk(source, (index) => { + PROJECT_ID_KEY.lastIndex = index; + if (PROJECT_ID_KEY.test(source)) { + const value = ownString(source.slice(index), 'projectId'); + if (value !== undefined && PROJECT_ID.test(value) && !ids.includes(value)) { + ids.push(value); + } + } + return ids.length < IDS_PER_FILE_MAX; + }); + assert(ids.length <= IDS_PER_FILE_MAX, 'One file gives a bounded number of ids'); + return ids; +} + +/** The project ids the site's config files name, root files first; unreadable files are skipped. */ +export function siteConfigProjectIds(projectRoot: string): readonly string[] { + assert(path.isAbsolute(projectRoot), 'The project root is an absolute path'); + const ids: string[] = []; + for (const folder of CONFIG_FOLDERS) { + for (const name of CONFIG_FILES) { + for (const id of configProjectIds(readConfig(path.join(projectRoot, folder, name)))) { + if (!ids.includes(id)) { + ids.push(id); + } + } + } + } + assert(ids.length <= CONFIG_FOLDERS.length * CONFIG_FILES.length * IDS_PER_FILE_MAX, 'The site gives a bounded number of ids'); + return ids; +} + +// A config file's text, or nothing when it is missing, unreadable or too long. +function readConfig(file: string): string { + try { + if (fs.statSync(file).size > CONFIG_BYTES_MAX) { + return ''; + } + return fs.readFileSync(file, 'utf8'); + } catch { + return ''; + } +} diff --git a/test/electron/content/cmsConnections.test.js b/test/electron/content/cmsConnections.test.js index a3455d4be..aced7de87 100644 --- a/test/electron/content/cmsConnections.test.js +++ b/test/electron/content/cmsConnections.test.js @@ -179,6 +179,27 @@ test('signing in saves an Editor key for the chosen project and logs the login o } })); +test('a site that writes its project id in a config file, not in .env, gets it suggested', () => + withFolder(async (folder) => { + const root = path.join(folder, 'site'); + fs.mkdirSync(path.join(root, 'studio'), { recursive: true }); + // The shape of a site with an embedded Studio: the id in code, the dataset in .env.development. + fs.writeFileSync(path.join(root, 'astro.config.mjs'), `// projectId: 'old111'\nconst sanityProject = { projectId: "nope999" };`); + fs.writeFileSync(path.join(root, 'studio', 'sanity.cli.ts'), `export default defineCliConfig({ api: { projectId: 'abc123' } })`); + fs.writeFileSync(path.join(root, '.env.development'), 'PUBLIC_SANITY_DATASET=production\n'); + const realFetch = globalThis.fetch; + const login = new SanityLogin(new CmsConnectionStore(crypt(), () => folder)); + try { + globalThis.fetch = fakeSanity([]); + const id = await signIn(login, root); + const choosing = await until(login, root, id, 'choosing'); + assert.deepEqual(choosing.suggestion, { projectId: 'abc123', dataset: 'production' }, 'an id outside the account is passed over'); + login.request(root, { action: 'cancel', id }); + } finally { + globalThis.fetch = realFetch; + } + })); + test('a role that cannot create keys says so, and nothing is saved', () => withFolder(async (folder) => { const calls = []; diff --git a/test/electron/content/sanityProjectSource.test.js b/test/electron/content/sanityProjectSource.test.js new file mode 100644 index 000000000..00278d8f9 --- /dev/null +++ b/test/electron/content/sanityProjectSource.test.js @@ -0,0 +1,54 @@ +// Goal: the Sanity project id a site writes in its own config files is found without running them, +// and nothing that only looks like one is. +// Method: config source texts in the shapes sites use (a nested object, a spread constant, a Studio's +// sanity.cli), then the negative space: comments, ids built at run time, malformed ids, other keys; +// and a temporary site folder with the id only in an embedded Studio. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { configProjectIds, siteConfigProjectIds } = require('#dist/electron/content/sanityProjectSource.js'); + +test('an id written as a string literal is found, at any depth, in order and once', () => { + assert.deepEqual(configProjectIds(`const sanityProject = {\n projectId: "ecka10i7",\n dataset: env.PUBLIC_SANITY_DATASET || "production",\n};`), [ + 'ecka10i7', + ]); + assert.deepEqual(configProjectIds(`export default defineCliConfig({ api: { projectId: 'abc123', dataset: 'production' } })`), ['abc123']); + assert.deepEqual(configProjectIds('integrations: [sanity({ projectId: `abc123` })]'), ['abc123']); + assert.deepEqual(configProjectIds(`a({ projectId: 'one111' }); b({ projectId: 'two222' }); c({ projectId: 'one111' })`), ['one111', 'two222']); +}); + +test('comments, run-time ids, malformed ids and other keys are not ids', () => { + assert.deepEqual(configProjectIds(`// projectId: 'old111'\n/* projectId: 'old222' */\nconst x = { projectId: 'new333' }`), ['new333']); + assert.deepEqual(configProjectIds(`const x = { projectId: process.env.SANITY_PROJECT_ID }`), []); + assert.deepEqual(configProjectIds('const x = { projectId: `${prefix}abc` }'), []); + assert.deepEqual(configProjectIds(`const x = { projectId: 'Has Spaces' }`), []); + assert.deepEqual(configProjectIds(`const x = { projectId: '' }`), []); + assert.deepEqual(configProjectIds(`const x = { projectId: '${'a'.repeat(33)}' }`), []); + assert.deepEqual(configProjectIds(`const x = { myProjectId: 'abc123', label: "projectId: 'abc123'" }`), []); + assert.deepEqual(configProjectIds(''), []); +}); + +test('one file gives at most eight ids', () => { + const many = Array.from({ length: 20 }, (_, index) => `{ projectId: 'p${index}' }`).join('\n'); + assert.equal(configProjectIds(many).length, 8); +}); + +test('a site folder: root config first, then an embedded Studio; missing files are skipped', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'stacki-sanity-config-')); + try { + assert.deepEqual(siteConfigProjectIds(root), []); + fs.mkdirSync(path.join(root, 'studio')); + fs.writeFileSync(path.join(root, 'studio', 'sanity.cli.ts'), `export default defineCliConfig({ api: { projectId: 'studio11' } })`); + assert.deepEqual(siteConfigProjectIds(root), ['studio11']); + fs.writeFileSync(path.join(root, 'astro.config.mjs'), `const sanityProject = { projectId: "root2222" };`); + fs.writeFileSync(path.join(root, 'studio', 'sanity.config.ts'), `export default defineConfig({ projectId: 'root2222' })`); + assert.deepEqual(siteConfigProjectIds(root), ['root2222', 'studio11']); + fs.writeFileSync(path.join(root, 'astro.config.ts'), `// ${'x'.repeat(256 * 1024)}\nconst a = { projectId: 'toolong1' }`); + assert.deepEqual(siteConfigProjectIds(root), ['root2222', 'studio11'], 'a file over the size limit is not read'); + assert.throws(() => siteConfigProjectIds('relative/site'), /absolute path/); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); From a9e9f9f091a3d696cfc86b738bab8868c5f536d5 Mon Sep 17 00:00:00 2001 From: SylvainDruaux Date: Tue, 17 Nov 2026 17:01:17 +0100 Subject: [PATCH 2/2] feat(cms): say when a site uses Sanity but has no Sanity connection Stacki never noticed that a site uses Sanity: CMS connections looked the same as for a site without it. When package.json lists @sanity/astro or sanity and no Sanity connection exists, CMS connections now says "This site uses Sanity. Connect it to edit its content in Stacki." The line goes away once connected. Studio shows it too, with no server change. hasDependency moves unchanged from features/props/loopCatalog.ts to src/lib/packageManifest.ts, because features may not import each other along this edge; its tests move with it. The new file is added to Studio's shared source list. Non-English lines are marked for review. --- .../i18n/messages/de/cmsConnections.ts | 1 + .../i18n/messages/en/cmsConnections.ts | 1 + .../i18n/messages/es/cmsConnections.ts | 1 + .../i18n/messages/fr/cmsConnections.ts | 1 + .../i18n/messages/ptBR/cmsConnections.ts | 1 + .../cmsConnections/CmsConnections.tsx | 23 +++++ src/features/props/loopCatalog.ts | 20 +--- src/lib/packageManifest.ts | 25 +++++ studio/scripts/shared-source.json | 1 + test/renderer/cms/sanityHint.test.js | 93 +++++++++++++++++++ test/renderer/lib/packageManifest.test.js | 26 ++++++ test/renderer/props/loopSettings.test.js | 4 - 12 files changed, 174 insertions(+), 23 deletions(-) create mode 100644 src/lib/packageManifest.ts create mode 100644 test/renderer/cms/sanityHint.test.js create mode 100644 test/renderer/lib/packageManifest.test.js diff --git a/shared/properties/i18n/messages/de/cmsConnections.ts b/shared/properties/i18n/messages/de/cmsConnections.ts index e86556dac..7a4419a20 100644 --- a/shared/properties/i18n/messages/de/cmsConnections.ts +++ b/shared/properties/i18n/messages/de/cmsConnections.ts @@ -46,6 +46,7 @@ export const messages = { 'cmsConnections.input.secret.printable': 'Ein API-Schlüssel besteht aus druckbaren Zeichen in einer Zeile.', 'cmsConnections.kind.custom': 'Eigenes CMS', 'cmsConnections.list.noEncryption': 'Dieser Computer kann keine Schlüssel verschlüsseln, deshalb speichert Stacki keine.', + 'cmsConnections.sanityDetected': 'Diese Website nutzt Sanity. Verbinde sie, um ihre Inhalte in Stacki zu bearbeiten.', // review 'cmsConnections.signIn.browser': 'Melde dich auf der Sanity-Seite in deinem Browser an und komm dann hierher zurück. Stacki erstellt einen Editor-Schlüssel für das Projekt dieser Website und behält nur diesen Schlüssel.', 'cmsConnections.signIn.cancelled': 'Anmeldung abgebrochen.', diff --git a/shared/properties/i18n/messages/en/cmsConnections.ts b/shared/properties/i18n/messages/en/cmsConnections.ts index 3d3fef3e6..b1ca9a50a 100644 --- a/shared/properties/i18n/messages/en/cmsConnections.ts +++ b/shared/properties/i18n/messages/en/cmsConnections.ts @@ -44,6 +44,7 @@ export const messages = { 'cmsConnections.input.secret.printable': 'An API key is printable characters on one line.', 'cmsConnections.kind.custom': 'Custom CMS', 'cmsConnections.list.noEncryption': 'This computer can’t encrypt keys, so Stacki won’t save any.', + 'cmsConnections.sanityDetected': 'This site uses Sanity. Connect it to edit its content in Stacki.', 'cmsConnections.signIn.browser': 'Sign in on Sanity’s page in your browser, then come back here. Stacki creates an Editor key for this site’s project and keeps only that key.', 'cmsConnections.signIn.cancelled': 'Sign-in cancelled.', diff --git a/shared/properties/i18n/messages/es/cmsConnections.ts b/shared/properties/i18n/messages/es/cmsConnections.ts index 6708d34ac..f73057b35 100644 --- a/shared/properties/i18n/messages/es/cmsConnections.ts +++ b/shared/properties/i18n/messages/es/cmsConnections.ts @@ -45,6 +45,7 @@ export const messages = { 'cmsConnections.input.secret.printable': 'Una clave de API son caracteres imprimibles en una sola línea.', 'cmsConnections.kind.custom': 'CMS personalizado', 'cmsConnections.list.noEncryption': 'Este equipo no puede cifrar claves, así que Stacki no guardará ninguna.', + 'cmsConnections.sanityDetected': 'Este sitio usa Sanity. Conéctalo para editar su contenido en Stacki.', // review 'cmsConnections.signIn.browser': 'Inicia sesión en la página de Sanity en tu navegador y vuelve aquí. Stacki crea una clave de Editor para el proyecto de este sitio y guarda solo esa clave.', 'cmsConnections.signIn.cancelled': 'Inicio de sesión cancelado.', diff --git a/shared/properties/i18n/messages/fr/cmsConnections.ts b/shared/properties/i18n/messages/fr/cmsConnections.ts index 68a83a185..552b035f2 100644 --- a/shared/properties/i18n/messages/fr/cmsConnections.ts +++ b/shared/properties/i18n/messages/fr/cmsConnections.ts @@ -46,6 +46,7 @@ export const messages = { 'cmsConnections.input.secret.printable': 'Une clé API se compose de caractères imprimables sur une seule ligne.', 'cmsConnections.kind.custom': 'CMS personnalisé', 'cmsConnections.list.noEncryption': 'Cet ordinateur ne peut pas chiffrer les clés, donc Stacki n’en enregistrera aucune.', + 'cmsConnections.sanityDetected': 'Ce site utilise Sanity. Connectez-le pour modifier son contenu dans Stacki.', // review 'cmsConnections.signIn.browser': 'Connectez-vous sur la page de Sanity dans votre navigateur, puis revenez ici. Stacki crée une clé Editor pour le projet de ce site et ne conserve que cette clé.', 'cmsConnections.signIn.cancelled': 'Connexion annulée.', diff --git a/shared/properties/i18n/messages/ptBR/cmsConnections.ts b/shared/properties/i18n/messages/ptBR/cmsConnections.ts index c515f39da..f98a93623 100644 --- a/shared/properties/i18n/messages/ptBR/cmsConnections.ts +++ b/shared/properties/i18n/messages/ptBR/cmsConnections.ts @@ -45,6 +45,7 @@ export const messages = { 'cmsConnections.input.secret.printable': 'Uma chave de API são caracteres imprimíveis em uma única linha.', 'cmsConnections.kind.custom': 'CMS personalizado', 'cmsConnections.list.noEncryption': 'Este computador não consegue criptografar chaves, então o Stacki não salvará nenhuma.', + 'cmsConnections.sanityDetected': 'Este site usa o Sanity. Conecte-o para editar o conteúdo dele no Stacki.', // review 'cmsConnections.signIn.browser': 'Entre na página do Sanity no seu navegador e volte aqui. O Stacki cria uma chave de Editor para o projeto deste site e guarda somente essa chave.', 'cmsConnections.signIn.cancelled': 'Login cancelado.', diff --git a/src/features/cmsConnections/CmsConnections.tsx b/src/features/cmsConnections/CmsConnections.tsx index 5f3fec680..4f164ddbb 100644 --- a/src/features/cmsConnections/CmsConnections.tsx +++ b/src/features/cmsConnections/CmsConnections.tsx @@ -15,6 +15,8 @@ import { CmsKeyForm, type CmsKeyKind } from './CmsKeyForm'; import { PayloadStatus } from './PayloadStatus'; import { EmDashButton } from './EmDashButton'; import { SkeletonRows } from '../../ui/Skeleton'; +import { readText } from '../../ipc/bridge'; +import { hasDependency } from '../../lib/packageManifest'; type Dialog = { readonly kind: 'sanity-login' } | { readonly kind: 'key'; readonly cms: CmsKeyKind }; @@ -23,6 +25,7 @@ export function CmsConnections({ projectPath }: { readonly projectPath: string } const [list, setList] = useState(undefined); const [error, setError] = useState(undefined); const [dialog, setDialog] = useState(undefined); + const sanitySite = useSanitySite(projectPath); const refresh = useCallback(() => { listCmsConnections(projectPath).then(setList, (reason: unknown) => setError(String(reason))); }, [projectPath]); @@ -39,6 +42,9 @@ export function CmsConnections({ projectPath }: { readonly projectPath: string } {error && } {list?.encryption === 'unavailable' &&

{translate('cmsConnections.list.noEncryption')}

} {list === undefined ? : } + {list !== undefined && sanitySite && !list.connections.some((connection) => connection.kind === 'sanity') && ( +

{translate('cmsConnections.sanityDetected')}

+ )} {dialog?.kind === 'sanity-login' && } {dialog?.kind === 'key' && } @@ -46,6 +52,23 @@ export function CmsConnections({ projectPath }: { readonly projectPath: string } ); } +// Whether the site's package.json lists Sanity (the Astro integration, or an embedded Studio), so the +// panel can say so while no Sanity connection exists. An unreadable package.json reads as no. +function useSanitySite(projectPath: string): boolean { + const [sanitySite, setSanitySite] = useState(false); + useEffect(() => { + let current = true; + readText(projectPath, 'package.json').then( + (text) => current && setSanitySite(hasDependency(text, '@sanity/astro') || hasDependency(text, 'sanity')), + () => current && setSanitySite(false), + ); + return () => { + current = false; + }; + }, [projectPath]); + return sanitySite; +} + function ConnectionRows(props: { readonly projectPath: string; readonly connections: readonly CmsConnection[]; diff --git a/src/features/props/loopCatalog.ts b/src/features/props/loopCatalog.ts index 0c2fb8aeb..2fc078b24 100644 --- a/src/features/props/loopCatalog.ts +++ b/src/features/props/loopCatalog.ts @@ -5,7 +5,6 @@ // it shows there, with the same field names and choices. import { assert } from '../../../shared/core/assert'; -import { toRecord } from '../../../shared/core/record'; import { ASTRO_CONTENT_ID } from '../../../shared/properties/astroContent'; import type { RemoteSchemaField, RemoteType } from '../../../shared/properties/cmsRemoteSchema'; import { ITEM_FIELD_LIMITS, type ItemFieldDeclaration, type ItemFieldKind } from '../../editor/itemFields'; @@ -13,6 +12,7 @@ import type { LoopField, LoopFieldKind, LoopSource, LoopSourceKind } from '../.. import { isFieldPath, ITEM_FIELD } from '../../editor/loopQuery'; import { listCmsConnections, remoteReferenceOptions } from '../../ipc/cmsConnectionsBridge'; import { readText } from '../../ipc/bridge'; +import { hasDependency } from '../../lib/packageManifest'; import { remoteCollections, remoteTemplate } from '../../ipc/remoteSource'; export const LOOP_CATALOG_LIMITS = { @@ -22,7 +22,6 @@ export const LOOP_CATALOG_LIMITS = { projectsCachedMax: 8, /** How deep an object's fields are listed: `location.lat`, `hero.cta.label`. */ nestingDepthMax: 4, - packageCharsMax: 1_000_000, } as const; export interface CatalogCollection { @@ -140,23 +139,6 @@ async function sanityClientIn(projectPath: string): Promise<'available' | 'unava return hasDependency(text, '@sanity/astro') ? 'available' : 'unavailable'; } -/** Whether a package.json's text lists `name` as a dependency of either kind. */ -export function hasDependency(text: string, name: string): boolean { - if (text.length === 0 || text.length > LOOP_CATALOG_LIMITS.packageCharsMax) { - return false; - } - let manifest: unknown; - try { - manifest = JSON.parse(text); - } catch { - return false; - } - const record = toRecord(manifest); - const dependencies = toRecord(record?.['dependencies']); - const development = toRecord(record?.['devDependencies']); - return typeof dependencies?.[name] === 'string' || typeof development?.[name] === 'string'; -} - /** A collection's fields, as the filter and sort menus offer them. */ export async function loadFields(projectPath: string, catalog: LoopCatalog, source: LoopSource): Promise { const connectionId = connectionOf(catalog, source.kind); diff --git a/src/lib/packageManifest.ts b/src/lib/packageManifest.ts new file mode 100644 index 000000000..a8397f0ff --- /dev/null +++ b/src/lib/packageManifest.ts @@ -0,0 +1,25 @@ +// A site's package.json, read as text the renderer already has: which packages +// it depends on. Used where a feature only makes sense with a package installed +// (a Sanity loop needs @sanity/astro) or hints at one (a Sanity site, in CMS +// connections). Malformed or oversized text depends on nothing. +import { toRecord } from '../../shared/core/record'; + +/** The longest package.json text read. */ +export const PACKAGE_MANIFEST_CHARS_MAX = 1_000_000; + +/** Whether a package.json's text lists `name` as a dependency of either kind. */ +export function hasDependency(text: string, name: string): boolean { + if (text.length === 0 || text.length > PACKAGE_MANIFEST_CHARS_MAX) { + return false; + } + let manifest: unknown; + try { + manifest = JSON.parse(text); + } catch { + return false; + } + const record = toRecord(manifest); + const dependencies = toRecord(record?.['dependencies']); + const development = toRecord(record?.['devDependencies']); + return typeof dependencies?.[name] === 'string' || typeof development?.[name] === 'string'; +} diff --git a/studio/scripts/shared-source.json b/studio/scripts/shared-source.json index 4f8f2de11..7e35af610 100644 --- a/studio/scripts/shared-source.json +++ b/studio/scripts/shared-source.json @@ -1537,6 +1537,7 @@ "src/lib/i18n/translateRich.ts", "src/lib/i18n/useTranslate.ts", "src/lib/insertRank.ts", + "src/lib/packageManifest.ts", "src/lib/pageName.ts", "src/lib/projectPath.ts", "src/lib/roleAccess.ts", diff --git a/test/renderer/cms/sanityHint.test.js b/test/renderer/cms/sanityHint.test.js new file mode 100644 index 000000000..900b9ba00 --- /dev/null +++ b/test/renderer/cms/sanityHint.test.js @@ -0,0 +1,93 @@ +// Goal: Settings > CMS connections says "This site uses Sanity" when the site's package.json lists +// @sanity/astro or sanity and no Sanity connection exists yet, and says nothing otherwise: once a +// Sanity connection is saved, for a site without Sanity, or when package.json cannot be read. +// Method: bundle the real CmsConnections with esbuild, mount it in jsdom over a fake preload bridge +// whose package.json text and connection list each test sets, and read the panel's sentences. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const fs = require('node:fs'); +const esbuild = require('esbuild'); +const { JSDOM } = require('jsdom'); +const { repoPath } = require('../../helpers/sources.js'); +const { installPopupDOM } = require('../../helpers/popupDom.js'); + +const output = repoPath('node_modules/.stacki-test/sanity-hint.cjs'); +fs.mkdirSync(path.dirname(output), { recursive: true }); +const bundled = esbuild.build({ + stdin: { contents: `export { CmsConnections } from './src/features/cmsConnections/CmsConnections';`, resolveDir: repoPath('.'), loader: 'ts' }, + outfile: output, + bundle: true, + platform: 'node', + format: 'cjs', + jsx: 'automatic', + loader: { '.css': 'empty', '.svg': 'empty' }, + external: ['react', 'react-dom', 'react/jsx-runtime'], + logLevel: 'silent', +}); + +const dom = new JSDOM('
', { url: 'http://localhost/', pretendToBeVisual: true }); +installPopupDOM(dom.window); +global.window = dom.window; +for (const name of ['document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent']) { + global[name] = dom.window[name]; +} +global.IS_REACT_ACT_ENVIRONMENT = true; + +const SANITY_CONNECTION = { id: 'c1', kind: 'sanity', label: 'Kade', projectId: 'abc123', dataset: 'production' }; +let manifest = async () => ({ text: '{}' }); +let connections = []; +const reads = []; +window.avb = { + readSourceText: async (input) => { + reads.push(input.rel); + return manifest(); + }, + cmsConnections: async () => ({ encryption: 'available', connections }), + emDashProject: async () => ({ kind: 'absent' }), +}; + +const React = require('react'); +const { act } = React; +const { createRoot } = require('react-dom/client'); +let component; +let root; +test.before(async () => { + await bundled; + component = require(output); +}); +test.afterEach(async () => { + await act(async () => root.unmount()); +}); + +const HINT = 'This site uses Sanity. Connect it to edit its content in Stacki.'; +async function panelText() { + reads.length = 0; + document.body.innerHTML = '
'; + root = createRoot(document.getElementById('root')); + await act(async () => root.render(React.createElement(component.CmsConnections, { projectPath: '/site' }))); + await act(async () => new Promise((resolve) => setTimeout(resolve, 0))); + assert.deepEqual(reads, ['package.json'], 'the panel reads package.json once'); + return [...document.querySelectorAll('.cms-connections p')].map((paragraph) => paragraph.textContent); +} + +test('a site that depends on @sanity/astro or sanity, with no Sanity connection, is told it uses Sanity', async () => { + connections = []; + manifest = async () => ({ text: '{"dependencies":{"@sanity/astro":"^3"}}' }); + assert.ok((await panelText()).includes(HINT)); + manifest = async () => ({ text: '{"devDependencies":{"sanity":"^6"}}' }); + assert.ok((await panelText()).includes(HINT)); +}); + +test('no hint once a Sanity connection exists, for a site without Sanity, or when package.json cannot be read', async () => { + manifest = async () => ({ text: '{"dependencies":{"@sanity/astro":"^3"}}' }); + connections = [SANITY_CONNECTION]; + assert.equal((await panelText()).includes(HINT), false); + connections = []; + manifest = async () => ({ text: '{"dependencies":{"astro":"^5"}}' }); + assert.equal((await panelText()).includes(HINT), false); + manifest = async () => { + throw new Error('no package.json'); + }; + assert.equal((await panelText()).includes(HINT), false); +}); diff --git a/test/renderer/lib/packageManifest.test.js b/test/renderer/lib/packageManifest.test.js new file mode 100644 index 000000000..7dade6641 --- /dev/null +++ b/test/renderer/lib/packageManifest.test.js @@ -0,0 +1,26 @@ +// Goal: src/lib/packageManifest.ts says a package.json depends on a package only when it lists +// it, as a dependency or a dev dependency, and says no for anything it cannot read. +// Method: package.json texts with the package in each list, in neither, under another name, and +// texts that are not a manifest: malformed, empty, a version that is not a string, oversized. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const load = require('../../helpers/rendererModule'); +const { hasDependency, PACKAGE_MANIFEST_CHARS_MAX } = load('src/lib/packageManifest.ts'); + +test('a package listed as a dependency or a dev dependency is found', () => { + assert.equal(hasDependency('{"dependencies":{"@sanity/astro":"^3"}}', '@sanity/astro'), true); + assert.equal(hasDependency('{"devDependencies":{"@sanity/astro":"^3"}}', '@sanity/astro'), true); + assert.equal(hasDependency('{"dependencies":{"sanity":"^6","@sanity/client":"^8"}}', 'sanity'), true); +}); + +test('a package not listed, or a manifest that cannot be read, depends on nothing', () => { + assert.equal(hasDependency('{"dependencies":{}}', '@sanity/astro'), false); + assert.equal(hasDependency('{"dependencies":{"@sanity/client":"^8"}}', 'sanity'), false); + assert.equal(hasDependency('{"peerDependencies":{"sanity":"^6"}}', 'sanity'), false); + assert.equal(hasDependency('{"dependencies":{"sanity":6}}', 'sanity'), false); + assert.equal(hasDependency('not json', '@sanity/astro'), false); + assert.equal(hasDependency('', '@sanity/astro'), false); + assert.equal(hasDependency('[]', '@sanity/astro'), false); + const oversized = `{"dependencies":{"sanity":"^6"},"x":"${'a'.repeat(PACKAGE_MANIFEST_CHARS_MAX)}"}`; + assert.equal(hasDependency(oversized, 'sanity'), false); +}); diff --git a/test/renderer/props/loopSettings.test.js b/test/renderer/props/loopSettings.test.js index e6f57701c..b4dbebc97 100644 --- a/test/renderer/props/loopSettings.test.js +++ b/test/renderer/props/loopSettings.test.js @@ -96,10 +96,6 @@ assert.equal( ); assert.equal(catalog.titled('case-studies'), 'Case Studies'); assert.equal(catalog.titled('sermonSpeaker'), 'Sermon Speaker'); -assert.equal(catalog.hasDependency('{"dependencies":{"@sanity/astro":"^3"}}', '@sanity/astro'), true); -assert.equal(catalog.hasDependency('{"devDependencies":{"@sanity/astro":"^3"}}', '@sanity/astro'), true); -assert.equal(catalog.hasDependency('{"dependencies":{}}', '@sanity/astro'), false); -assert.equal(catalog.hasDependency('not json', '@sanity/astro'), false); // Dragging a picked item: the drop slot is measured before the item is taken out. const { moved } = load('src/features/props/LoopItems.tsx');