Skip to content

Commit

Permalink
feat: add hasSanityPackageInImportMap (#6832)
Browse files Browse the repository at this point in the history
* feat: add hasSanityPackageInImportMap

* test: add tests for hasSanityPackageInImportMap

* return early if sanity found in import map

Co-authored-by: Espen Hovlandsdal <espen@hovlandsdal.com>

* chore: update internal tag to include comment

---------

Co-authored-by: Espen Hovlandsdal <espen@hovlandsdal.com>
  • Loading branch information
cngonzalez and rexxars authored Jun 6, 2024
1 parent 74f8080 commit 8ea7d8f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {describe, expect, it, jest} from '@jest/globals'

import {hasSanityPackageInImportMap} from './hasSanityPackageInImportMap'

const querySelectorAllSpy = jest.spyOn(document, 'querySelectorAll')

describe('hasSanityPackageInImportMap', () => {
it('should return false if document is undefined', () => {
const documentSpy = jest.spyOn(global, 'document', 'get')
documentSpy.mockReturnValueOnce(undefined as any)
expect(hasSanityPackageInImportMap()).toBe(false)
})
it('should return false if no script with type importmap is found', () => {
querySelectorAllSpy.mockReturnValue([] as any)
expect(hasSanityPackageInImportMap()).toBe(false)
})

it('should return true if script with type importmap is found and contains sanity', () => {
querySelectorAllSpy.mockReturnValue([
{textContent: JSON.stringify({imports: {sanity: 'path/to/sanity'}})},
] as any)
expect(hasSanityPackageInImportMap()).toBe(true)
})

it('should return false if script with type importmap is found but does not contain sanity', () => {
querySelectorAllSpy.mockReturnValue([
{textContent: JSON.stringify({imports: {other: 'path/to/other'}})},
] as any)
expect(hasSanityPackageInImportMap()).toBe(false)
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Returns whether or not there is a `sanity` entry in an import map in the current document,
* which usually means that this studio is "auto updating".
* @internal
*/
export const hasSanityPackageInImportMap = () => {
if (typeof document === 'undefined' || !('querySelectorAll' in document)) {
return false
}
const importMapEntries = document.querySelectorAll('script[type="importmap"]')
return Array.from(importMapEntries).some((entry) => {
if (!entry.textContent) return false
const importMap = JSON.parse(entry.textContent)
const imports = importMap.imports || {}
return 'sanity' in imports
})
}

0 comments on commit 8ea7d8f

Please sign in to comment.