@sanity/sdk 3.0.0-rc.2 → 3.1.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/dist/_exports/_internal.d.ts +25 -3
- package/dist/_exports/_internal.d.ts.map +1 -1
- package/dist/_exports/_internal.js +127 -9
- package/dist/_exports/_internal.js.map +1 -1
- package/dist/_exports/agent.d.ts +1 -1
- package/dist/_exports/agent.js +1 -1
- package/dist/_exports/comlink.d.ts +1 -1
- package/dist/_exports/comlink.js +2 -3
- package/dist/_exports/comlink.js.map +1 -1
- package/dist/{authStore-DKFX8fn7.d.ts → authStore-C-OEkGaM.d.ts} +30 -44
- package/dist/authStore-C-OEkGaM.d.ts.map +1 -0
- package/dist/{authStore-CtE9bLHW.js → clientStore-gUALQ0qW.js} +269 -11
- package/dist/{authStore-CtE9bLHW.js.map → clientStore-gUALQ0qW.js.map} +1 -1
- package/dist/{createSanityInstance-DUI1bGIg.d.ts → createSanityInstance-DCePpBYW.d.ts} +2 -2
- package/dist/{createSanityInstance-DUI1bGIg.d.ts.map → createSanityInstance-DCePpBYW.d.ts.map} +1 -1
- package/dist/{getNodeState-CR3__B2D.js → getNodeState-E0hjqFOo.js} +2 -3
- package/dist/{getNodeState-CR3__B2D.js.map → getNodeState-E0hjqFOo.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +168 -176
- package/dist/index.js.map +1 -1
- package/dist/{createStateSourceAction-BOKtqFNm.js → object-BwynGPRZ.js} +87 -3
- package/dist/object-BwynGPRZ.js.map +1 -0
- package/dist/{queryStore-DPf9sN3V.js → version-C90rNWaX.js} +48 -16
- package/dist/version-C90rNWaX.js.map +1 -0
- package/package.json +4 -4
- package/src/_exports/_internal.ts +1 -0
- package/src/_exports/index.ts +7 -4
- package/src/access/checkPermissions.test.ts +1 -1
- package/src/access/checkPermissions.ts +1 -1
- package/src/applications/applications.test.ts +4 -4
- package/src/applications/applications.ts +4 -4
- package/src/auth/handleAuthCallback.test.ts +2 -2
- package/src/auth/handleAuthCallback.ts +1 -1
- package/src/auth/logout.test.ts +1 -1
- package/src/auth/logout.ts +1 -1
- package/src/auth/refreshStampedToken.ts +1 -1
- package/src/auth/studioModeAuth.test.ts +1 -1
- package/src/auth/studioModeAuth.ts +1 -1
- package/src/auth/subscribeToStateAndFetchCurrentUser.test.ts +2 -2
- package/src/auth/subscribeToStateAndFetchCurrentUser.ts +1 -1
- package/src/comments/addonDatasetStore.test.ts +2 -2
- package/src/comments/addonDatasetStore.ts +2 -2
- package/src/comments/commentActions.ts +6 -5
- package/src/comments/commentsStore.ts +4 -4
- package/src/datasets/datasets.test.ts +44 -9
- package/src/datasets/datasets.ts +24 -23
- package/src/document/applyDocumentActions.ts +2 -6
- package/src/document/documentConstants.ts +9 -0
- package/src/document/documentStore.concurrency.test.ts +2 -1
- package/src/document/documentStore.test.ts +87 -17
- package/src/document/documentStore.ts +5 -5
- package/src/document/permissions.ts +2 -1
- package/src/document/processActions.test.ts +2 -1
- package/src/document/processMutations.ts +3 -2
- package/src/document/reducers.test.ts +224 -0
- package/src/document/reducers.ts +110 -27
- package/src/favorites/favorites.test.ts +64 -24
- package/src/favorites/favorites.ts +73 -22
- package/src/installations/installations.test.ts +2 -2
- package/src/installations/installations.ts +2 -2
- package/src/organization/organization.test.ts +2 -2
- package/src/organization/organization.ts +1 -1
- package/src/organizations/organizations.test.ts +2 -2
- package/src/organizations/organizations.ts +1 -1
- package/src/presence/presenceStore.test.ts +15 -22
- package/src/presence/presenceStore.ts +3 -2
- package/src/project/project.test.ts +3 -3
- package/src/project/project.ts +1 -1
- package/src/projection/getProjectionState.test.ts +6 -4
- package/src/projection/getProjectionState.ts +2 -2
- package/src/projects/projects.test.ts +2 -2
- package/src/projects/projects.ts +1 -1
- package/src/query/queryStore.ts +3 -3
- package/src/store/createSanityInstance.test.ts +1 -1
- package/src/store/createSanityInstance.ts +4 -4
- package/src/store/createStoreInstance.test.ts +0 -5
- package/src/store/fetcherStore.test.ts +23 -1
- package/src/store/fetcherStore.ts +3 -3
- package/src/telemetry/telemetryManager.test.ts +1 -1
- package/src/telemetry/telemetryManager.ts +2 -2
- package/src/users/usersStore.test.ts +1 -1
- package/src/users/usersStore.ts +5 -5
- package/src/utils/ids.test.ts +40 -15
- package/src/utils/ids.ts +47 -2
- package/dist/authStore-DKFX8fn7.d.ts.map +0 -1
- package/dist/clientStore-BtE2-q2i.js +0 -90
- package/dist/clientStore-BtE2-q2i.js.map +0 -1
- package/dist/createStateSourceAction-BOKtqFNm.js.map +0 -1
- package/dist/getEnv-D5RGkQLu.js +0 -8
- package/dist/getEnv-D5RGkQLu.js.map +0 -1
- package/dist/logger-DAtJb5RQ.js +0 -173
- package/dist/logger-DAtJb5RQ.js.map +0 -1
- package/dist/object-CxXlSVg7.js +0 -83
- package/dist/object-CxXlSVg7.js.map +0 -1
- package/dist/queryStore-DPf9sN3V.js.map +0 -1
- package/dist/rolldown-runtime-vyAXikos.js +0 -9
- package/dist/telemetryManager-Dq_qCkeI.js +0 -127
- package/dist/telemetryManager-Dq_qCkeI.js.map +0 -1
- package/dist/version-BChjsi4u.js +0 -9
- package/dist/version-BChjsi4u.js.map +0 -1
- package/src/utils/createFetcherStore.test.ts +0 -171
- package/src/utils/createFetcherStore.ts +0 -284
package/src/users/usersStore.ts
CHANGED
|
@@ -30,7 +30,7 @@ import {bindActionGlobally} from '../store/createActionBinder'
|
|
|
30
30
|
import {createStateSourceAction, type SelectorContext} from '../store/createStateSourceAction'
|
|
31
31
|
import {type StoreState} from '../store/createStoreState'
|
|
32
32
|
import {defineStore, type StoreContext} from '../store/defineStore'
|
|
33
|
-
import {
|
|
33
|
+
import {randomId} from '../utils/ids'
|
|
34
34
|
import {setCleanupTimeout} from '../utils/setCleanupTimeout'
|
|
35
35
|
import {
|
|
36
36
|
addSubscription,
|
|
@@ -130,7 +130,7 @@ const listenForLoadMoreAndFetch = ({state, instance}: StoreContext<UsersStoreSta
|
|
|
130
130
|
return client.observable
|
|
131
131
|
.request<PatchedSanityUserFromClient>({
|
|
132
132
|
method: 'GET',
|
|
133
|
-
|
|
133
|
+
url: `/users/${userId}`,
|
|
134
134
|
tag: 'users.get',
|
|
135
135
|
})
|
|
136
136
|
.pipe(
|
|
@@ -184,7 +184,7 @@ const listenForLoadMoreAndFetch = ({state, instance}: StoreContext<UsersStoreSta
|
|
|
184
184
|
return client.observable
|
|
185
185
|
.request<SanityUser | SanityUserResponse>({
|
|
186
186
|
method: 'GET',
|
|
187
|
-
|
|
187
|
+
url: `access/${resourceType}/${resourceId}/users/${userId}`,
|
|
188
188
|
tag: 'users.get',
|
|
189
189
|
})
|
|
190
190
|
.pipe(
|
|
@@ -253,7 +253,7 @@ const listenForLoadMoreAndFetch = ({state, instance}: StoreContext<UsersStoreSta
|
|
|
253
253
|
switchMap(([[resource, client], cursor]) =>
|
|
254
254
|
client.observable.request<SanityUserResponse>({
|
|
255
255
|
method: 'GET',
|
|
256
|
-
|
|
256
|
+
url: `access/${resource.type}/${resource.id}/users`,
|
|
257
257
|
tag: 'users.list',
|
|
258
258
|
query: cursor
|
|
259
259
|
? {nextCursor: cursor, limit: batchSize.toString()}
|
|
@@ -310,7 +310,7 @@ export const getUsersState = bindActionGlobally(
|
|
|
310
310
|
},
|
|
311
311
|
),
|
|
312
312
|
onSubscribe: ({instance, state}, options?: GetUsersOptions) => {
|
|
313
|
-
const subscriptionId =
|
|
313
|
+
const subscriptionId = randomId(16)
|
|
314
314
|
const key = getUsersKey(instance, options)
|
|
315
315
|
state.set('addSubscription', addSubscription(subscriptionId, key))
|
|
316
316
|
return () => {
|
package/src/utils/ids.test.ts
CHANGED
|
@@ -1,26 +1,51 @@
|
|
|
1
|
-
import {describe, expect, it} from 'vitest'
|
|
1
|
+
import {afterEach, describe, expect, it, vi} from 'vitest'
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import {randomId, randomUuid} from './ids'
|
|
4
4
|
|
|
5
|
-
describe('
|
|
6
|
-
it('should generate
|
|
7
|
-
expect(
|
|
5
|
+
describe('randomId', () => {
|
|
6
|
+
it('should generate an 8-character base62 id by default', () => {
|
|
7
|
+
expect(randomId()).toMatch(/^[a-zA-Z0-9]{8}$/)
|
|
8
8
|
})
|
|
9
9
|
|
|
10
|
-
it('should generate
|
|
11
|
-
expect(
|
|
10
|
+
it('should generate an id of the given length', () => {
|
|
11
|
+
expect(randomId(16)).toMatch(/^[a-zA-Z0-9]{16}$/)
|
|
12
12
|
})
|
|
13
13
|
|
|
14
14
|
it('should generate different ids on each call', () => {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
expect(randomId()).not.toBe(randomId())
|
|
16
|
+
})
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
describe('randomUuid', () => {
|
|
20
|
+
const uuidV4Pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
|
|
21
|
+
|
|
22
|
+
afterEach(() => {
|
|
23
|
+
vi.unstubAllGlobals()
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('should generate a v4 UUID', () => {
|
|
27
|
+
expect(randomUuid()).toMatch(uuidV4Pattern)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('should use crypto.randomUUID when available', () => {
|
|
31
|
+
vi.stubGlobal('crypto', {randomUUID: () => 'native-uuid'})
|
|
32
|
+
expect(randomUuid()).toBe('native-uuid')
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('should generate a v4 UUID when crypto.randomUUID is unavailable (insecure contexts)', () => {
|
|
36
|
+
const originalCrypto = globalThis.crypto
|
|
37
|
+
vi.stubGlobal('crypto', {
|
|
38
|
+
getRandomValues: (array: Uint8Array<ArrayBuffer>) => originalCrypto.getRandomValues(array),
|
|
39
|
+
})
|
|
40
|
+
expect(randomUuid()).toMatch(uuidV4Pattern)
|
|
18
41
|
})
|
|
19
42
|
|
|
20
|
-
it('should generate
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}
|
|
43
|
+
it('should generate unique ids when crypto.randomUUID is unavailable', () => {
|
|
44
|
+
const originalCrypto = globalThis.crypto
|
|
45
|
+
vi.stubGlobal('crypto', {
|
|
46
|
+
getRandomValues: (array: Uint8Array<ArrayBuffer>) => originalCrypto.getRandomValues(array),
|
|
47
|
+
})
|
|
48
|
+
const ids = new Set(Array.from({length: 100}, () => randomUuid()))
|
|
49
|
+
expect(ids.size).toBe(100)
|
|
25
50
|
})
|
|
26
51
|
})
|
package/src/utils/ids.ts
CHANGED
|
@@ -1,3 +1,48 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
const ID_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Generates a random ID of the given length from the alphabet `[a-zA-Z0-9]`, the same shape
|
|
5
|
+
* `@sanity/client` and Sanity Studio use for short IDs such as release IDs.
|
|
6
|
+
*
|
|
7
|
+
* Ported from `@sanity/client`'s `generateReleaseId`, which uses rejection sampling to keep
|
|
8
|
+
* the output unbiased. Uses `crypto.getRandomValues`, which unlike `crypto.randomUUID` is
|
|
9
|
+
* also available on insecure origins (plain http).
|
|
10
|
+
*
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
export function randomId(length: number = 8): string {
|
|
14
|
+
let id = ''
|
|
15
|
+
while (id.length < length) {
|
|
16
|
+
const bytes = crypto.getRandomValues(new Uint8Array(length - id.length))
|
|
17
|
+
for (const byte of bytes) {
|
|
18
|
+
const index = byte & 63
|
|
19
|
+
if (index < ID_ALPHABET.length) id += ID_ALPHABET.charAt(index)
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return id
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Generates a random v4 UUID.
|
|
27
|
+
*
|
|
28
|
+
* Prefers the native `crypto.randomUUID`, which is only available in secure contexts
|
|
29
|
+
* (https, localhost). Falls back to deriving the UUID from `crypto.getRandomValues`,
|
|
30
|
+
* which has no such restriction, so ID generation also works when an app is served over
|
|
31
|
+
* plain http, e.g. when testing from a phone on a local network.
|
|
32
|
+
*
|
|
33
|
+
* @internal
|
|
34
|
+
*/
|
|
35
|
+
export function randomUuid(): string {
|
|
36
|
+
// eslint-disable-next-line no-restricted-properties -- this is the sanctioned wrapper around crypto.randomUUID
|
|
37
|
+
if (typeof crypto.randomUUID === 'function') return crypto.randomUUID()
|
|
38
|
+
|
|
39
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16))
|
|
40
|
+
const hex = Array.from(bytes, (byte, index) => {
|
|
41
|
+
// Set the version (4) and variant (RFC 4122) bits
|
|
42
|
+
if (index === 6) byte = (byte & 0x0f) | 0x40
|
|
43
|
+
if (index === 8) byte = (byte & 0x3f) | 0x80
|
|
44
|
+
return byte.toString(16).padStart(2, '0')
|
|
45
|
+
}).join('')
|
|
46
|
+
|
|
47
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
|
3
48
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"authStore-DKFX8fn7.d.ts","names":[],"sources":["../src/store/createStoreState.ts","../src/store/defineStore.ts","../src/store/createActionBinder.ts","../src/store/createStateSourceAction.ts","../src/store/fetcherStore.ts","../src/access/checkPermissions.ts","../src/utils/includeShape.ts","../src/applications/applications.ts","../src/auth/authStateType.ts","../src/project/organizationVerification.ts","../src/auth/getOrganizationVerificationState.ts","../src/auth/handleAuthCallback.ts","../src/auth/logout.ts","../src/client/clientStore.ts","../src/comments/types.ts","../src/comments/commentActions.ts","../src/comments/commentsStore.ts","../src/config/handles.ts","../src/utils/logger.ts","../src/config/loggingConfig.ts","../src/datasets/datasets.ts","../src/document/actions.ts","../src/document/patchOperations.ts","../src/document/processMutations.ts","../src/document/permissions.ts","../src/document/sharedListener.ts","../src/document/documentStore.ts","../src/document/reducers.ts","../src/document/events.ts","../src/document/applyDocumentActions.ts","../src/document/processActions/releaseUtil.ts","../src/favorites/favorites.ts","../src/installations/installations.ts","../src/organization/organization.ts","../src/organizations/organizations.ts","../src/users/types.ts","../src/presence/types.ts","../src/presence/presenceStore.ts","../src/projection/types.ts","../src/preview/types.ts","../src/project/project.ts","../src/projection/getProjectionState.ts","../src/projection/resolveProjection.ts","../src/projects/projects.ts","../src/query/queryStore.ts","../src/releases/releasesStore.ts","../src/releases/getPerspectiveState.ts","../src/users/usersStore.ts","../src/utils/createFetcherStore.ts","../src/utils/getCorsErrorProjectId.ts","../src/utils/isImportError.ts","../src/version.ts","../src/_exports/index.ts","../src/auth/authStore.ts"],"mappings":";;;;;;;;;;;;;UAOiB,WAAW;;;;;;;EAO1B,WAAW;;;;;;;;;;EAWX,MAAM,cAAc,cAAc,QAAQ,YAAY,GAAG,WAAW,QAAQ;;;;;;;;;EAU5E,YAAY,WAAW;;;;;UC7BR,aAAa,QAAQ;;;;;;;EAOpC,UAAU;;;;;;;EAQV,OAAO,WAAW;;;;EAKlB,KAAK;;;;;KCAK,YAAY,QAAQ,2BAA2B,SAAS,mBAClE,SAAS,aAAa,QAAQ,UAC3B,QAAQ,YACR;;;;KAKO,iBAAiB,SAAS,2BAA2B,YAC/D,UAAU,mBACP,QAAQ,YACR;;;;;;;;;;;;UCpBY,YAAY;;;;;;EAM3B,YAAY;;;;;;;;EASZ,kBAAkB;;;;;;;;;;EAWlB,YAAY,WAAW;;;;;;;;;;;;;;;;;;;;;;;UAwBR,gBAAgB;;;;EAI/B,OAAO;;;;EAKP,UAAU;;;;;;KAOA,SAAS,QAAQ,2BAA2B,YACtD,SAAS,gBAAgB,YACtB,QAAQ,YACR;;;;;;;;;;;;;;UCzDY;EACf;;EAEA;;;;;;;;;;;;;;KAeU,gBAAgB;;EAGtB;EACA;EACA;EACA;EACA;;;EAIA;EACA,MAAM;;EAE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AW,2BAA2B;EAC9C,QAAQ;EACR,UAAU;EACV;EACA,OAAO;EACP;EACA;EACA;;;;;;UAOe,kBAAkB,2BAA2B;EAC5D,kBAAiB,4BAA4B,WAAW,SAAS;EACjE;;;;;;UAOe,aAAa,2BAA2B;EACvD,UAAU,iBACR,kBAAkB,SAAS,QAC3B,SACA,YAAY;EAEd,cAAc,iBAAiB,kBAAkB,SAAS,QAAQ,SAAS,QAAQ;;;;;;;;iBC1ErE,sBAAsB,OAAO;;;;;;;;;;;;;;;;;;;;;;iBCa7B,cAAc;;;;;cCdjB;;;;KCFD,kBAAgB;;;;;;KCqBhB,YAAY,oBAAoB,qBAAqB,qBAAqB;;;;;KAM1E;EACV,MAAM,cAAc;EACpB;EACA,aAAa;EACb;;;;;;KAOU;EAAsB,MAAM,cAAc;EAAY;;;;;;KAMtD;EAAsB,MAAM,cAAc;EAAY;;;;;;KAMtD;EAAkB,MAAM,cAAc;EAAO;;;;;;;UAOxC;EACf;EACA;EACA;;;;;;KAOU;;;;UAOK;EACf,WAAW;EACX,YAAY;EACZ;IACE;IACA,gBAAgB,QAAQ,iBAAiB;IACzC,iBAAiB;IACjB;IACA,aAAa;IACb;IACA;IACA;IACA;IACA,YAAY;;EAEd,mBAAmB;;;;;cAuIR,qBAAmB,iBAAA,oBAAA,YAAA;;;;cAUnB,eAAa,iBAAA,oBAAA;;;;cAkBb,kBAAgB,iBAAA,oBAAA;;;;cAQhB,cAAY,iBAAA,oBAAA,YAAA;;;;cAQZ,4BAA0B,iBAAA,oBAAA;;;;;cAS1B,uBAAqB,iBAAA,oBAAA;;;;;;cAcrB,cAAY,iBAAA,iBAAA"}
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-vyAXikos.js";
|
|
2
|
-
import { a as defineStore, c as isDatasetResource, i as bindActionGlobally, l as isMediaLibraryResource, s as isCanvasResource, t as createStateSourceAction } from "./createStateSourceAction-BOKtqFNm.js";
|
|
3
|
-
import { T as getStagingApiHost, l as getTokenState, r as getAuthMethodState } from "./authStore-CtE9bLHW.js";
|
|
4
|
-
import { i as pickProperties } from "./object-CxXlSVg7.js";
|
|
5
|
-
import { createClient } from "@sanity/client";
|
|
6
|
-
var clientStore_exports = /* @__PURE__ */ __exportAll({
|
|
7
|
-
getClient: () => getClient,
|
|
8
|
-
getClientState: () => getClientState
|
|
9
|
-
});
|
|
10
|
-
const allowedKeys = Object.keys({
|
|
11
|
-
apiHost: null,
|
|
12
|
-
useCdn: null,
|
|
13
|
-
token: null,
|
|
14
|
-
perspective: null,
|
|
15
|
-
proxy: null,
|
|
16
|
-
withCredentials: null,
|
|
17
|
-
timeout: null,
|
|
18
|
-
maxRetries: null,
|
|
19
|
-
dataset: null,
|
|
20
|
-
projectId: null,
|
|
21
|
-
scope: null,
|
|
22
|
-
apiVersion: null,
|
|
23
|
-
requestTagPrefix: null,
|
|
24
|
-
useProjectHostname: null,
|
|
25
|
-
resource: null
|
|
26
|
-
}), DEFAULT_CLIENT_CONFIG = {
|
|
27
|
-
apiVersion: "2024-11-12",
|
|
28
|
-
useCdn: !1,
|
|
29
|
-
ignoreBrowserTokenWarning: !0,
|
|
30
|
-
allowReconfigure: !1,
|
|
31
|
-
requestTagPrefix: "sanity.sdk"
|
|
32
|
-
}, clientStore = defineStore({
|
|
33
|
-
name: "clientStore",
|
|
34
|
-
getInitialState: (instance) => ({
|
|
35
|
-
clients: {},
|
|
36
|
-
token: getTokenState(instance).getCurrent()
|
|
37
|
-
}),
|
|
38
|
-
initialize(context) {
|
|
39
|
-
let subscription = listenToToken(context), authMethodSubscription = listenToAuthMethod(context);
|
|
40
|
-
return () => {
|
|
41
|
-
subscription.unsubscribe(), authMethodSubscription.unsubscribe();
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
}), listenToToken = ({ instance, state }) => getTokenState(instance).observable.subscribe((token) => {
|
|
45
|
-
state.set("setTokenAndResetClients", {
|
|
46
|
-
token,
|
|
47
|
-
clients: {}
|
|
48
|
-
});
|
|
49
|
-
}), listenToAuthMethod = ({ instance, state }) => getAuthMethodState(instance).observable.subscribe((authMethod) => {
|
|
50
|
-
state.set("setAuthMethod", { authMethod });
|
|
51
|
-
}), getClientConfigKey = (options) => JSON.stringify(pickProperties(options, allowedKeys)), getClient = bindActionGlobally(clientStore, ({ state, instance }, options) => {
|
|
52
|
-
if (!options || typeof options != "object") throw Error("getClient() requires a configuration object with at least an \"apiVersion\" property. Example: getClient(instance, { apiVersion: \"2024-11-12\" })");
|
|
53
|
-
let disallowedKeys = Object.keys(options).filter((key) => !allowedKeys.includes(key));
|
|
54
|
-
if (disallowedKeys.length > 0) {
|
|
55
|
-
let listFormatter = new Intl.ListFormat("en", {
|
|
56
|
-
style: "long",
|
|
57
|
-
type: "conjunction"
|
|
58
|
-
});
|
|
59
|
-
throw Error(`The client options provided contains unsupported properties: ${listFormatter.format(disallowedKeys)}. Allowed keys are: ${listFormatter.format(allowedKeys)}.`);
|
|
60
|
-
}
|
|
61
|
-
let tokenFromState = state.get().token, { clients, authMethod } = state.get(), projectId = options.projectId ?? instance.config.projectId, dataset = options.dataset ?? instance.config.dataset, resource;
|
|
62
|
-
options.resource && (isMediaLibraryResource(options.resource) ? resource = {
|
|
63
|
-
type: "media-library",
|
|
64
|
-
id: options.resource.mediaLibraryId
|
|
65
|
-
} : isCanvasResource(options.resource) ? resource = {
|
|
66
|
-
type: "canvas",
|
|
67
|
-
id: options.resource.canvasId
|
|
68
|
-
} : isDatasetResource(options.resource) && (projectId = options.resource.projectId, dataset = options.resource.dataset));
|
|
69
|
-
let apiHost = options.apiHost ?? instance.config.auth?.apiHost ?? getStagingApiHost(), effectiveOptions = {
|
|
70
|
-
...DEFAULT_CLIENT_CONFIG,
|
|
71
|
-
...(options.scope === "global" || !projectId || resource) && { useProjectHostname: !1 },
|
|
72
|
-
token: authMethod === "cookie" ? void 0 : tokenFromState ?? void 0,
|
|
73
|
-
...options,
|
|
74
|
-
...projectId && { projectId },
|
|
75
|
-
...dataset && { dataset },
|
|
76
|
-
...resource ? { resource } : { resource: void 0 },
|
|
77
|
-
...apiHost && { apiHost }
|
|
78
|
-
};
|
|
79
|
-
resource && (delete effectiveOptions.projectId, delete effectiveOptions.dataset), effectiveOptions.token === null || effectiveOptions.token === void 0 ? (delete effectiveOptions.token, authMethod === "cookie" && (effectiveOptions.withCredentials = !0)) : delete effectiveOptions.withCredentials;
|
|
80
|
-
let key = getClientConfigKey(effectiveOptions);
|
|
81
|
-
if (clients[key]) return clients[key];
|
|
82
|
-
let client = createClient(effectiveOptions);
|
|
83
|
-
return state.set("addClient", (prev) => ({ clients: {
|
|
84
|
-
...prev.clients,
|
|
85
|
-
[key]: client
|
|
86
|
-
} })), client;
|
|
87
|
-
}), getClientState = bindActionGlobally(clientStore, createStateSourceAction(({ instance }, options) => getClient(instance, options)));
|
|
88
|
-
export { getClient as n, getClientState as r, clientStore_exports as t };
|
|
89
|
-
|
|
90
|
-
//# sourceMappingURL=clientStore-BtE2-q2i.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"clientStore-BtE2-q2i.js","names":[],"sources":["../src/client/clientStore.ts"],"sourcesContent":["import {type ClientConfig, createClient, type SanityClient} from '@sanity/client'\n\nimport {getAuthMethodState, getTokenState} from '../auth/authStore'\nimport {\n type DocumentResource,\n isCanvasResource,\n isDatasetResource,\n isMediaLibraryResource,\n} from '../config/sanityConfig'\nimport {bindActionGlobally} from '../store/createActionBinder'\nimport {createStateSourceAction} from '../store/createStateSourceAction'\nimport {defineStore, type StoreContext} from '../store/defineStore'\nimport {getStagingApiHost} from '../utils/getStagingApiHost'\nimport {pickProperties} from '../utils/object'\n\nconst DEFAULT_API_VERSION = '2024-11-12'\nconst DEFAULT_REQUEST_TAG_PREFIX = 'sanity.sdk'\n\ntype AllowedClientConfigKey =\n | 'useCdn'\n | 'token'\n | 'perspective'\n | 'apiHost'\n | 'proxy'\n | 'withCredentials'\n | 'timeout'\n | 'maxRetries'\n | 'dataset'\n | 'projectId'\n | 'requestTagPrefix'\n | 'useProjectHostname'\n\nconst allowedKeys = Object.keys({\n apiHost: null,\n useCdn: null,\n token: null,\n perspective: null,\n proxy: null,\n withCredentials: null,\n timeout: null,\n maxRetries: null,\n dataset: null,\n projectId: null,\n scope: null,\n apiVersion: null,\n requestTagPrefix: null,\n useProjectHostname: null,\n resource: null,\n} satisfies Record<keyof ClientOptions, null>) as (keyof ClientOptions)[]\n\nconst DEFAULT_CLIENT_CONFIG: ClientConfig = {\n apiVersion: DEFAULT_API_VERSION,\n useCdn: false,\n ignoreBrowserTokenWarning: true,\n allowReconfigure: false,\n requestTagPrefix: DEFAULT_REQUEST_TAG_PREFIX,\n}\n\n/**\n * States tracked by the client store\n * @public\n */\nexport interface ClientStoreState {\n token: string | null\n clients: {[TKey in string]?: SanityClient}\n authMethod?: 'localstorage' | 'cookie'\n}\n\n/**\n * Options used when retrieving a client instance from the client store.\n *\n * This interface extends the base {@link ClientConfig} and adds:\n *\n * - **apiVersion:** A required string indicating the API version for the client.\n * - **scope:** An optional flag to choose between the project-specific client\n * ('project') and the global client ('global'). When set to `'global'`, the\n * global client is used.\n *\n * These options are utilized by `getClient` and `getClientState` to configure and\n * return appropriate client instances that automatically handle authentication\n * updates and configuration changes.\n *\n * @public\n */\nexport interface ClientOptions extends Pick<ClientConfig, AllowedClientConfigKey> {\n /**\n * An optional flag to choose between the default client (typically project-level)\n * and the global client ('global'). When set to `'global'`, the global client\n * is used.\n */\n scope?: 'default' | 'global'\n /**\n * A required string indicating the API version for the client.\n */\n apiVersion: string\n\n /**\n * @internal\n * The SDK resource to use for the client -- this will get transformed into a ClientConfig resource.\n */\n resource?: DocumentResource\n}\n\nconst clientStore = defineStore<ClientStoreState>({\n name: 'clientStore',\n\n getInitialState: (instance) => ({\n clients: {},\n token: getTokenState(instance).getCurrent(),\n }),\n\n initialize(context) {\n const subscription = listenToToken(context)\n const authMethodSubscription = listenToAuthMethod(context)\n return () => {\n subscription.unsubscribe()\n authMethodSubscription.unsubscribe()\n }\n },\n})\n\n/**\n * Updates the client store state when a token is received.\n * @internal\n */\nconst listenToToken = ({instance, state}: StoreContext<ClientStoreState>) => {\n return getTokenState(instance).observable.subscribe((token) => {\n state.set('setTokenAndResetClients', {token, clients: {}})\n })\n}\n\nconst listenToAuthMethod = ({instance, state}: StoreContext<ClientStoreState>) => {\n return getAuthMethodState(instance).observable.subscribe((authMethod) => {\n state.set('setAuthMethod', {authMethod})\n })\n}\n\ntype ClientInstanceCacheKeyInput = ClientConfig &\n Partial<Pick<ClientOptions, 'scope'>> & {\n apiVersion: string\n }\n\nconst getClientConfigKey = (options: ClientInstanceCacheKeyInput) =>\n JSON.stringify(pickProperties(options, allowedKeys))\n\n/**\n * Retrieves a Sanity client instance configured with the provided options.\n *\n * This function returns a client instance configured for the project or as a\n * global client based on the options provided. It ensures efficient reuse of\n * client instances by returning the same instance for the same options.\n * For automatic handling of authentication token updates, consider using\n * `getClientState`.\n *\n * @public\n */\nexport const getClient = bindActionGlobally(\n clientStore,\n ({state, instance}, options: ClientOptions) => {\n if (!options || typeof options !== 'object') {\n throw new Error(\n 'getClient() requires a configuration object with at least an \"apiVersion\" property. ' +\n 'Example: getClient(instance, { apiVersion: \"2024-11-12\" })',\n )\n }\n\n // Check for disallowed keys\n const providedKeys = Object.keys(options) as (keyof ClientOptions)[]\n const disallowedKeys = providedKeys.filter((key) => !allowedKeys.includes(key))\n\n if (disallowedKeys.length > 0) {\n const listFormatter = new Intl.ListFormat('en', {style: 'long', type: 'conjunction'})\n throw new Error(\n `The client options provided contains unsupported properties: ${listFormatter.format(disallowedKeys)}. ` +\n `Allowed keys are: ${listFormatter.format(allowedKeys)}.`,\n )\n }\n\n const tokenFromState = state.get().token\n const {clients, authMethod} = state.get()\n let projectId = options.projectId ?? instance.config.projectId\n let dataset = options.dataset ?? instance.config.dataset\n\n let resource: ClientConfig['resource'] | undefined\n\n if (options.resource) {\n if (isMediaLibraryResource(options.resource)) {\n resource = {type: 'media-library', id: options.resource.mediaLibraryId}\n } else if (isCanvasResource(options.resource)) {\n resource = {type: 'canvas', id: options.resource.canvasId}\n } else if (isDatasetResource(options.resource)) {\n // use project-based routes for datasets to avoid existing CORS and Studio auth cookie issues\n projectId = options.resource.projectId\n dataset = options.resource.dataset\n }\n }\n\n const apiHost = options.apiHost ?? instance.config.auth?.apiHost ?? getStagingApiHost()\n\n const effectiveOptions: ClientConfig & {apiVersion: string} = {\n ...DEFAULT_CLIENT_CONFIG,\n ...((options.scope === 'global' || !projectId || resource) && {useProjectHostname: false}),\n token: authMethod === 'cookie' ? undefined : (tokenFromState ?? undefined),\n ...options,\n ...(projectId && {projectId}),\n ...(dataset && {dataset}),\n ...(resource ? {resource} : {resource: undefined}),\n ...(apiHost && {apiHost}),\n }\n\n // When a resource is provided, don't use projectId/dataset - the client should be \"projectless\"\n // The client code itself will ignore the non-resource config, so we do this to prevent confusing the user.\n // (ref: https://github.com/sanity-io/client/blob/5c23f81f5ab93a53f5b22b39845c867988508d84/src/data/dataMethods.ts#L691)\n if (resource) {\n delete effectiveOptions.projectId\n delete effectiveOptions.dataset\n }\n\n if (effectiveOptions.token === null || typeof effectiveOptions.token === 'undefined') {\n delete effectiveOptions.token\n if (authMethod === 'cookie') {\n effectiveOptions.withCredentials = true\n }\n } else {\n delete effectiveOptions.withCredentials\n }\n\n const key = getClientConfigKey(effectiveOptions)\n\n if (clients[key]) return clients[key]\n\n const client = createClient(effectiveOptions)\n state.set('addClient', (prev) => ({clients: {...prev.clients, [key]: client}}))\n\n return client\n },\n)\n\n/**\n * Returns a state source for the Sanity client instance.\n *\n * This function provides a subscribable state source that emits updated client\n * instances whenever relevant configurations change (such as authentication tokens).\n * Use this when you need to react to client configuration changes in your application.\n *\n * @public\n */\nexport const getClientState = bindActionGlobally(\n clientStore,\n createStateSourceAction(({instance}, options: ClientOptions) => getClient(instance, options)),\n)\n"],"mappings":";;;;;;;;;AAeA,MAiBM,cAAc,OAAO,KAAK;CAC9B,SAA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AG,KAAK;GAAU,MAAM;CAAM,EAAC,EAAE,GAEvE;AACT,CACF,GAWa,iBAAiB,mBAC5B,aACA,yBAAyB,EAAC,YAAW,YAA2B,UAAU,UAAU,OAAO,CAAC,CAC9F"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createStateSourceAction-BOKtqFNm.js","names":[],"sources":["../src/config/sanityConfig.ts","../src/releases/utils/isReleasePerspective.ts","../src/store/createStoreState.ts","../src/store/defineStore.ts","../src/store/createStoreInstance.ts","../src/store/createActionBinder.ts","../src/store/createStateSourceAction.ts"],"sourcesContent":["import {type ClientPerspective, type StackablePerspective} from '@sanity/client'\n\nimport {type AuthConfig} from './authConfig'\n\n/**\n * A minimal Observable-compatible interface for subscribing to token changes.\n * Any object with a `subscribe` method that follows this contract will work,\n * including RxJS Observables. This avoids coupling the SDK to a specific\n * reactive library.\n *\n * @public\n */\nexport interface TokenSource {\n /** Subscribe to token emissions. Emits `null` when logged out. */\n subscribe(observer: {next: (token: string | null) => void}): {unsubscribe(): void}\n}\n\n/**\n * Studio-specific configuration for the SDK.\n * When present, the SDK operates in studio mode and derives auth from the\n * provided token source instead of discovering tokens independently.\n *\n * @public\n */\nexport interface StudioConfig {\n /**\n * Whether the Studio has already determined the user is authenticated.\n * When `true` and the token source emits `null`, the SDK infers\n * cookie-based auth is in use rather than transitioning to logged-out.\n */\n authenticated?: boolean\n /** Reactive auth token source from the Studio's auth store. */\n auth?: {\n /**\n * A reactive token source. The SDK subscribes and stays in sync — the\n * Studio is the single authority for auth and handles token refresh.\n *\n * Optional because older Studios may not expose it. When absent, the\n * SDK falls back to localStorage/cookie discovery.\n */\n token?: TokenSource\n }\n}\n\n/**\n * Represents the minimal configuration required to identify a Sanity project.\n * @public\n */\nexport interface ProjectHandle<TProjectId extends string = string> {\n projectId?: TProjectId\n}\n\n/**\n * @public\n */\nexport type ReleasePerspective = {\n releaseName: string\n excludedPerspectives?: StackablePerspective[]\n}\n\n/**\n * @public\n */\nexport interface PerspectiveHandle {\n perspective?: ClientPerspective | ReleasePerspective\n}\n\n/**\n * @public\n */\nexport interface DatasetHandle<TDataset extends string = string, TProjectId extends string = string>\n extends ProjectHandle<TProjectId>, PerspectiveHandle {\n dataset?: TDataset\n /**\n * @beta\n * Explicit resource to use. On an individual operation this overrides any default;\n * on a `SanityConfig` it becomes the instance's default resource. Unlike\n * `projectId`/`dataset`, this can also be a media library or canvas resource.\n */\n resource?: DocumentResource\n}\n\n/**\n * Identifies a specific document type within a Sanity dataset and project.\n * Includes `projectId`, `dataset`, and `documentType`.\n * Optionally includes a `documentId` and `liveEdit` flag.\n * @public\n */\nexport interface DocumentTypeHandle<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends DatasetHandle<TDataset, TProjectId> {\n documentId?: string\n documentType: TDocumentType\n /**\n * Indicates whether this document uses liveEdit mode.\n * When `true`, the document does not use the draft/published model and edits are applied directly to the document.\n * @see https://www.sanity.io/docs/content-lake/drafts#ca0663a8f002\n */\n liveEdit?: boolean\n}\n\n/**\n * Uniquely identifies a specific document within a Sanity dataset and project.\n * Includes `projectId`, `dataset`, `documentType`, and the required `documentId`.\n * Commonly used by document-related hooks and components to reference a document without fetching its full content initially.\n * @public\n */\nexport interface DocumentHandle<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> {\n documentId: string\n}\n\n/**\n * Identifies a release within a Sanity dataset and project. `releaseId` is the\n * `name` parameter on the release document (e.g. `{name: 'r41035a4'}`).\n * The underlying release document ID is `_.releases.<releaseId>`.\n * It's also the `id` parameter sent to the Actions API.\n * (This type doesn't need to have ProjectId / Dataset generics since it's always the same shape)\n * @beta\n */\nexport interface ReleaseHandle extends DatasetHandle {\n releaseId: string\n}\n\n/**\n * Represents the complete configuration for a Sanity SDK instance\n * @public\n */\nexport interface SanityConfig extends DatasetHandle, PerspectiveHandle {\n /**\n * Authentication configuration for the instance\n */\n auth?: AuthConfig\n /**\n * Studio configuration provided by a Sanity Studio workspace.\n * When present, the SDK operates in studio mode and derives auth from the\n * workspace's reactive token source — no manual configuration needed.\n *\n * @remarks Typically set automatically by `SanityApp` when it detects an\n * `SDKStudioContext` provider. Can also be set explicitly for programmatic use.\n */\n studio?: StudioConfig\n}\n\n/**\n * A document resource can be used for querying.\n * This will soon be the default way to identify where you are querying from.\n *\n * @beta\n */\nexport type DocumentResource = DatasetResource | MediaLibraryResource | CanvasResource\n\n/**\n * @beta\n */\nexport type DatasetResource = {projectId: string; dataset: string}\n\n/**\n * @beta\n */\nexport type MediaLibraryResource = {mediaLibraryId: string}\n\n/**\n * @beta\n */\nexport type CanvasResource = {canvasId: string}\n\n/**\n * @beta\n */\nexport function isDatasetResource(resource: DocumentResource): resource is DatasetResource {\n return 'projectId' in resource && 'dataset' in resource\n}\n\n/**\n * @beta\n */\nexport function isMediaLibraryResource(\n resource: DocumentResource,\n): resource is MediaLibraryResource {\n return 'mediaLibraryId' in resource\n}\n\n/**\n * @beta\n */\nexport function isCanvasResource(resource: DocumentResource): resource is CanvasResource {\n return 'canvasId' in resource\n}\n","import {type PerspectiveHandle, type ReleasePerspective} from '../../config/sanityConfig'\n\nexport const isReleasePerspective = (\n perspective: PerspectiveHandle['perspective'],\n): perspective is ReleasePerspective => {\n return typeof perspective === 'object' && perspective !== null && 'releaseName' in perspective\n}\n","import {Observable} from 'rxjs'\nimport {devtools, type DevtoolsOptions} from 'zustand/middleware'\nimport {createStore} from 'zustand/vanilla'\n\n/**\n * Represents a reactive store state container with multiple access patterns\n */\nexport interface StoreState<TState> {\n /**\n * Gets the current state value\n *\n * @remarks\n * This is a direct synchronous accessor that doesn't trigger subscriptions\n */\n get: () => TState\n\n /**\n * Updates the store state\n * @param name - Action name for devtools tracking\n * @param updatedState - New state value or updater function\n *\n * @remarks\n * When providing a partial object, previous top-level keys not included in\n * the update will be preserved.\n */\n set: (name: string, updatedState: Partial<TState> | ((s: TState) => Partial<TState>)) => void\n\n /**\n * Observable stream of state changes\n * @remarks\n * - Emits immediately with current state on subscription\n * - Shares underlying subscription between observers\n * - Only emits when state reference changes\n * - Completes when store is disposed\n */\n observable: Observable<TState>\n}\n\n/**\n * Creates a reactive store state container with multiple access patterns\n * @param initialState - Initial state value for the store\n * @param devToolsOptions - Configuration for Zustand devtools integration\n * @returns StoreState instance with get/set/observable interface\n *\n * @example\n * ```typescript\n * // Create a simple counter store\n * const counterStore = createStoreState({ count: 0 });\n *\n * // Update state\n * counterStore.set('increment', { count: 1 });\n *\n * // Observe changes\n * counterStore.observable.subscribe(console.log);\n * ```\n *\n * @remarks\n * Uses Zustand for state management under the hood with RxJS for observable interface.\n * Designed to work with both imperative and reactive programming patterns.\n */\nexport function createStoreState<TState>(\n initialState: TState,\n devToolsOptions?: DevtoolsOptions,\n): StoreState<TState> {\n // Create underlying Zustand store with devtools integration\n const store = createStore<TState>()(devtools(() => initialState, devToolsOptions))\n\n return {\n get: store.getState,\n set: (actionKey, updatedState) => {\n const currentState = store.getState()\n const nextState =\n typeof updatedState === 'function' ? updatedState(currentState) : updatedState\n\n // Optimization: Skip update if state reference remains the same\n if (currentState !== nextState) {\n store.setState(nextState, false, actionKey)\n }\n },\n observable: new Observable((observer) => {\n // Emit current state immediately on subscription\n const emit = () => observer.next(store.getState())\n emit()\n\n // Subscribe to Zustand store changes\n const unsubscribe = store.subscribe(emit)\n\n // Cleanup when observable unsubscribed\n return () => unsubscribe()\n }),\n }\n}\n","import {type SanityInstance} from './createSanityInstance'\nimport {type StoreState} from './createStoreState'\n\n/**\n * Context object provided to store initialization functions\n */\nexport interface StoreContext<TState, TKey = unknown> {\n /**\n * Sanity instance associated with this store\n *\n * @remarks\n * Provides access to the Sanity configuration and instance lifecycle methods\n */\n instance: SanityInstance\n\n /**\n * Reactive store state management utilities\n *\n * @remarks\n * Contains methods for getting/setting state and observing changes\n */\n state: StoreState<TState>\n\n /**\n * The key used to instantiate the store.\n */\n key: TKey\n}\n\n/**\n * Defines the structure and behavior of a store\n *\n * @remarks\n * Stores are isolated state containers that can be associated with Sanity instances.\n * Each store definition creates a separate state instance per composite key.\n */\nexport interface StoreDefinition<TState, TKey = unknown> {\n /**\n * Unique name for the store\n *\n * @remarks\n * Used for debugging, devtools integration, and store identification\n */\n name: string\n\n /**\n * Creates the initial state for the store\n * @param instance - Sanity instance the store is being created for\n * @returns Initial state value\n *\n * @remarks\n * Called when a new store instance is created. Can use Sanity instance\n * configuration to determine initial state.\n */\n getInitialState: (instance: SanityInstance, key: TKey) => TState\n\n /**\n * Optional initialization function\n * @param context - Store context with state and instance access\n * @returns Optional cleanup function for store disposal\n *\n * @remarks\n * Use this for:\n * - Setting up event listeners\n * - Initial data fetching\n * - Connecting external services\n *\n * Return a cleanup function to:\n * - Remove event listeners\n * - Cancel pending operations\n * - Dispose external connections\n */\n initialize?: (context: StoreContext<TState, TKey>) => (() => void) | undefined\n}\n\n/**\n * Typescript helper function for creating store definitions\n *\n * @param storeDefinition - Configuration object defining the store\n * @returns The finalized store definition\n */\nexport function defineStore<TState, TKey = unknown>(\n storeDefinition: StoreDefinition<TState, TKey>,\n): StoreDefinition<TState, TKey> {\n return storeDefinition\n}\n","import {getEnv} from '../utils/getEnv'\nimport {type SanityInstance} from './createSanityInstance'\nimport {createStoreState, type StoreState} from './createStoreState'\nimport {type StoreDefinition} from './defineStore'\n\n/**\n * Represents a running instance of a store with its own state and lifecycle\n *\n * @remarks\n * Each StoreInstance is tied to a specific SanityInstance, manages its own state,\n * and can be independently disposed when no longer needed.\n */\nexport interface StoreInstance<TState> {\n /**\n * Access to the reactive state container for this store instance\n */\n state: StoreState<TState>\n\n /**\n * Checks if this store instance has been disposed\n * @returns Boolean indicating disposed state\n */\n isDisposed: () => void\n\n /**\n * Cleans up this store instance and runs any initialization cleanup functions\n * @remarks Triggers the cleanup function returned from the initialize method\n */\n dispose: () => void\n}\n\n/**\n * Creates a new instance of a store from a store definition\n *\n * @param instance - The Sanity instance this store will be associated with\n * @param storeDefinition - The store definition containing initial state and initialization logic\n * @returns A store instance with state management and lifecycle methods\n *\n * @remarks\n * The store instance maintains its own state that is scoped to the given Sanity instance.\n * If the store definition includes an initialize function, it will be called during\n * instance creation, and its cleanup function will be called during disposal.\n *\n * @example\n * ```ts\n * const counterStore = defineStore({\n * name: 'Counter',\n * getInitialState: () => ({ count: 0 }),\n * initialize: ({state}) => {\n * console.log('Counter store initialized')\n * return () => console.log('Counter store disposed')\n * }\n * })\n *\n * const instance = createStoreInstance(sanityInstance, counterStore)\n * // Later when done with the store:\n * instance.dispose()\n * ```\n */\nexport function createStoreInstance<TState, TKey extends {name: string}>(\n instance: SanityInstance,\n key: TKey,\n {name, getInitialState, initialize}: StoreDefinition<TState, TKey>,\n): StoreInstance<TState> {\n const state = createStoreState(getInitialState(instance, key), {\n enabled: !!getEnv('DEV'),\n name: `${name}-${key.name}`,\n })\n const dispose = initialize?.({state, instance, key})\n const disposed = {current: false}\n\n return {\n state,\n dispose: () => {\n if (disposed.current) return\n disposed.current = true\n dispose?.()\n },\n isDisposed: () => disposed.current,\n }\n}\n","import {type ClientPerspective} from '@sanity/client'\n\nimport {\n type DatasetHandle,\n type DocumentResource,\n isCanvasResource,\n isDatasetResource,\n isMediaLibraryResource,\n type ReleasePerspective,\n} from '../config/sanityConfig'\nimport {isReleasePerspective} from '../releases/utils/isReleasePerspective'\nimport {type SanityInstance} from './createSanityInstance'\nimport {createStoreInstance, type StoreInstance} from './createStoreInstance'\nimport {type StoreState} from './createStoreState'\nimport {type StoreContext, type StoreDefinition} from './defineStore'\n\nexport interface BoundResourceKey {\n name: string\n resource: DocumentResource\n}\nexport interface BoundPerspectiveKey extends BoundResourceKey {\n perspective: ClientPerspective | ReleasePerspective\n}\n/**\n * Defines a store action that operates on a specific state type\n */\nexport type StoreAction<TState, TParams extends unknown[], TReturn, TKey = unknown> = (\n context: StoreContext<TState, TKey>,\n ...params: TParams\n) => TReturn\n\n/**\n * Represents a store action that has been bound to a specific store instance\n */\nexport type BoundStoreAction<_TState, TParams extends unknown[], TReturn> = (\n instance: SanityInstance,\n ...params: TParams\n) => TReturn\n\n/**\n * Creates an action binder function that uses the provided key function\n * to determine how store instances are shared between Sanity instances\n *\n * @param keyFn - Function that generates a key from a Sanity config\n * @returns A function that binds store actions to Sanity instances\n *\n * @remarks\n * Action binders determine how store instances are shared across multiple\n * Sanity instances. The key function determines which instances share state.\n *\n * @example\n * ```ts\n * // Create a custom binder that uses a tenant ID for isolation\n * const bindActionByTenant = createActionBinder(config => config.tenantId || 'default')\n *\n * // Use the custom binder with a store definition\n * const getTenantUsers = bindActionByTenant(\n * userStore,\n * ({state}) => state.get().users\n * )\n * ```\n */\nexport function createActionBinder<\n TKey extends {name: string},\n TKeyParams extends unknown[] = unknown[],\n>(keyFn: (instance: SanityInstance, ...params: TKeyParams) => TKey) {\n const instanceRegistry = new Map<string, Set<string>>()\n const storeRegistry = new Map<string, StoreInstance<unknown>>()\n\n /**\n * Binds a store action to a store definition\n *\n * @param storeDefinition - The store definition\n * @param action - The action to bind\n * @returns A function that executes the action with a Sanity instance\n */\n return function bindAction<TState, TParams extends TKeyParams, TReturn>(\n storeDefinition: StoreDefinition<TState, TKey>,\n action: StoreAction<TState, TParams, TReturn, TKey>,\n ): BoundStoreAction<TState, TParams, TReturn> {\n return function boundAction(instance: SanityInstance, ...params: TParams) {\n const key = keyFn(instance, ...params)\n const compositeKey = storeDefinition.name + (key.name ? `:${key.name}` : '')\n\n // Get or create instance set for this composite key\n let instances = instanceRegistry.get(compositeKey)\n if (!instances) {\n instances = new Set<string>()\n instanceRegistry.set(compositeKey, instances)\n }\n\n // Register instance for disposal tracking\n if (!instances.has(instance.instanceId)) {\n instances.add(instance.instanceId)\n instance.onDispose(() => {\n instances.delete(instance.instanceId)\n\n // Clean up when last instance is disposed\n if (instances.size === 0) {\n storeRegistry.get(compositeKey)?.dispose()\n storeRegistry.delete(compositeKey)\n instanceRegistry.delete(compositeKey)\n }\n })\n }\n\n // Get or create store instance\n let storeInstance = storeRegistry.get(compositeKey)\n if (!storeInstance) {\n storeInstance = createStoreInstance(instance, key, storeDefinition)\n storeRegistry.set(compositeKey, storeInstance)\n }\n\n // Execute action with store context\n return action({instance, state: storeInstance.state as StoreState<TState>, key}, ...params)\n }\n }\n}\n\nconst createResourceKey = (\n instance: SanityInstance,\n resource?: DocumentResource,\n): BoundResourceKey => {\n let name: string | undefined\n let resourceForKey: DocumentResource | undefined\n // A per-call resource wins; otherwise use the instance's default resource.\n const effectiveResource = resource ?? instance.config.resource\n if (effectiveResource) {\n resourceForKey = effectiveResource\n if (isDatasetResource(effectiveResource)) {\n name = `${effectiveResource.projectId}.${effectiveResource.dataset}`\n } else if (isMediaLibraryResource(effectiveResource)) {\n name = `media-library:${effectiveResource.mediaLibraryId}`\n } else if (isCanvasResource(effectiveResource)) {\n name = `canvas:${effectiveResource.canvasId}`\n } else {\n throw new Error(`Received invalid resource: ${JSON.stringify(effectiveResource)}`)\n }\n return {name, resource: resourceForKey}\n }\n\n // `projectId`/`dataset` on the config are shorthand for a dataset resource.\n const {projectId, dataset} = instance.config\n if (!projectId || !dataset) {\n throw new Error('This API requires a project ID and dataset configured.')\n }\n return {name: `${projectId}.${dataset}`, resource: {projectId, dataset}}\n}\n\n/**\n * Binds an action to a store that's scoped to a specific document resource.\n **/\nexport const bindActionByResource = createActionBinder<\n BoundResourceKey,\n // `resource` is optional because it falls back to the instance config in\n // `createResourceKey` — see the note there on why that fallback still exists.\n [{resource?: DocumentResource}, ...unknown[]]\n>((instance, {resource}) => {\n return createResourceKey(instance, resource)\n})\n\n/**\n * Binds an action to a store that's scoped to a specific document resource and perspective.\n *\n * @remarks\n * This creates actions that operate on state isolated to a specific document resource and perspective.\n * Different document resources and perspectives will have separate states.\n *\n * This is mostly useful for stores that do batch fetching operations, since the query store\n * can isolate single queries by perspective.\n *\n * @throws Error if resource or perspective is missing from the Sanity instance config\n *\n * @example\n * ```ts\n * // Define a store\n * const documentStore = defineStore<DocumentState>({\n * name: 'Document',\n * getInitialState: () => ({ documents: {} }),\n * // ...\n * })\n *\n * // Create resource-and-perspective-specific actions\n * export const fetchDocuments = bindActionByResourceAndPerspective(\n * documentStore,\n * ({instance, state}, documentId) => {\n * // This state is isolated to the specific document resource and perspective\n * // ...fetch logic...\n * }\n * )\n *\n * // Usage\n * fetchDocument(sanityInstance, 'doc123')\n * ```\n */\nexport const bindActionByResourceAndPerspective = createActionBinder<\n BoundPerspectiveKey,\n [DatasetHandle, ...unknown[]]\n>((instance, options): BoundPerspectiveKey => {\n const {resource, perspective} = options\n // Same trade-off as the resource fallback in `createResourceKey`: configured once on the\n // instance rather than passed to every call. Kept for the same reason.\n const utilizedPerspective = perspective ?? instance.config.perspective ?? 'drafts'\n let perspectiveKey: string\n if (isReleasePerspective(utilizedPerspective)) {\n perspectiveKey = utilizedPerspective.releaseName\n } else if (typeof utilizedPerspective === 'string') {\n perspectiveKey = utilizedPerspective\n } else {\n // \"StackablePerspective\", shouldn't be a common case, but just in case\n perspectiveKey = JSON.stringify(utilizedPerspective)\n }\n const sourceKey = createResourceKey(instance, resource)\n\n return {\n name: `${sourceKey.name}:${perspectiveKey}`,\n resource: sourceKey.resource,\n perspective: utilizedPerspective,\n }\n})\n\n/**\n * Binds an action to a global store that's shared across all Sanity instances\n *\n * @remarks\n * This creates actions that operate on state shared globally across all Sanity instances.\n * Use this for features like authentication where the state should be the same\n * regardless of which project or dataset is being used.\n *\n * @example\n * ```ts\n * // Define a store\n * const authStore = defineStore<AuthState>({\n * name: 'Auth',\n * getInitialState: () => ({\n * user: null,\n * isAuthenticated: false\n * }),\n * // ...\n * })\n *\n * // Create global actions\n * export const getCurrentUser = bindActionGlobally(\n * authStore,\n * ({state}) => state.get().user\n * )\n *\n * export const login = bindActionGlobally(\n * authStore,\n * ({state, instance}, credentials) => {\n * // Login logic that affects global state\n * // ...\n * }\n * )\n *\n * // Usage with any instance\n * getCurrentUser(sanityInstance)\n * ```\n */\nexport const bindActionGlobally = createActionBinder((..._rest) => ({name: 'global'}))\n","import {defer, distinctUntilChanged, finalize, map, Observable, shareReplay, skip} from 'rxjs'\n\nimport {type StoreAction} from './createActionBinder'\nimport {type SanityInstance} from './createSanityInstance'\nimport {type StoreContext} from './defineStore'\n\n/**\n * Represents a reactive state source that provides synchronized access to store data\n *\n * @remarks\n * Designed to work with React's useSyncExternalStore hook. Provides three ways to access data:\n * 1. `getCurrent()` for synchronous current value access\n * 2. `subscribe()` for imperative change notifications\n * 3. `observable` for reactive stream access\n *\n * @public\n */\nexport interface StateSource<T> {\n /**\n * Subscribes to state changes with optional callback\n * @param onStoreChanged - Called whenever relevant state changes occur\n * @returns Unsubscribe function to clean up the subscription\n */\n subscribe: (onStoreChanged?: () => void) => () => void\n\n /**\n * Gets the current derived state value\n *\n * @remarks\n * Safe to call without subscription. Will always return the latest value\n * based on the current store state and selector parameters.\n */\n getCurrent: () => T\n\n /**\n * Observable stream of state values\n *\n * @remarks\n * Shares a single underlying subscription between all observers. Emits:\n * - Immediately with current value on subscription\n * - On every relevant state change\n * - Errors if selector throws\n */\n observable: Observable<T>\n}\n\n/**\n * Context passed to selectors when deriving state\n *\n * @remarks\n * Provides access to both the current state value and the Sanity instance,\n * allowing selectors to use configuration values when computing derived state.\n * The context is memoized for each state object and instance combination\n * to optimize performance and prevent unnecessary recalculations.\n *\n * @example\n * ```ts\n * // Using both state and instance in a selector (psuedo example)\n * const getUserByProjectId = createStateSourceAction(\n * ({ state, instance }: SelectorContext<UsersState>, options?: ProjectHandle) => {\n * const allUsers = state.users\n * const projectId = options?.projectId ?? instance.config.projectId\n * return allUsers.filter(user => user.projectId === projectId)\n * }\n * )\n * ```\n */\nexport interface SelectorContext<TState> {\n /**\n * The current state object from the store\n */\n state: TState\n\n /**\n * The Sanity instance associated with this state\n */\n instance: SanityInstance\n}\n\n/**\n * Function type for selecting derived state from store state and parameters\n * @public\n */\nexport type Selector<TState, TParams extends unknown[], TReturn> = (\n context: SelectorContext<TState>,\n ...params: TParams\n) => TReturn\n\n/**\n * Configuration options for creating a state source action\n */\ninterface StateSourceOptions<TState, TParams extends unknown[], TReturn, TKey> {\n /**\n * Selector function that derives the desired value from store state\n *\n * @remarks\n * Will be called on every store change. Should be pure function.\n * Thrown errors will propagate to observable subscribers.\n */\n selector: Selector<TState, TParams, TReturn>\n\n /**\n * Optional setup/cleanup handler for subscriptions\n *\n * @param context - Store context containing state and instance\n * @param params - Action parameters provided during invocation\n * @returns Optional cleanup function called when subscription ends\n */\n onSubscribe?: (context: StoreContext<TState, TKey>, ...params: TParams) => void | (() => void)\n\n /**\n * Equality function to prevent unnecessary updates\n */\n isEqual?: (prev: TReturn, curr: TReturn) => boolean\n}\n\n/**\n * Creates a state source action that generates StateSource instances\n *\n * @remarks\n * The returned action can be bound to a store using createActionBinder.\n * When invoked, returns a StateSource that stays synchronized with the store.\n *\n * Key performance features:\n * - Memoizes selector contexts to prevent redundant object creation\n * - Only runs selectors when the underlying state changes\n *\n * For complex data transformations, consider using memoized selectors\n * (like those from Reselect) to prevent expensive recalculations.\n *\n * @example\n * ```ts\n * // Create a simple counter source\n * const getCount = createStateSourceAction(({state}: SelectorContext<CounterState>) => state.count)\n * ```\n *\n * @example\n * ```ts\n * // Create a parameterized source with setup/cleanup\n * const getItem = createStateSourceAction({\n * selector: ({state}, index: number) => state.items[index],\n * onSubscribe: (context, index) => {\n * trackItemSubscription(index)\n * return () => untrackItem(index)\n * }\n * })\n * ```\n *\n * @example\n * ```ts\n * // Binding a state source to a specific store\n * const documentStore = defineStore<DocumentState>({\n * name: 'Documents',\n * getInitialState: () => ({ documents: {} }),\n * // ...\n * })\n *\n * const getDocument = bindActionByResource(\n * documentStore,\n * createStateSourceAction(({state}, documentId: string) => state.documents[documentId])\n * )\n *\n * // Usage\n * const documentSource = getDocument(sanityInstance, 'doc123')\n * const doc = documentSource.getCurrent()\n * const subscription = documentSource.observable.subscribe(updatedDoc => {\n * console.log('Document changed:', updatedDoc)\n * })\n * ```\n */\nexport function createStateSourceAction<TState, TParams extends unknown[], TReturn, TKey = unknown>(\n options: Selector<TState, TParams, TReturn> | StateSourceOptions<TState, TParams, TReturn, TKey>,\n): StoreAction<TState, TParams, StateSource<TReturn>, TKey> {\n const selector = typeof options === 'function' ? options : options.selector\n const subscribeHandler = options && 'onSubscribe' in options ? options.onSubscribe : undefined\n const isEqual = options && 'isEqual' in options ? (options.isEqual ?? Object.is) : Object.is\n const selectorContextCache = new WeakMap<\n object,\n WeakMap<SanityInstance, SelectorContext<TState>>\n >()\n\n /**\n * The state source action implementation\n * @param context - Store context providing access to state and instance\n * @param params - Parameters provided when invoking the bound action\n */\n function stateSourceAction(context: StoreContext<TState, TKey>, ...params: TParams) {\n const {state, instance} = context\n\n const getCurrent = (currentState: TState) => {\n if (typeof currentState !== 'object' || currentState === null) {\n throw new Error(\n `Expected store state to be an object but got \"${typeof currentState}\" instead`,\n )\n }\n\n let instanceCache = selectorContextCache.get(currentState)\n if (!instanceCache) {\n instanceCache = new WeakMap<SanityInstance, SelectorContext<TState>>()\n selectorContextCache.set(currentState, instanceCache)\n }\n let selectorContext = instanceCache.get(instance)\n if (!selectorContext) {\n selectorContext = {state: currentState, instance}\n instanceCache.set(instance, selectorContext)\n }\n return selector(selectorContext, ...params)\n }\n\n // `state.observable` will emit the current value immediately and\n // hence we inherit the same behavior here.\n let values = state.observable.pipe(map(getCurrent), distinctUntilChanged(isEqual))\n\n if (subscribeHandler) {\n values = withSubscribeHook(values, () => subscribeHandler(context, ...params))\n }\n\n // Share but replay the latest value so every subscriber gets an\n // initial synchronous emission, matching `state.observable`. That keeps\n // `skip(1)` in `subscribe()` aligned with \"skip current snapshot\" rather than\n // silently eating the first real update after multicasting.\n const sharedValues = values.pipe(shareReplay({bufferSize: 1, refCount: true}))\n\n const subscribe = (onStoreChanged?: () => void) => {\n const subscription = sharedValues.pipe(skip(1)).subscribe({\n next: () => onStoreChanged?.(),\n // Propagate selector errors to both subscription types\n error: () => onStoreChanged?.(),\n })\n\n return () => {\n subscription.unsubscribe()\n }\n }\n\n return {\n getCurrent: () => getCurrent(state.get()),\n subscribe,\n observable: sharedValues,\n }\n }\n\n return stateSourceAction\n}\n\n/**\n * Creates a new Observable which wraps an existing Observable which will invoke\n * the function when a new subscriber appears.\n */\nfunction withSubscribeHook<T>(obs: Observable<T>, fn: () => void | (() => void)): Observable<T> {\n return defer(() => {\n const cleanup = fn()\n return cleanup ? obs.pipe(finalize(() => cleanup())) : obs\n })\n}\n"],"mappings":";;;;;;;;AA+KA,SAAgB,kBAAkB,UAAyD;CACzF,OAAO,eAAe,YAAY,aAAa;AACjD;;;;AAKA,SAAgB,uBACd,UACkC;CAClC,OAAO,oBAAoB;AAC7B;;;;AAKA,SAAgB,iBAAiB,UAAwD;CACvF,OAAO,cAAc;AACvB;AC/LA,MAAa,wBACX,gBAEO,OAAO,eAAgB,cAAY,eAAwB,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;ACuDrF,SAAgB,iBACd,cACA,iBACoB;CAEpB,IAAM,QAAQ,YAAoB,CAAC,CAAC,eAAe,cAAc,eAAe,CAAC;CAEjF,OAAO;EACL,KAAK,MAAM;EACX,MAAM,WAAW,iBAAiB;GAChC,IAAM,eAAe,MAAM,SAAS,GAC9B,YACJ,OAAO,gBAAiB,aAAa,aAAa,YAAY,IAAI;GAGpE,AAAI,iBAAiB,aACnB,MAAM,SAAS,WAAW,IAAO,SAAS;EAE9C;EACA,YAAY,IAAI,YAAY,aAAa;GAEvC,IAAM,aAAa,SAAS,KAAK,MAAM,SAAS,CAAC;GACjD,KAAK;GAGL,IAAM,cAAc,MAAM,UAAU,IAAI;GAGxC,aAAa,YAAY;EAC3B,CAAC;CACH;AACF;;;;;;;ACVA,SAAgB,YACd,iBAC+B;CAC/B,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1BA,SAAgB,oBACd,UACA,KACA,EAAC,MAAM,iBAAiB,cACD;CACvB,IAAM,QAAQ,iBAAiB,gBAAgB,UAAU,GAAG,G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if (import.meta.env) return import.meta.env[key];
|
|
3
|
-
if (typeof process < "u" && process.env) return process.env[key];
|
|
4
|
-
if (typeof window < "u" && window.ENV) return window.ENV?.[key];
|
|
5
|
-
}
|
|
6
|
-
export { getEnv as t };
|
|
7
|
-
|
|
8
|
-
//# sourceMappingURL=getEnv-D5RGkQLu.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"getEnv-D5RGkQLu.js","names":[],"sources":["../src/utils/getEnv.ts"],"sourcesContent":["// Local type declaration for Remix\ntype WindowWithEnv = Window &\n typeof globalThis & {\n ENV?: Record<string, unknown>\n }\n\ntype KnownEnvVar = 'DEV' | 'PKG_VERSION'\n\nexport function getEnv(key: KnownEnvVar): unknown {\n if (typeof import.meta !== 'undefined' && import.meta.env) {\n // Vite environment variables\n return (import.meta.env as unknown as Record<string, unknown>)[key]\n } else if (typeof process !== 'undefined' && process.env) {\n // Node.js or server-side environment variables\n return process.env[key]\n } else if (typeof window !== 'undefined' && (window as WindowWithEnv).ENV) {\n // Remix-style client-side environment variables\n return (window as WindowWithEnv).ENV?.[key]\n }\n return undefined\n}\n"],"mappings":"AAQA,SAAgB,OAAO,KAA2B;CAChD,IAA0C,YAAY,KAEpD,OAAQ,YAAY,IAA2C;CAC1D,IAAI,OAAO,UAAY,OAAe,QAAQ,KAEnD,OAAO,QAAQ,IAAI;CACd,IAAI,OAAO,SAAW,OAAgB,OAAyB,KAEpE,OAAQ,OAAyB,MAAM;AAG3C"}
|
package/dist/logger-DAtJb5RQ.js
DELETED
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
const LOG_LEVEL_PRIORITY = {
|
|
2
|
-
error: 0,
|
|
3
|
-
warn: 1,
|
|
4
|
-
info: 2,
|
|
5
|
-
debug: 3,
|
|
6
|
-
trace: 4
|
|
7
|
-
}, DEFAULT_CONFIG = {
|
|
8
|
-
level: "warn",
|
|
9
|
-
namespaces: [],
|
|
10
|
-
internal: !1,
|
|
11
|
-
timestamps: !0,
|
|
12
|
-
enableInProduction: !1,
|
|
13
|
-
handler: {
|
|
14
|
-
error: console.error.bind(console),
|
|
15
|
-
warn: console.warn.bind(console),
|
|
16
|
-
info: console.info.bind(console),
|
|
17
|
-
debug: console.debug.bind(console),
|
|
18
|
-
trace: console.debug.bind(console)
|
|
19
|
-
}
|
|
20
|
-
};
|
|
21
|
-
/**
|
|
22
|
-
* Parse DEBUG environment variable for automatic logging configuration
|
|
23
|
-
*
|
|
24
|
-
* Supports patterns similar to Sanity CLI/Studio:
|
|
25
|
-
* - DEBUG=sanity:* (all namespaces, debug level)
|
|
26
|
-
* - DEBUG=sanity:auth,sanity:document (specific namespaces)
|
|
27
|
-
* - DEBUG=sanity:trace:* (all namespaces, trace level)
|
|
28
|
-
* - DEBUG=sanity:*:internal (enable internal logs)
|
|
29
|
-
*
|
|
30
|
-
* @internal
|
|
31
|
-
*/
|
|
32
|
-
function parseDebugEnvVar() {
|
|
33
|
-
if (typeof process > "u" || !process.env?.DEBUG) return null;
|
|
34
|
-
let debug = process.env.DEBUG;
|
|
35
|
-
if (!debug.includes("sanity")) return null;
|
|
36
|
-
let config = {}, levelMatch = debug.match(/sanity:(trace|debug|info|warn|error):/), hasLevelSpecifier = !!levelMatch;
|
|
37
|
-
if (config.level = levelMatch ? levelMatch[1] : "debug", debug === "sanity") config.namespaces = ["*"];
|
|
38
|
-
else if (hasLevelSpecifier && debug.match(/sanity:(trace|debug|info|warn|error):\*/)) config.namespaces = ["*"];
|
|
39
|
-
else if (!hasLevelSpecifier && debug.includes("sanity:*")) config.namespaces = ["*"];
|
|
40
|
-
else {
|
|
41
|
-
let namespaces = debug.split(",").filter((s) => s.includes("sanity:")).map((s) => {
|
|
42
|
-
let cleaned = s.replace(/^sanity:/, "");
|
|
43
|
-
return hasLevelSpecifier && cleaned.match(/^(trace|debug|info|warn|error):/) ? cleaned.split(":").slice(1).join(":") : cleaned.split(":")[0];
|
|
44
|
-
}).filter(Boolean).filter((ns) => ns !== "*");
|
|
45
|
-
namespaces.length > 0 && (config.namespaces = namespaces);
|
|
46
|
-
}
|
|
47
|
-
return debug.includes(":internal") && (config.internal = !0), config;
|
|
48
|
-
}
|
|
49
|
-
const envConfig = parseDebugEnvVar();
|
|
50
|
-
let globalConfig = {
|
|
51
|
-
...DEFAULT_CONFIG,
|
|
52
|
-
...envConfig ?? {}
|
|
53
|
-
};
|
|
54
|
-
/* c8 ignore next 14 */
|
|
55
|
-
envConfig && ([
|
|
56
|
-
"info",
|
|
57
|
-
"debug",
|
|
58
|
-
"trace"
|
|
59
|
-
].includes(globalConfig.level) || globalConfig.level === "warn") && console.info(`[${(/* @__PURE__ */ new Date()).toISOString()}] [INFO] [sdk] Logging auto-configured from DEBUG environment variable`, {
|
|
60
|
-
level: globalConfig.level,
|
|
61
|
-
namespaces: globalConfig.namespaces,
|
|
62
|
-
internal: globalConfig.internal,
|
|
63
|
-
source: "env:DEBUG",
|
|
64
|
-
value: typeof process < "u" ? process.env?.DEBUG : void 0
|
|
65
|
-
});
|
|
66
|
-
/**
|
|
67
|
-
* Configure the global logging system
|
|
68
|
-
* @public
|
|
69
|
-
*/
|
|
70
|
-
function configureLogging(config) {
|
|
71
|
-
globalConfig = {
|
|
72
|
-
...globalConfig,
|
|
73
|
-
...config,
|
|
74
|
-
handler: config.handler ?? globalConfig.handler
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Check if logging is enabled in the current environment
|
|
79
|
-
* @internal
|
|
80
|
-
*/
|
|
81
|
-
function isLoggingEnabled() {
|
|
82
|
-
return typeof process < "u" && process.env?.NODE_ENV === "production" ? globalConfig.enableInProduction : !0;
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Check if a namespace is enabled
|
|
86
|
-
* @internal
|
|
87
|
-
*/
|
|
88
|
-
function isNamespaceEnabled(namespace) {
|
|
89
|
-
return isLoggingEnabled() ? globalConfig.namespaces.includes("*") ? !0 : globalConfig.namespaces.includes(namespace) : !1;
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Check if a log level is enabled
|
|
93
|
-
* @internal
|
|
94
|
-
*/
|
|
95
|
-
function isLevelEnabled(level) {
|
|
96
|
-
return isLoggingEnabled() ? LOG_LEVEL_PRIORITY[level] <= LOG_LEVEL_PRIORITY[globalConfig.level] : !1;
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Format a log message with timestamp, namespace, and instance context
|
|
100
|
-
* @internal
|
|
101
|
-
*/
|
|
102
|
-
function formatMessage(namespace, level, message, context) {
|
|
103
|
-
let parts = [];
|
|
104
|
-
if (globalConfig.timestamps) {
|
|
105
|
-
let timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
106
|
-
parts.push(`[${timestamp}]`);
|
|
107
|
-
}
|
|
108
|
-
parts.push(`[${level.toUpperCase()}]`), parts.push(`[${namespace}]`);
|
|
109
|
-
let instanceContext = context?.instanceContext;
|
|
110
|
-
return instanceContext && (instanceContext.projectId && parts.push(`[project:${instanceContext.projectId}]`), instanceContext.dataset && parts.push(`[dataset:${instanceContext.dataset}]`), instanceContext.instanceId && parts.push(`[instance:${instanceContext.instanceId.slice(0, 8)}]`)), parts.push(message), [parts.join(" "), context];
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Sanitize context for logging (remove sensitive data)
|
|
114
|
-
* @internal
|
|
115
|
-
* @remarks
|
|
116
|
-
* This performs shallow sanitization only - it redacts top-level keys that contain
|
|
117
|
-
* sensitive names (token, password, secret, apiKey, authorization).
|
|
118
|
-
* Nested sensitive data (e.g., `\{auth: \{token: 'secret'\}\}`) will NOT be redacted.
|
|
119
|
-
* If deep sanitization is needed in the future, this can be enhanced to recursively
|
|
120
|
-
* traverse nested objects.
|
|
121
|
-
*/
|
|
122
|
-
function sanitizeContext(context) {
|
|
123
|
-
if (!context || Object.keys(context).length === 0) return;
|
|
124
|
-
let sanitized = { ...context }, sensitiveKeys = [
|
|
125
|
-
"token",
|
|
126
|
-
"password",
|
|
127
|
-
"secret",
|
|
128
|
-
"apiKey",
|
|
129
|
-
"authorization"
|
|
130
|
-
];
|
|
131
|
-
for (let key of Object.keys(sanitized)) sensitiveKeys.some((sensitive) => key.toLowerCase().includes(sensitive)) && (sanitized[key] = "[REDACTED]");
|
|
132
|
-
return sanitized;
|
|
133
|
-
}
|
|
134
|
-
/**
|
|
135
|
-
* Create a logger for a specific namespace
|
|
136
|
-
* @param namespace - A string identifier for the logging domain (e.g., 'auth', 'document')
|
|
137
|
-
* @param baseContext - Optional base context to include in all log messages
|
|
138
|
-
* @remarks
|
|
139
|
-
* If baseContext includes an `instanceContext` property (with projectId, dataset, instanceId),
|
|
140
|
-
* it will be automatically formatted into the log output for easier debugging of
|
|
141
|
-
* multi-instance scenarios.
|
|
142
|
-
* @public
|
|
143
|
-
*/
|
|
144
|
-
function createLogger(namespace, baseContext) {
|
|
145
|
-
let logAtLevel = (level, message, context) => {
|
|
146
|
-
if (!isNamespaceEnabled(namespace) || !isLevelEnabled(level) || context?.internal && !globalConfig.internal) return;
|
|
147
|
-
let [formatted, finalContext] = formatMessage(namespace, level, message, sanitizeContext({
|
|
148
|
-
...baseContext,
|
|
149
|
-
...context
|
|
150
|
-
}));
|
|
151
|
-
globalConfig.handler[level](formatted, finalContext);
|
|
152
|
-
};
|
|
153
|
-
return {
|
|
154
|
-
namespace,
|
|
155
|
-
error: (message, context) => logAtLevel("error", message, context),
|
|
156
|
-
warn: (message, context) => logAtLevel("warn", message, context),
|
|
157
|
-
info: (message, context) => logAtLevel("info", message, context),
|
|
158
|
-
debug: (message, context) => logAtLevel("debug", message, context),
|
|
159
|
-
trace: (message, context) => logAtLevel("trace", message, {
|
|
160
|
-
...context,
|
|
161
|
-
internal: !0
|
|
162
|
-
}),
|
|
163
|
-
isLevelEnabled: (level) => isNamespaceEnabled(namespace) && isLevelEnabled(level),
|
|
164
|
-
child: (childContext) => createLogger(namespace, {
|
|
165
|
-
...baseContext,
|
|
166
|
-
...childContext
|
|
167
|
-
}),
|
|
168
|
-
getInstanceContext: () => baseContext?.instanceContext
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
export { createLogger as n, configureLogging as t };
|
|
172
|
-
|
|
173
|
-
//# sourceMappingURL=logger-DAtJb5RQ.js.map
|