@intijs/adapter-sanity 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +21 -2
- package/dist/index.d.ts +77 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +298 -0
- package/package.json +45 -4
- package/src/index.ts +373 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024–present Inti.js Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @intijs/adapter-sanity
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Read adapter for [Sanity](https://www.sanity.io), part of [Inti](https://github.com/intijs/inti), currently in beta. It converts documents into Inti pages and describes the schema for `inti sync`. **It does not write**, so inline editing is not available.
|
|
4
|
+
|
|
5
|
+
> **Not on npm yet.** The `@intijs` packages will be published there. Until then the `npm install` command below answers 404: install from git as described under [Installation](https://github.com/intijs/inti#-installation) in the repository README.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @intijs/core @intijs/adapter-sanity
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { SanityAdapter } from '@intijs/adapter-sanity';
|
|
13
|
+
|
|
14
|
+
const adapter = new SanityAdapter({
|
|
15
|
+
projectId: import.meta.env.SANITY_PROJECT_ID,
|
|
16
|
+
dataset: 'production'
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const page = adapter.parsePage(document);
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { IntiAdapter } from '@intijs/core/adapters';
|
|
2
|
+
import type { IntiPage, IntiNavigation } from '@intijs/core/types';
|
|
3
|
+
import type { SchemaDefinition } from '@intijs/core/adapters';
|
|
4
|
+
/**
|
|
5
|
+
* Sanity CMS Adapter
|
|
6
|
+
* Integrates Sanity.io with Inti.js
|
|
7
|
+
*/
|
|
8
|
+
export interface SanityConfig {
|
|
9
|
+
projectId: string;
|
|
10
|
+
dataset: string;
|
|
11
|
+
apiVersion?: string;
|
|
12
|
+
useCdn?: boolean;
|
|
13
|
+
token?: string;
|
|
14
|
+
perspective?: 'raw' | 'published' | 'previewDrafts';
|
|
15
|
+
draftMode?: boolean;
|
|
16
|
+
/** Document type of a page. Default `page` */
|
|
17
|
+
pageType?: string;
|
|
18
|
+
fetch?: typeof fetch;
|
|
19
|
+
}
|
|
20
|
+
export declare class SanityAdapter extends IntiAdapter<SanityDocument> {
|
|
21
|
+
protected sanityConfig: SanityConfig;
|
|
22
|
+
protected baseUrl: string;
|
|
23
|
+
private http;
|
|
24
|
+
constructor(config: SanityConfig);
|
|
25
|
+
/** The page document with this `slug.current`, through a GROQ query */
|
|
26
|
+
fetchPageBySlug(slug: string): Promise<IntiPage>;
|
|
27
|
+
parsePage(raw: SanityDocument): IntiPage;
|
|
28
|
+
parseNavigation(raw: SanityNavigationResult): IntiNavigation;
|
|
29
|
+
/**
|
|
30
|
+
* Introspect Sanity schema for type generation
|
|
31
|
+
*/
|
|
32
|
+
introspect(): Promise<SchemaDefinition>;
|
|
33
|
+
private parseBlocks;
|
|
34
|
+
private parseImageBlock;
|
|
35
|
+
private extractBlockData;
|
|
36
|
+
private isReference;
|
|
37
|
+
private getImageUrl;
|
|
38
|
+
private resolveImageUrl;
|
|
39
|
+
private fetchSchema;
|
|
40
|
+
private getMockSchema;
|
|
41
|
+
private parseSanityFields;
|
|
42
|
+
private toPascalCase;
|
|
43
|
+
/**
|
|
44
|
+
* Build GROQ query for fetching pages
|
|
45
|
+
*/
|
|
46
|
+
buildPageQuery(contentType: string, slug?: string): string;
|
|
47
|
+
/**
|
|
48
|
+
* Get query URL for Sanity API
|
|
49
|
+
*/
|
|
50
|
+
getQueryUrl(query: string): string;
|
|
51
|
+
}
|
|
52
|
+
interface SanityDocument {
|
|
53
|
+
result?: any;
|
|
54
|
+
_id?: string;
|
|
55
|
+
_type?: string;
|
|
56
|
+
[key: string]: any;
|
|
57
|
+
}
|
|
58
|
+
interface SanityNavigationResult {
|
|
59
|
+
result?: {
|
|
60
|
+
items?: Array<{
|
|
61
|
+
label?: string;
|
|
62
|
+
title?: string;
|
|
63
|
+
link?: {
|
|
64
|
+
url?: string;
|
|
65
|
+
internal?: {
|
|
66
|
+
slug?: {
|
|
67
|
+
current?: string;
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
url?: string;
|
|
72
|
+
children?: any[];
|
|
73
|
+
}>;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
export default SanityAdapter;
|
|
77
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAGpD,OAAO,KAAK,EAAE,QAAQ,EAAa,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAC9E,OAAO,KAAK,EAAE,gBAAgB,EAA4C,MAAM,uBAAuB,CAAC;AAExG;;;GAGG;AACH,MAAM,WAAW,YAAY;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,KAAK,GAAG,WAAW,GAAG,eAAe,CAAC;IACpD,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACxB;AAED,qBAAa,aAAc,SAAQ,WAAW,CAAC,cAAc,CAAC;IAC1D,SAAS,CAAC,YAAY,EAAE,YAAY,CAAC;IACrC,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,IAAI,CAAa;gBAEb,MAAM,EAAE,YAAY;IAkBhC,uEAAuE;IACjE,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;IAiBtD,SAAS,CAAC,GAAG,EAAE,cAAc,GAAG,QAAQ;IAgBxC,eAAe,CAAC,GAAG,EAAE,sBAAsB,GAAG,cAAc;IAa5D;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,gBAAgB,CAAC;IAiB7C,OAAO,CAAC,WAAW;IA2CnB,OAAO,CAAC,eAAe;IAevB,OAAO,CAAC,gBAAgB;IAqCxB,OAAO,CAAC,WAAW;IAInB,OAAO,CAAC,WAAW;IASnB,OAAO,CAAC,eAAe;YAQT,WAAW;IAmBzB,OAAO,CAAC,aAAa;IA2BrB,OAAO,CAAC,iBAAiB;IAiCzB,OAAO,CAAC,YAAY;IAOpB;;OAEG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM;IAqB1D;;OAEG;IACH,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;CAKrC;AAGD,UAAU,cAAc;IACpB,MAAM,CAAC,EAAE,GAAG,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACtB;AAED,UAAU,sBAAsB;IAC5B,MAAM,CAAC,EAAE;QACL,KAAK,CAAC,EAAE,KAAK,CAAC;YACV,KAAK,CAAC,EAAE,MAAM,CAAC;YACf,KAAK,CAAC,EAAE,MAAM,CAAC;YACf,IAAI,CAAC,EAAE;gBACH,GAAG,CAAC,EAAE,MAAM,CAAC;gBACb,QAAQ,CAAC,EAAE;oBAAE,IAAI,CAAC,EAAE;wBAAE,OAAO,CAAC,EAAE,MAAM,CAAA;qBAAE,CAAA;iBAAE,CAAC;aAC9C,CAAC;YACF,GAAG,CAAC,EAAE,MAAM,CAAC;YACb,QAAQ,CAAC,EAAE,GAAG,EAAE,CAAC;SACpB,CAAC,CAAC;KACN,CAAC;CACL;AAED,eAAe,aAAa,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { IntiAdapter } from '@intijs/core/adapters';
|
|
2
|
+
import { NotFoundError } from '@intijs/core/errors';
|
|
3
|
+
import { createHttpClient } from '@intijs/core/http';
|
|
4
|
+
export class SanityAdapter extends IntiAdapter {
|
|
5
|
+
sanityConfig;
|
|
6
|
+
baseUrl;
|
|
7
|
+
http;
|
|
8
|
+
constructor(config) {
|
|
9
|
+
super('Sanity', config);
|
|
10
|
+
this.sanityConfig = {
|
|
11
|
+
apiVersion: 'v2024-03-01',
|
|
12
|
+
useCdn: true,
|
|
13
|
+
perspective: 'published',
|
|
14
|
+
draftMode: false,
|
|
15
|
+
...config
|
|
16
|
+
};
|
|
17
|
+
const host = this.sanityConfig.useCdn && !this.sanityConfig.draftMode
|
|
18
|
+
? 'apicdn.sanity.io'
|
|
19
|
+
: 'api.sanity.io';
|
|
20
|
+
this.baseUrl = `https://${this.sanityConfig.projectId}.${host}/${this.sanityConfig.apiVersion}/data/query/${this.sanityConfig.dataset}`;
|
|
21
|
+
this.http = createHttpClient({ name: 'sanity', fetch: config.fetch });
|
|
22
|
+
}
|
|
23
|
+
/** The page document with this `slug.current`, through a GROQ query */
|
|
24
|
+
async fetchPageBySlug(slug) {
|
|
25
|
+
const headers = {};
|
|
26
|
+
if (this.sanityConfig.token)
|
|
27
|
+
headers.Authorization = `Bearer ${this.sanityConfig.token}`;
|
|
28
|
+
const data = await this.http.get(this.baseUrl, {
|
|
29
|
+
query: {
|
|
30
|
+
query: '*[_type == $type && slug.current == $slug][0]',
|
|
31
|
+
$type: JSON.stringify(this.sanityConfig.pageType ?? 'page'),
|
|
32
|
+
$slug: JSON.stringify(slug),
|
|
33
|
+
perspective: this.sanityConfig.draftMode ? 'previewDrafts' : this.sanityConfig.perspective
|
|
34
|
+
},
|
|
35
|
+
headers,
|
|
36
|
+
resource: 'page'
|
|
37
|
+
});
|
|
38
|
+
if (!data?.result)
|
|
39
|
+
throw new NotFoundError('page', slug);
|
|
40
|
+
return this.parsePage(data);
|
|
41
|
+
}
|
|
42
|
+
parsePage(raw) {
|
|
43
|
+
const pageData = raw.result || raw;
|
|
44
|
+
return {
|
|
45
|
+
id: pageData._id,
|
|
46
|
+
slug: pageData.slug?.current || pageData._id,
|
|
47
|
+
title: pageData.title || 'Untitled',
|
|
48
|
+
blocks: this.parseBlocks(pageData.content || pageData.body || pageData.sections || pageData.modules || []),
|
|
49
|
+
seo: {
|
|
50
|
+
title: pageData.seo?.title || pageData.metaTitle || pageData.title,
|
|
51
|
+
description: pageData.seo?.description || pageData.metaDescription,
|
|
52
|
+
image: this.resolveImageUrl(pageData.seo?.image || pageData.ogImage)
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
parseNavigation(raw) {
|
|
57
|
+
const items = raw.result?.items?.map((item) => ({
|
|
58
|
+
label: item.label || item.title,
|
|
59
|
+
url: item.link?.url || item.link?.internal?.slug?.current || item.url || '#',
|
|
60
|
+
children: item.children?.map((child) => ({
|
|
61
|
+
label: child.label || child.title,
|
|
62
|
+
url: child.link?.url || child.link?.internal?.slug?.current || child.url || '#'
|
|
63
|
+
}))
|
|
64
|
+
})) || [];
|
|
65
|
+
return { items };
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Introspect Sanity schema for type generation
|
|
69
|
+
*/
|
|
70
|
+
async introspect() {
|
|
71
|
+
const schema = await this.fetchSchema();
|
|
72
|
+
const collections = schema
|
|
73
|
+
.filter((type) => type.type === 'document')
|
|
74
|
+
.map((doc) => ({
|
|
75
|
+
name: doc.name,
|
|
76
|
+
fields: this.parseSanityFields(doc.fields || [])
|
|
77
|
+
}));
|
|
78
|
+
return {
|
|
79
|
+
source: 'sanity',
|
|
80
|
+
version: '3.0',
|
|
81
|
+
collections
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
parseBlocks(content) {
|
|
85
|
+
if (!Array.isArray(content))
|
|
86
|
+
return [];
|
|
87
|
+
return content.map((block, index) => {
|
|
88
|
+
// Handle Portable Text (Rich Text)
|
|
89
|
+
if (block._type === 'block') {
|
|
90
|
+
return {
|
|
91
|
+
id: `block-${index}`,
|
|
92
|
+
type: 'rich-text',
|
|
93
|
+
data: {
|
|
94
|
+
style: block.style || 'normal',
|
|
95
|
+
children: block.children || [],
|
|
96
|
+
markDefs: block.markDefs || []
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
// Handle image assets
|
|
101
|
+
if (block._type === 'image' || block._type?.includes('image')) {
|
|
102
|
+
return {
|
|
103
|
+
id: block._key || `image-${index}`,
|
|
104
|
+
type: 'image',
|
|
105
|
+
data: this.parseImageBlock(block)
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
// Handle custom blocks
|
|
109
|
+
if (block._type) {
|
|
110
|
+
return {
|
|
111
|
+
id: block._key || `block-${index}`,
|
|
112
|
+
type: this.toPascalCase(block._type),
|
|
113
|
+
data: this.extractBlockData(block)
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
id: `block-${index}`,
|
|
118
|
+
type: 'unknown',
|
|
119
|
+
data: block
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
parseImageBlock(block) {
|
|
124
|
+
const asset = block.asset;
|
|
125
|
+
return {
|
|
126
|
+
asset: asset ? {
|
|
127
|
+
id: asset._ref,
|
|
128
|
+
url: this.getImageUrl(asset._ref, {}),
|
|
129
|
+
alt: block.alt,
|
|
130
|
+
caption: block.caption
|
|
131
|
+
} : null,
|
|
132
|
+
hotspot: block.hotspot,
|
|
133
|
+
crop: block.crop
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
extractBlockData(block) {
|
|
137
|
+
const data = {};
|
|
138
|
+
for (const [key, value] of Object.entries(block)) {
|
|
139
|
+
if (key.startsWith('_'))
|
|
140
|
+
continue;
|
|
141
|
+
// Handle references
|
|
142
|
+
if (this.isReference(value)) {
|
|
143
|
+
data[key] = { _ref: value._ref, _type: value._type };
|
|
144
|
+
}
|
|
145
|
+
// Handle assets
|
|
146
|
+
else if (key === 'asset' && value?._ref) {
|
|
147
|
+
data[key] = {
|
|
148
|
+
id: value._ref,
|
|
149
|
+
url: this.getImageUrl(value._ref, {})
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
// Handle arrays
|
|
153
|
+
else if (Array.isArray(value)) {
|
|
154
|
+
data[key] = value.map(v => this.isReference(v) ? { _ref: v._ref } : v);
|
|
155
|
+
}
|
|
156
|
+
// Handle slugs
|
|
157
|
+
else if (value?._type === 'slug') {
|
|
158
|
+
data[key] = value.current;
|
|
159
|
+
}
|
|
160
|
+
// Handle portable text blocks
|
|
161
|
+
else if (value?._type === 'block' || (Array.isArray(value) && value[0]?._type === 'block')) {
|
|
162
|
+
data[key] = value;
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
data[key] = value;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return data;
|
|
169
|
+
}
|
|
170
|
+
isReference(value) {
|
|
171
|
+
return value && typeof value === 'object' && value._ref && value._type === 'reference';
|
|
172
|
+
}
|
|
173
|
+
getImageUrl(assetRef, options) {
|
|
174
|
+
// Extract image ID from reference
|
|
175
|
+
const imageId = assetRef.replace('image-', '').replace(/-[a-z]+$/, '');
|
|
176
|
+
const dimensions = assetRef.match(/-(\d+)x(\d+)-/) || [];
|
|
177
|
+
const width = options.width || dimensions[1] || 800;
|
|
178
|
+
return `https://cdn.sanity.io/images/${this.sanityConfig.projectId}/${this.sanityConfig.dataset}/${imageId}-${width}x${width}.webp`;
|
|
179
|
+
}
|
|
180
|
+
resolveImageUrl(image) {
|
|
181
|
+
if (!image)
|
|
182
|
+
return undefined;
|
|
183
|
+
if (typeof image === 'string')
|
|
184
|
+
return image;
|
|
185
|
+
if (image.asset?._ref)
|
|
186
|
+
return this.getImageUrl(image.asset._ref, {});
|
|
187
|
+
if (image.url)
|
|
188
|
+
return image.url;
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
async fetchSchema() {
|
|
192
|
+
const url = `https://${this.sanityConfig.projectId}.api.sanity.io/${this.sanityConfig.apiVersion}/datasets/${this.sanityConfig.dataset}/query`;
|
|
193
|
+
const query = '*[_type == "sanity.imageAsset"] { _type }'; // Dummy query to check auth
|
|
194
|
+
const headers = {
|
|
195
|
+
'Content-Type': 'application/json'
|
|
196
|
+
};
|
|
197
|
+
if (this.sanityConfig.token) {
|
|
198
|
+
headers['Authorization'] = `Bearer ${this.sanityConfig.token}`;
|
|
199
|
+
}
|
|
200
|
+
// Note: Sanity doesn't expose schema via public API
|
|
201
|
+
// In production, this would need to fetch from Sanity's export or use the client
|
|
202
|
+
// For now, return a mock schema structure
|
|
203
|
+
return this.getMockSchema();
|
|
204
|
+
}
|
|
205
|
+
getMockSchema() {
|
|
206
|
+
return [
|
|
207
|
+
{
|
|
208
|
+
type: 'document',
|
|
209
|
+
name: 'Page',
|
|
210
|
+
fields: [
|
|
211
|
+
{ name: 'title', type: 'string' },
|
|
212
|
+
{ name: 'slug', type: 'slug' },
|
|
213
|
+
{ name: 'content', type: 'array', of: [{ type: 'block' }] },
|
|
214
|
+
{ name: 'seo', type: 'object' }
|
|
215
|
+
]
|
|
216
|
+
},
|
|
217
|
+
{
|
|
218
|
+
type: 'document',
|
|
219
|
+
name: 'Post',
|
|
220
|
+
fields: [
|
|
221
|
+
{ name: 'title', type: 'string' },
|
|
222
|
+
{ name: 'slug', type: 'slug' },
|
|
223
|
+
{ name: 'excerpt', type: 'text' },
|
|
224
|
+
{ name: 'body', type: 'array', of: [{ type: 'block' }, { type: 'image' }] },
|
|
225
|
+
{ name: 'author', type: 'reference' },
|
|
226
|
+
{ name: 'publishedAt', type: 'datetime' }
|
|
227
|
+
]
|
|
228
|
+
}
|
|
229
|
+
];
|
|
230
|
+
}
|
|
231
|
+
parseSanityFields(fields) {
|
|
232
|
+
const fieldTypeMap = {
|
|
233
|
+
'string': 'string',
|
|
234
|
+
'text': 'text',
|
|
235
|
+
'slug': 'string',
|
|
236
|
+
'url': 'string',
|
|
237
|
+
'number': 'number',
|
|
238
|
+
'boolean': 'boolean',
|
|
239
|
+
'datetime': 'datetime',
|
|
240
|
+
'date': 'date',
|
|
241
|
+
'file': 'media',
|
|
242
|
+
'image': 'media',
|
|
243
|
+
'reference': 'relation',
|
|
244
|
+
'array': 'json',
|
|
245
|
+
'object': 'json',
|
|
246
|
+
'block': 'richtext',
|
|
247
|
+
'span': 'text'
|
|
248
|
+
};
|
|
249
|
+
return fields.map(field => {
|
|
250
|
+
const isArray = field.type === 'array';
|
|
251
|
+
const actualType = isArray && field.of ? field.of[0]?.type : field.type;
|
|
252
|
+
return {
|
|
253
|
+
name: field.name,
|
|
254
|
+
type: fieldTypeMap[actualType] || 'json',
|
|
255
|
+
required: field.validation?.some((v) => v.required) || false,
|
|
256
|
+
multiple: isArray || field.type === 'array',
|
|
257
|
+
localized: false // Sanity handles localization differently
|
|
258
|
+
};
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
toPascalCase(str) {
|
|
262
|
+
return str
|
|
263
|
+
.split('-')
|
|
264
|
+
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
|
265
|
+
.join('');
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Build GROQ query for fetching pages
|
|
269
|
+
*/
|
|
270
|
+
buildPageQuery(contentType, slug) {
|
|
271
|
+
const baseQuery = `*[_type == "${contentType}"`;
|
|
272
|
+
const slugFilter = slug ? ` && slug.current == "${slug}"` : '';
|
|
273
|
+
const perspective = this.sanityConfig.draftMode ? ', "drafts." + _id in path("drafts.**")' : ' && !(_id in path("drafts.**"))';
|
|
274
|
+
return `${baseQuery}${slugFilter}${perspective}] {
|
|
275
|
+
_id,
|
|
276
|
+
_type,
|
|
277
|
+
title,
|
|
278
|
+
slug,
|
|
279
|
+
content,
|
|
280
|
+
body,
|
|
281
|
+
sections,
|
|
282
|
+
modules,
|
|
283
|
+
seo,
|
|
284
|
+
metaTitle,
|
|
285
|
+
metaDescription,
|
|
286
|
+
ogImage
|
|
287
|
+
}[0]`;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Get query URL for Sanity API
|
|
291
|
+
*/
|
|
292
|
+
getQueryUrl(query) {
|
|
293
|
+
const encodedQuery = encodeURIComponent(query);
|
|
294
|
+
const perspective = this.sanityConfig.draftMode ? 'previewDrafts' : 'published';
|
|
295
|
+
return `${this.baseUrl}?query=${encodedQuery}&perspective=${perspective}`;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
export default SanityAdapter;
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intijs/adapter-sanity",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Victor Antinori Broce",
|
|
7
|
+
"homepage": "https://github.com/intijs/inti/tree/main/packages/adapter-sanity#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/intijs/inti.git",
|
|
11
|
+
"directory": "packages/adapter-sanity"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/intijs/inti/issues"
|
|
15
|
+
},
|
|
16
|
+
"description": "Sanity CMS adapter for Inti.js",
|
|
17
|
+
"main": "./dist/index.js",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"import": "./dist/index.js",
|
|
22
|
+
"types": "./dist/index.d.ts"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist",
|
|
27
|
+
"src"
|
|
28
|
+
],
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "tsc",
|
|
31
|
+
"prepare": "node ../../scripts/prepare-package.mjs",
|
|
32
|
+
"dev": "tsc --watch",
|
|
33
|
+
"clean": "rm -rf dist",
|
|
34
|
+
"test": "bun test",
|
|
35
|
+
"prepublishOnly": "npm run build"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@intijs/core": "^0.1.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@types/node": "^20.0.0",
|
|
42
|
+
"typescript": "^5.7.3"
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import { IntiAdapter } from '@intijs/core/adapters';
|
|
2
|
+
import { NotFoundError } from '@intijs/core/errors';
|
|
3
|
+
import { createHttpClient, type HttpClient } from '@intijs/core/http';
|
|
4
|
+
import type { IntiPage, IntiBlock, IntiNavigation } from '@intijs/core/types';
|
|
5
|
+
import type { SchemaDefinition, SchemaCollection, SchemaField, FieldType } from '@intijs/core/adapters';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Sanity CMS Adapter
|
|
9
|
+
* Integrates Sanity.io with Inti.js
|
|
10
|
+
*/
|
|
11
|
+
export interface SanityConfig {
|
|
12
|
+
projectId: string;
|
|
13
|
+
dataset: string;
|
|
14
|
+
apiVersion?: string;
|
|
15
|
+
useCdn?: boolean;
|
|
16
|
+
token?: string;
|
|
17
|
+
perspective?: 'raw' | 'published' | 'previewDrafts';
|
|
18
|
+
draftMode?: boolean;
|
|
19
|
+
/** Document type of a page. Default `page` */
|
|
20
|
+
pageType?: string;
|
|
21
|
+
fetch?: typeof fetch;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class SanityAdapter extends IntiAdapter<SanityDocument> {
|
|
25
|
+
protected sanityConfig: SanityConfig;
|
|
26
|
+
protected baseUrl: string;
|
|
27
|
+
private http: HttpClient;
|
|
28
|
+
|
|
29
|
+
constructor(config: SanityConfig) {
|
|
30
|
+
super('Sanity', config);
|
|
31
|
+
this.sanityConfig = {
|
|
32
|
+
apiVersion: 'v2024-03-01',
|
|
33
|
+
useCdn: true,
|
|
34
|
+
perspective: 'published',
|
|
35
|
+
draftMode: false,
|
|
36
|
+
...config
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const host = this.sanityConfig.useCdn && !this.sanityConfig.draftMode
|
|
40
|
+
? 'apicdn.sanity.io'
|
|
41
|
+
: 'api.sanity.io';
|
|
42
|
+
|
|
43
|
+
this.baseUrl = `https://${this.sanityConfig.projectId}.${host}/${this.sanityConfig.apiVersion}/data/query/${this.sanityConfig.dataset}`;
|
|
44
|
+
this.http = createHttpClient({ name: 'sanity', fetch: config.fetch });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The page document with this `slug.current`, through a GROQ query */
|
|
48
|
+
async fetchPageBySlug(slug: string): Promise<IntiPage> {
|
|
49
|
+
const headers: Record<string, string> = {};
|
|
50
|
+
if (this.sanityConfig.token) headers.Authorization = `Bearer ${this.sanityConfig.token}`;
|
|
51
|
+
const data = await this.http.get<SanityDocument>(this.baseUrl, {
|
|
52
|
+
query: {
|
|
53
|
+
query: '*[_type == $type && slug.current == $slug][0]',
|
|
54
|
+
$type: JSON.stringify(this.sanityConfig.pageType ?? 'page'),
|
|
55
|
+
$slug: JSON.stringify(slug),
|
|
56
|
+
perspective: this.sanityConfig.draftMode ? 'previewDrafts' : this.sanityConfig.perspective
|
|
57
|
+
},
|
|
58
|
+
headers,
|
|
59
|
+
resource: 'page'
|
|
60
|
+
});
|
|
61
|
+
if (!data?.result) throw new NotFoundError('page', slug);
|
|
62
|
+
return this.parsePage(data);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
parsePage(raw: SanityDocument): IntiPage {
|
|
66
|
+
const pageData = raw.result || raw;
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
id: pageData._id,
|
|
70
|
+
slug: pageData.slug?.current || pageData._id,
|
|
71
|
+
title: pageData.title || 'Untitled',
|
|
72
|
+
blocks: this.parseBlocks(pageData.content || pageData.body || pageData.sections || pageData.modules || []),
|
|
73
|
+
seo: {
|
|
74
|
+
title: pageData.seo?.title || pageData.metaTitle || pageData.title,
|
|
75
|
+
description: pageData.seo?.description || pageData.metaDescription,
|
|
76
|
+
image: this.resolveImageUrl(pageData.seo?.image || pageData.ogImage)
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
parseNavigation(raw: SanityNavigationResult): IntiNavigation {
|
|
82
|
+
const items = raw.result?.items?.map((item: any) => ({
|
|
83
|
+
label: item.label || item.title,
|
|
84
|
+
url: item.link?.url || item.link?.internal?.slug?.current || item.url || '#',
|
|
85
|
+
children: item.children?.map((child: any) => ({
|
|
86
|
+
label: child.label || child.title,
|
|
87
|
+
url: child.link?.url || child.link?.internal?.slug?.current || child.url || '#'
|
|
88
|
+
}))
|
|
89
|
+
})) || [];
|
|
90
|
+
|
|
91
|
+
return { items };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Introspect Sanity schema for type generation
|
|
96
|
+
*/
|
|
97
|
+
async introspect(): Promise<SchemaDefinition> {
|
|
98
|
+
const schema = await this.fetchSchema();
|
|
99
|
+
|
|
100
|
+
const collections: SchemaCollection[] = schema
|
|
101
|
+
.filter((type: any) => type.type === 'document')
|
|
102
|
+
.map((doc: any) => ({
|
|
103
|
+
name: doc.name,
|
|
104
|
+
fields: this.parseSanityFields(doc.fields || [])
|
|
105
|
+
}));
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
source: 'sanity',
|
|
109
|
+
version: '3.0',
|
|
110
|
+
collections
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private parseBlocks(content: any[]): IntiBlock[] {
|
|
115
|
+
if (!Array.isArray(content)) return [];
|
|
116
|
+
|
|
117
|
+
return content.map((block, index) => {
|
|
118
|
+
// Handle Portable Text (Rich Text)
|
|
119
|
+
if (block._type === 'block') {
|
|
120
|
+
return {
|
|
121
|
+
id: `block-${index}`,
|
|
122
|
+
type: 'rich-text',
|
|
123
|
+
data: {
|
|
124
|
+
style: block.style || 'normal',
|
|
125
|
+
children: block.children || [],
|
|
126
|
+
markDefs: block.markDefs || []
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Handle image assets
|
|
132
|
+
if (block._type === 'image' || block._type?.includes('image')) {
|
|
133
|
+
return {
|
|
134
|
+
id: block._key || `image-${index}`,
|
|
135
|
+
type: 'image',
|
|
136
|
+
data: this.parseImageBlock(block)
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Handle custom blocks
|
|
141
|
+
if (block._type) {
|
|
142
|
+
return {
|
|
143
|
+
id: block._key || `block-${index}`,
|
|
144
|
+
type: this.toPascalCase(block._type),
|
|
145
|
+
data: this.extractBlockData(block)
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
id: `block-${index}`,
|
|
151
|
+
type: 'unknown',
|
|
152
|
+
data: block
|
|
153
|
+
};
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
private parseImageBlock(block: any): any {
|
|
158
|
+
const asset = block.asset;
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
asset: asset ? {
|
|
162
|
+
id: asset._ref,
|
|
163
|
+
url: this.getImageUrl(asset._ref, {}),
|
|
164
|
+
alt: block.alt,
|
|
165
|
+
caption: block.caption
|
|
166
|
+
} : null,
|
|
167
|
+
hotspot: block.hotspot,
|
|
168
|
+
crop: block.crop
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private extractBlockData(block: any): Record<string, any> {
|
|
173
|
+
const data: Record<string, any> = {};
|
|
174
|
+
|
|
175
|
+
for (const [key, value] of Object.entries(block)) {
|
|
176
|
+
if (key.startsWith('_')) continue;
|
|
177
|
+
|
|
178
|
+
// Handle references
|
|
179
|
+
if (this.isReference(value)) {
|
|
180
|
+
data[key] = { _ref: (value as any)._ref, _type: (value as any)._type };
|
|
181
|
+
}
|
|
182
|
+
// Handle assets
|
|
183
|
+
else if (key === 'asset' && (value as any)?._ref) {
|
|
184
|
+
data[key] = {
|
|
185
|
+
id: (value as any)._ref,
|
|
186
|
+
url: this.getImageUrl((value as any)._ref, {})
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
// Handle arrays
|
|
190
|
+
else if (Array.isArray(value)) {
|
|
191
|
+
data[key] = value.map(v => this.isReference(v) ? { _ref: (v as any)._ref } : v);
|
|
192
|
+
}
|
|
193
|
+
// Handle slugs
|
|
194
|
+
else if ((value as any)?._type === 'slug') {
|
|
195
|
+
data[key] = (value as any).current;
|
|
196
|
+
}
|
|
197
|
+
// Handle portable text blocks
|
|
198
|
+
else if ((value as any)?._type === 'block' || (Array.isArray(value) && (value[0] as any)?._type === 'block')) {
|
|
199
|
+
data[key] = value;
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
data[key] = value;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return data;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private isReference(value: any): boolean {
|
|
210
|
+
return value && typeof value === 'object' && value._ref && value._type === 'reference';
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
private getImageUrl(assetRef: string, options: any): string {
|
|
214
|
+
// Extract image ID from reference
|
|
215
|
+
const imageId = assetRef.replace('image-', '').replace(/-[a-z]+$/, '');
|
|
216
|
+
const dimensions = assetRef.match(/-(\d+)x(\d+)-/) || [];
|
|
217
|
+
const width = options.width || dimensions[1] || 800;
|
|
218
|
+
|
|
219
|
+
return `https://cdn.sanity.io/images/${this.sanityConfig.projectId}/${this.sanityConfig.dataset}/${imageId}-${width}x${width}.webp`;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private resolveImageUrl(image: any): string | undefined {
|
|
223
|
+
if (!image) return undefined;
|
|
224
|
+
if (typeof image === 'string') return image;
|
|
225
|
+
if (image.asset?._ref) return this.getImageUrl(image.asset._ref, {});
|
|
226
|
+
if (image.url) return image.url;
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
private async fetchSchema(): Promise<any[]> {
|
|
231
|
+
const url = `https://${this.sanityConfig.projectId}.api.sanity.io/${this.sanityConfig.apiVersion}/datasets/${this.sanityConfig.dataset}/query`;
|
|
232
|
+
|
|
233
|
+
const query = '*[_type == "sanity.imageAsset"] { _type }'; // Dummy query to check auth
|
|
234
|
+
|
|
235
|
+
const headers: Record<string, string> = {
|
|
236
|
+
'Content-Type': 'application/json'
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
if (this.sanityConfig.token) {
|
|
240
|
+
headers['Authorization'] = `Bearer ${this.sanityConfig.token}`;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Note: Sanity doesn't expose schema via public API
|
|
244
|
+
// In production, this would need to fetch from Sanity's export or use the client
|
|
245
|
+
// For now, return a mock schema structure
|
|
246
|
+
return this.getMockSchema();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private getMockSchema(): any[] {
|
|
250
|
+
return [
|
|
251
|
+
{
|
|
252
|
+
type: 'document',
|
|
253
|
+
name: 'Page',
|
|
254
|
+
fields: [
|
|
255
|
+
{ name: 'title', type: 'string' },
|
|
256
|
+
{ name: 'slug', type: 'slug' },
|
|
257
|
+
{ name: 'content', type: 'array', of: [{ type: 'block' }] },
|
|
258
|
+
{ name: 'seo', type: 'object' }
|
|
259
|
+
]
|
|
260
|
+
},
|
|
261
|
+
{
|
|
262
|
+
type: 'document',
|
|
263
|
+
name: 'Post',
|
|
264
|
+
fields: [
|
|
265
|
+
{ name: 'title', type: 'string' },
|
|
266
|
+
{ name: 'slug', type: 'slug' },
|
|
267
|
+
{ name: 'excerpt', type: 'text' },
|
|
268
|
+
{ name: 'body', type: 'array', of: [{ type: 'block' }, { type: 'image' }] },
|
|
269
|
+
{ name: 'author', type: 'reference' },
|
|
270
|
+
{ name: 'publishedAt', type: 'datetime' }
|
|
271
|
+
]
|
|
272
|
+
}
|
|
273
|
+
];
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
private parseSanityFields(fields: any[]): SchemaField[] {
|
|
277
|
+
const fieldTypeMap: Record<string, FieldType> = {
|
|
278
|
+
'string': 'string',
|
|
279
|
+
'text': 'text',
|
|
280
|
+
'slug': 'string',
|
|
281
|
+
'url': 'string',
|
|
282
|
+
'number': 'number',
|
|
283
|
+
'boolean': 'boolean',
|
|
284
|
+
'datetime': 'datetime',
|
|
285
|
+
'date': 'date',
|
|
286
|
+
'file': 'media',
|
|
287
|
+
'image': 'media',
|
|
288
|
+
'reference': 'relation',
|
|
289
|
+
'array': 'json',
|
|
290
|
+
'object': 'json',
|
|
291
|
+
'block': 'richtext',
|
|
292
|
+
'span': 'text'
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
return fields.map(field => {
|
|
296
|
+
const isArray = field.type === 'array';
|
|
297
|
+
const actualType = isArray && field.of ? field.of[0]?.type : field.type;
|
|
298
|
+
|
|
299
|
+
return {
|
|
300
|
+
name: field.name,
|
|
301
|
+
type: fieldTypeMap[actualType] || 'json',
|
|
302
|
+
required: field.validation?.some((v: any) => v.required) || false,
|
|
303
|
+
multiple: isArray || field.type === 'array',
|
|
304
|
+
localized: false // Sanity handles localization differently
|
|
305
|
+
};
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private toPascalCase(str: string): string {
|
|
310
|
+
return str
|
|
311
|
+
.split('-')
|
|
312
|
+
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
|
313
|
+
.join('');
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Build GROQ query for fetching pages
|
|
318
|
+
*/
|
|
319
|
+
buildPageQuery(contentType: string, slug?: string): string {
|
|
320
|
+
const baseQuery = `*[_type == "${contentType}"`;
|
|
321
|
+
const slugFilter = slug ? ` && slug.current == "${slug}"` : '';
|
|
322
|
+
const perspective = this.sanityConfig.draftMode ? ', "drafts." + _id in path("drafts.**")' : ' && !(_id in path("drafts.**"))';
|
|
323
|
+
|
|
324
|
+
return `${baseQuery}${slugFilter}${perspective}] {
|
|
325
|
+
_id,
|
|
326
|
+
_type,
|
|
327
|
+
title,
|
|
328
|
+
slug,
|
|
329
|
+
content,
|
|
330
|
+
body,
|
|
331
|
+
sections,
|
|
332
|
+
modules,
|
|
333
|
+
seo,
|
|
334
|
+
metaTitle,
|
|
335
|
+
metaDescription,
|
|
336
|
+
ogImage
|
|
337
|
+
}[0]`;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Get query URL for Sanity API
|
|
342
|
+
*/
|
|
343
|
+
getQueryUrl(query: string): string {
|
|
344
|
+
const encodedQuery = encodeURIComponent(query);
|
|
345
|
+
const perspective = this.sanityConfig.draftMode ? 'previewDrafts' : 'published';
|
|
346
|
+
return `${this.baseUrl}?query=${encodedQuery}&perspective=${perspective}`;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Sanity types
|
|
351
|
+
interface SanityDocument {
|
|
352
|
+
result?: any;
|
|
353
|
+
_id?: string;
|
|
354
|
+
_type?: string;
|
|
355
|
+
[key: string]: any;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
interface SanityNavigationResult {
|
|
359
|
+
result?: {
|
|
360
|
+
items?: Array<{
|
|
361
|
+
label?: string;
|
|
362
|
+
title?: string;
|
|
363
|
+
link?: {
|
|
364
|
+
url?: string;
|
|
365
|
+
internal?: { slug?: { current?: string } };
|
|
366
|
+
};
|
|
367
|
+
url?: string;
|
|
368
|
+
children?: any[];
|
|
369
|
+
}>;
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export default SanityAdapter;
|