@sanity/client 7.2.2 → 7.4.0-agent-actions.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/README.md +141 -1
- package/dist/_chunks-cjs/isRecord.cjs +6 -0
- package/dist/_chunks-cjs/isRecord.cjs.map +1 -0
- package/dist/_chunks-cjs/resolveEditInfo.cjs +3 -5
- package/dist/_chunks-cjs/resolveEditInfo.cjs.map +1 -1
- package/dist/_chunks-cjs/stegaClean.cjs +4 -0
- package/dist/_chunks-cjs/stegaClean.cjs.map +1 -1
- package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +2 -5
- package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +1 -1
- package/dist/_chunks-es/isRecord.js +7 -0
- package/dist/_chunks-es/isRecord.js.map +1 -0
- package/dist/_chunks-es/resolveEditInfo.js +1 -3
- package/dist/_chunks-es/resolveEditInfo.js.map +1 -1
- package/dist/_chunks-es/stegaClean.js +4 -0
- package/dist/_chunks-es/stegaClean.js.map +1 -1
- package/dist/_chunks-es/stegaEncodeSourceMap.js +1 -4
- package/dist/_chunks-es/stegaEncodeSourceMap.js.map +1 -1
- package/dist/index.browser.cjs +158 -33
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.d.cts +513 -68
- package/dist/index.browser.d.ts +513 -68
- package/dist/index.browser.js +159 -34
- package/dist/index.browser.js.map +1 -1
- package/dist/index.cjs +160 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +513 -68
- package/dist/index.d.ts +513 -68
- package/dist/index.js +160 -34
- package/dist/index.js.map +1 -1
- package/dist/stega.browser.d.cts +513 -68
- package/dist/stega.browser.d.ts +513 -68
- package/dist/stega.d.cts +513 -68
- package/dist/stega.d.ts +513 -68
- package/package.json +1 -1
- package/src/agent/actions/AgentActionsClient.ts +29 -2
- package/src/agent/actions/commonTypes.ts +57 -17
- package/src/agent/actions/generate.ts +36 -2
- package/src/agent/actions/patch.ts +136 -0
- package/src/agent/actions/prompt.ts +145 -0
- package/src/agent/actions/transform.ts +56 -4
- package/src/agent/actions/translate.ts +5 -2
- package/src/csm/walkMap.ts +1 -1
- package/src/data/eventsource.ts +16 -7
- package/src/data/listen.ts +10 -4
- package/src/data/live.ts +13 -5
- package/src/defineCreateClient.ts +7 -1
- package/src/http/errors.ts +92 -27
- package/src/http/request.ts +3 -3
- package/src/http/requestOptions.ts +4 -0
- package/src/types.ts +39 -10
- package/src/util/codeFrame.ts +174 -0
- package/src/{csm → util}/isRecord.ts +1 -1
- package/umd/sanityClient.js +161 -36
- package/umd/sanityClient.min.js +2 -2
package/README.md
CHANGED
|
@@ -27,6 +27,10 @@ export const client = createClient({
|
|
|
27
27
|
projectId: 'your-project-id',
|
|
28
28
|
dataset: 'your-dataset-name',
|
|
29
29
|
useCdn: true, // set to `false` to bypass the edge cache
|
|
30
|
+
// Set default headers to be included with all requests
|
|
31
|
+
headers: {
|
|
32
|
+
'X-Custom-Header': 'custom-value'
|
|
33
|
+
},
|
|
30
34
|
apiVersion: '2025-02-06', // use current date (YYYY-MM-DD) to target the latest API version. Note: this should always be hard coded. Setting API version based on a dynamic value (e.g. new Date()) may break your application at a random point in the future.
|
|
31
35
|
// token: process.env.SANITY_SECRET_TOKEN // Needed for certain operations like updating content, accessing drafts or using draft perspectives
|
|
32
36
|
})
|
|
@@ -113,12 +117,17 @@ export async function updateDocumentTitle(_id, title) {
|
|
|
113
117
|
- [Agent Actions API](#agent-actions-api)
|
|
114
118
|
- [Overview](#overview)
|
|
115
119
|
- [Generating Content](#generating-content)
|
|
120
|
+
- [Generating images](#generating-images)
|
|
116
121
|
- [Example: Using GROQ in instructionParams](#example-using-groq-in-instructionparams)
|
|
117
122
|
- [Example: Using the async flag](#example-using-the-async-flag)
|
|
118
123
|
- [Transforming Documents](#transforming-documents)
|
|
124
|
+
- [Transforming images](#transforming-images)
|
|
125
|
+
- [Image descriptions](#image-descriptions)
|
|
119
126
|
- [Example: Field-based transformation](#example-field-based-transformation)
|
|
120
127
|
- [Translating Documents](#translating-documents)
|
|
121
128
|
- [Example: Storing language in a field](#example-storing-language-in-a-field)
|
|
129
|
+
- [Prompt the LLM](#prompt-the-llm)
|
|
130
|
+
- [Patch with a schema-aware API](#patch-with-a-schema-aware-api)
|
|
122
131
|
- [Version actions](#version-actions)
|
|
123
132
|
- [Create Version Action](#create-version)
|
|
124
133
|
- [Discard Version Action](#discard-version)
|
|
@@ -1974,10 +1983,12 @@ Agent Actions allow you to:
|
|
|
1974
1983
|
- **Generate** new content for a document or specific fields using LLM instructions.
|
|
1975
1984
|
- **Transform** a document based on instructions, optionally copying from a source document.
|
|
1976
1985
|
- **Translate** a document or fields from one language to another, with support for style guides and protected phrases.
|
|
1986
|
+
- **Prompt** the LLM using the same instruction template format as the other actions, but returns text or json instead of acting on a document.
|
|
1987
|
+
- **Patch** documents using a schema-aware API; validates that provided paths and values are schema compliant and handles `setIfMissing` semantics for deep value operations
|
|
1977
1988
|
|
|
1978
1989
|
All methods are available in both Promise and Observable forms:
|
|
1979
1990
|
|
|
1980
|
-
- `client.agent.action.generate`, `client.agent.action.transform`, `client.agent.action.translate` (Promise-based)
|
|
1991
|
+
- `client.agent.action.generate`, `client.agent.action.transform`, `client.agent.action.translate`, `client.agent.action.prompt`, `client.agent.action.patch` (Promise-based)
|
|
1981
1992
|
- `client.observable.agent.action.generate`, etc. (Observable-based, for streaming or RxJS use)
|
|
1982
1993
|
|
|
1983
1994
|
---
|
|
@@ -2001,6 +2012,28 @@ const result = await client.agent.action.generate({
|
|
|
2001
2012
|
- **instruction**: A string template describing what to generate. Use `$variable` for dynamic values.
|
|
2002
2013
|
- **instructionParams**: Values for variables in the instruction. Supports constants, fields, documents, or GROQ queries.
|
|
2003
2014
|
- **target**: (Optional) Specifies which fields or paths to generate content for.
|
|
2015
|
+
- **temperature**: (Optional) Controls variance, 0-1 – defaults to 0.3
|
|
2016
|
+
- **async**: (Optional) when true, the request will respond with the document id; the LLM request and mutations will continue on the server.
|
|
2017
|
+
- **noWrite**: (Optional) when true, the document will not be changed. The response will contain the document value with the changes.
|
|
2018
|
+
- **conditionalPaths**: (Optional) control how conditionally readOnly and hidden fields and types will be treated
|
|
2019
|
+
|
|
2020
|
+
##### Generating images
|
|
2021
|
+
|
|
2022
|
+
Generate will generate images the same was as AI Assist, for images that have been configured using
|
|
2023
|
+
[AI Assist schema options](https://github.com/sanity-io/assist/tree/main/plugin#image-generation).
|
|
2024
|
+
|
|
2025
|
+
To generate images _without_ changing the schema, directly target an image asset path.
|
|
2026
|
+
|
|
2027
|
+
For example, all the following will generate an image into the provided asset:
|
|
2028
|
+
|
|
2029
|
+
- `target: {path: ['image', 'asset'] }`
|
|
2030
|
+
- `target: {path: 'image', include: ['asset'] }`
|
|
2031
|
+
|
|
2032
|
+
Image generation can be combined with regular content targets:
|
|
2033
|
+
|
|
2034
|
+
- `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`
|
|
2035
|
+
|
|
2036
|
+
Since Generate happens in a single LLM pass, the image will be contextually related to other generated content.
|
|
2004
2037
|
|
|
2005
2038
|
##### Example: Using GROQ in instructionParams
|
|
2006
2039
|
|
|
@@ -2057,6 +2090,41 @@ const result = await client.agent.action.transform({
|
|
|
2057
2090
|
- **instruction**: A string template describing the transformation.
|
|
2058
2091
|
- **targetDocument**: (Optional) Specify a different document to write the result to, or create a new one.
|
|
2059
2092
|
- **target**: (Optional) Specifies which fields or paths to transform.
|
|
2093
|
+
- **temperature**: (Optional) Controls variance, 0-1 – defaults to 0
|
|
2094
|
+
- **async**: (Optional) when true, the request will respond with the document id; the LLM request and mutations will continue on the server.
|
|
2095
|
+
- **noWrite**: (Optional) when true, the document will not be changed. The response will contain the document value with the changes.
|
|
2096
|
+
- **conditionalPaths**: (Optional) control how conditionally readOnly and hidden fields and types will be treated
|
|
2097
|
+
|
|
2098
|
+
##### Transforming images
|
|
2099
|
+
|
|
2100
|
+
To transform an existing image, directly target an image asset path.
|
|
2101
|
+
|
|
2102
|
+
For example, all the following will transform the image into the provided asset:
|
|
2103
|
+
|
|
2104
|
+
- `target: {path: ['image', 'asset'] }`
|
|
2105
|
+
- `target: {path: 'image', include: ['asset'] }`
|
|
2106
|
+
|
|
2107
|
+
Image transform can be combined with regular content targets:
|
|
2108
|
+
|
|
2109
|
+
- `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`
|
|
2110
|
+
|
|
2111
|
+
Image transform can have per-path instructions, just like any other target paths:
|
|
2112
|
+
|
|
2113
|
+
- `target: [{path: ['image', 'asset'], instruction: 'Make the sky blue' }`
|
|
2114
|
+
|
|
2115
|
+
##### Image descriptions
|
|
2116
|
+
|
|
2117
|
+
Images can be transformed to an textual description by targeting a `string`, `text` or Portable Text field (`array` with `block`)
|
|
2118
|
+
and with `operation: 'image-description'`.
|
|
2119
|
+
|
|
2120
|
+
Custom instructions for image description targets will be used to generate the description.
|
|
2121
|
+
|
|
2122
|
+
Such targets must be a descendant field of an image object.
|
|
2123
|
+
|
|
2124
|
+
For example:
|
|
2125
|
+
* `target: {path: ['image', 'description'], operation: 'image-description' }`
|
|
2126
|
+
* `target: {path: ['array', {_key: 'abc'}, 'alt'], operation: 'image-description' } //assuming the item in the array on the key-ed path is an image`
|
|
2127
|
+
* `target: {path: ['image'], include: ['portableTextField'], operation: 'image-description', instruction: 'Use formatting and headings to describe the image in great detail' }`
|
|
2060
2128
|
|
|
2061
2129
|
##### Example: Field-based transformation
|
|
2062
2130
|
|
|
@@ -2080,6 +2148,7 @@ await client.agent.action.transform({
|
|
|
2080
2148
|
const result = await client.agent.action.translate({
|
|
2081
2149
|
schemaId: 'your-schema-id',
|
|
2082
2150
|
documentId: 'source-document-id',
|
|
2151
|
+
targetDocument: {operation: 'create'},
|
|
2083
2152
|
fromLanguage: {id: 'en', title: 'English'},
|
|
2084
2153
|
toLanguage: {id: 'es', title: 'Spanish'},
|
|
2085
2154
|
styleGuide: 'Use a friendly tone.',
|
|
@@ -2090,11 +2159,16 @@ const result = await client.agent.action.translate({
|
|
|
2090
2159
|
|
|
2091
2160
|
- **schemaId**: The schema identifier for the document type.
|
|
2092
2161
|
- **documentId**: The source document ID.
|
|
2162
|
+
- **targetDocument**: (Optional) Specify a different document to write the result to, or create a new one.
|
|
2093
2163
|
- **fromLanguage**: (Optional) The source language code and title.
|
|
2094
2164
|
- **toLanguage**: The target language code and title.
|
|
2095
2165
|
- **styleGuide**: (Optional) Instructions for translation style.
|
|
2096
2166
|
- **protectedPhrases**: (Optional) Array of phrases to leave untranslated.
|
|
2097
2167
|
- **target**: (Optional) Specifies which fields or paths to translate.
|
|
2168
|
+
- **temperature**: (Optional) Controls variance, 0-1 – defaults to 0
|
|
2169
|
+
- **async**: (Optional) when true, the request will respond with the document id; the LLM request and mutations will continue on the server.
|
|
2170
|
+
- **noWrite**: (Optional) when true, the document will not be changed. The response will contain the document value with the changes.
|
|
2171
|
+
- **conditionalPaths**: (Optional) control how conditionally readOnly and hidden fields and types will be treated
|
|
2098
2172
|
|
|
2099
2173
|
##### Example: Storing language in a field
|
|
2100
2174
|
|
|
@@ -2108,6 +2182,72 @@ await client.agent.action.translate({
|
|
|
2108
2182
|
})
|
|
2109
2183
|
```
|
|
2110
2184
|
|
|
2185
|
+
#### Prompt the LLM
|
|
2186
|
+
|
|
2187
|
+
```ts
|
|
2188
|
+
const result = await client.agent.action.prompt({
|
|
2189
|
+
instruction: 'Say: Oh, hi $name!',
|
|
2190
|
+
instructionParams: {
|
|
2191
|
+
name: 'Mark',
|
|
2192
|
+
},
|
|
2193
|
+
temperature: 0.5,
|
|
2194
|
+
format: 'text',
|
|
2195
|
+
})
|
|
2196
|
+
```
|
|
2197
|
+
|
|
2198
|
+
- **instruction**: A string template describing what the LLM should do. Use `$variable` for dynamic values.
|
|
2199
|
+
- **instructionParams**: Values for variables in the instruction. Supports constants, fields, documents, or GROQ queries.
|
|
2200
|
+
- **format**: (Optional) 'text' or 'json'. Defaults to 'text'. Note that when specifying 'json', the instruction MUST include the word "json" (ignoring case) in some form.
|
|
2201
|
+
- **temperature**: (Optional) Controls variance, 0-1 – defaults to 0
|
|
2202
|
+
|
|
2203
|
+
#### Patch with a schema-aware API
|
|
2204
|
+
|
|
2205
|
+
The `client.patch` and `client.transaction` API are not schema aware. This allows patching documents any way you want, but the operations will not fail if they deviate from the document schema.
|
|
2206
|
+
|
|
2207
|
+
To ensure schema-compliant operation, `client.agent.action.patch` is available. It will ensure that provided paths and values adhere to the document schema,
|
|
2208
|
+
ensure no duplicate keys are inserted, and merge object values so `set` operations dont accidentally remove existing values.
|
|
2209
|
+
|
|
2210
|
+
```ts
|
|
2211
|
+
const result = await client.agent.action.patch({
|
|
2212
|
+
schemaId,
|
|
2213
|
+
documentId,
|
|
2214
|
+
target: [
|
|
2215
|
+
{path: 'title', operation: 'set', value: 'New title'},
|
|
2216
|
+
{
|
|
2217
|
+
path: ['wrapper', 'array'],
|
|
2218
|
+
operation: 'append',
|
|
2219
|
+
value: [{_type: 'item', title: 'Item title'}],
|
|
2220
|
+
},
|
|
2221
|
+
],
|
|
2222
|
+
})
|
|
2223
|
+
```
|
|
2224
|
+
|
|
2225
|
+
- **schemaId**: The schema identifier for the document type.
|
|
2226
|
+
- **documentId**: The source document ID OR use `targetDocument`
|
|
2227
|
+
- **targetDocument**: (Optional) Specify a different document to write the result to, or create a new one. Incompatible with `documentId`
|
|
2228
|
+
- **target**: Specify patch operations and values for paths in the document.
|
|
2229
|
+
- **async**: (Optional) when true, the request will respond with the document id; the LLM request and mutations will continue on the server.
|
|
2230
|
+
- **noWrite**: (Optional) when true, the document will not be changed. The response will contain the document value with the changes.
|
|
2231
|
+
- **conditionalPaths**: (Optional) control how conditionally readOnly and hidden fields and types will be treated
|
|
2232
|
+
|
|
2233
|
+
#### Appending into array after a key
|
|
2234
|
+
|
|
2235
|
+
When appending to arrays, providing a `_key` is optional.
|
|
2236
|
+
When a path targets a key in an array, the values provided will be appended after that key'ed item in the array.
|
|
2237
|
+
Note that when appending to arrays, `value` must be an array itself, even when only a single item should be appended.
|
|
2238
|
+
|
|
2239
|
+
```ts
|
|
2240
|
+
const result = await client.agent.action.patch({
|
|
2241
|
+
schemaId,
|
|
2242
|
+
documentId,
|
|
2243
|
+
target: {
|
|
2244
|
+
path: ['array', {_key: 'existingKey'}],
|
|
2245
|
+
operation: 'append',
|
|
2246
|
+
value: [{_type: 'item', title: 'Item title', _key: 'isOptionalAndWillBeGeneratedIfMissing'}],
|
|
2247
|
+
},
|
|
2248
|
+
})
|
|
2249
|
+
```
|
|
2250
|
+
|
|
2111
2251
|
## License
|
|
2112
2252
|
|
|
2113
2253
|
MIT © [Sanity.io](https://www.sanity.io/)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isRecord.cjs","sources":["../../src/util/isRecord.ts"],"sourcesContent":["/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n"],"names":[],"mappings":";AACO,SAAS,SAAS,OAAkD;AAClE,SAAA,OAAO,SAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var isRecord = require("./isRecord.cjs");
|
|
2
3
|
const rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g, reKeySegment = /_key\s*==\s*['"](.*)['"]/, reIndexTuple = /^\d*:\d*$/;
|
|
3
4
|
function isIndexSegment(segment) {
|
|
4
5
|
return typeof segment == "number" || typeof segment == "string" && /^\[\d+\]$/.test(segment);
|
|
@@ -213,20 +214,17 @@ function resolveMapping(resultPath, csm) {
|
|
|
213
214
|
function isArray(value) {
|
|
214
215
|
return value !== null && Array.isArray(value);
|
|
215
216
|
}
|
|
216
|
-
function isRecord(value) {
|
|
217
|
-
return typeof value == "object" && value !== null;
|
|
218
|
-
}
|
|
219
217
|
function walkMap(value, mappingFn, path = []) {
|
|
220
218
|
if (isArray(value))
|
|
221
219
|
return value.map((v, idx) => {
|
|
222
|
-
if (isRecord(v)) {
|
|
220
|
+
if (isRecord.isRecord(v)) {
|
|
223
221
|
const _key = v._key;
|
|
224
222
|
if (typeof _key == "string")
|
|
225
223
|
return walkMap(v, mappingFn, path.concat({ _key, _index: idx }));
|
|
226
224
|
}
|
|
227
225
|
return walkMap(v, mappingFn, path.concat(idx));
|
|
228
226
|
});
|
|
229
|
-
if (isRecord(value)) {
|
|
227
|
+
if (isRecord.isRecord(value)) {
|
|
230
228
|
if (value._type === "block" || value._type === "span") {
|
|
231
229
|
const result = { ...value };
|
|
232
230
|
return value._type === "block" ? result.children = walkMap(value.children, mappingFn, path.concat("children")) : value._type === "span" && (result.text = walkMap(value.text, mappingFn, path.concat("text"))), result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveEditInfo.cjs","sources":["../../src/csm/studioPath.ts","../../src/csm/draftUtils.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","// nominal/opaque type hack\ntype Opaque<T, K> = T & {__opaqueId__: K}\n\n/** @internal */\nexport type DraftId = Opaque<string, 'draftId'>\n\n/** @internal */\nexport type PublishedId = Opaque<string, 'publishedId'>\n\n/** @internal */\nexport const DRAFTS_FOLDER = 'drafts'\n\n/** @internal */\nexport const VERSION_FOLDER = 'versions'\n\nconst PATH_SEPARATOR = '.'\nconst DRAFTS_PREFIX = `${DRAFTS_FOLDER}${PATH_SEPARATOR}`\nconst VERSION_PREFIX = `${VERSION_FOLDER}${PATH_SEPARATOR}`\n\n/** @internal */\nexport function isDraftId(id: string): id is DraftId {\n return id.startsWith(DRAFTS_PREFIX)\n}\n\n/** @internal */\nexport function isVersionId(id: string): boolean {\n return id.startsWith(VERSION_PREFIX)\n}\n\n/** @internal */\nexport function isPublishedId(id: string): id is PublishedId {\n return !isDraftId(id) && !isVersionId(id)\n}\n\n/** @internal */\nexport function getDraftId(id: string): DraftId {\n if (isVersionId(id)) {\n const publishedId = getPublishedId(id)\n return (DRAFTS_PREFIX + publishedId) as DraftId\n }\n\n return isDraftId(id) ? id : ((DRAFTS_PREFIX + id) as DraftId)\n}\n\n/** @internal */\nexport function getVersionId(id: string, version: string): string {\n if (version === 'drafts' || version === 'published') {\n throw new Error('Version can not be \"published\" or \"drafts\"')\n }\n\n return `${VERSION_PREFIX}${version}${PATH_SEPARATOR}${getPublishedId(id)}`\n}\n\n/**\n * @internal\n * Given an id, returns the versionId if it exists.\n * e.g. `versions.summer-drop.foo` = `summer-drop`\n * e.g. `drafts.foo` = `undefined`\n * e.g. `foo` = `undefined`\n */\nexport function getVersionFromId(id: string): string | undefined {\n if (!isVersionId(id)) return undefined\n // eslint-disable-next-line unused-imports/no-unused-vars\n const [_versionPrefix, versionId, ..._publishedId] = id.split(PATH_SEPARATOR)\n\n return versionId\n}\n\n/** @internal */\nexport function getPublishedId(id: string): PublishedId {\n if (isVersionId(id)) {\n // make sure to only remove the versions prefix and the bundle name\n return id.split(PATH_SEPARATOR).slice(2).join(PATH_SEPARATOR) as PublishedId as PublishedId\n }\n\n if (isDraftId(id)) {\n return id.slice(DRAFTS_PREFIX.length) as PublishedId\n }\n\n return id as PublishedId\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n","import {isArray} from './isArray'\nimport {isRecord} from './isRecord'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n // Handle Portable Text in a faster way\n if (value._type === 'block' || value._type === 'span') {\n const result = {...value}\n if (value._type === 'block') {\n result.children = walkMap(value.children, mappingFn, path.concat('children'))\n } else if (value._type === 'span') {\n result.text = walkMap(value.text, mappingFn, path.concat('text'))\n }\n return result\n }\n\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {getPublishedId, getVersionFromId, isPublishedId, isVersionId} from './draftUtils'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (isPublishedId(_id)) {\n searchParams.set('perspective', 'published')\n } else if (isVersionId(_id)) {\n const versionId = getVersionFromId(_id)!\n searchParams.set('perspective', versionId)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n"],"names":["studioPath.fromString","studioPath.toString"],"mappings":";AAYA,MAAM,aACJ,oGAEW,eAAe,4BACtB,eAAe;AAGd,SAAS,eAAe,SAAyC;AAC/D,SAAA,OAAO,WAAY,YAAa,OAAO,WAAY,YAAY,YAAY,KAAK,OAAO;AAChG;AAGO,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAK,CAAC,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AAGO,SAAS,aAAa,SAA6C;AACxE,MAAI,OAAO,WAAY,YAAY,aAAa,KAAK,OAAO;AACnD,WAAA;AAGT,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW;AACzC,WAAA;AAGH,QAAA,CAAC,MAAM,EAAE,IAAI;AACX,UAAA,OAAO,QAAS,YAAY,SAAS,QAAQ,OAAO,MAAO,YAAY,OAAO;AACxF;AAGgB,SAAA,IACd,KACA,MACA,YAC4B;AAC5B,QAAM,SAAS,OAAO,QAAS,WAAW,WAAW,IAAI,IAAI;AACzD,MAAA,CAAC,MAAM,QAAQ,MAAM;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AAQ;AAAA,IACnF;AACA,QAAI,CAAC,QAAS;AACd,UAAM,EAAC,KAAK,OAAO,YAAY,SAAY,IAAA;AACpC,WAAA;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM,cAAc,aAAa,UAAU;AAAA,MAC3C,WAAW;AAAA,MACX,SAAS;AAAA,IACX;AAAA,EAAA;AAIJ;AAGO,SAAS,uBAAuB,WAAuC;AAC5E,MAAI,UAAyB,OAAO,aAAc,WAAW,YAAY,UAAU;AAInF,SAHI,YAAY,QACd,UAAU,QAAQ,QAAQ,OAAO,EAAE,IAEjC,OAAO,aAAc,WAChB,EAAC,YAEH,EAAC,GAAG,WAAW,QAAO;AAC/B;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"resolveEditInfo.cjs","sources":["../../src/csm/studioPath.ts","../../src/csm/draftUtils.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/walkMap.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","// nominal/opaque type hack\ntype Opaque<T, K> = T & {__opaqueId__: K}\n\n/** @internal */\nexport type DraftId = Opaque<string, 'draftId'>\n\n/** @internal */\nexport type PublishedId = Opaque<string, 'publishedId'>\n\n/** @internal */\nexport const DRAFTS_FOLDER = 'drafts'\n\n/** @internal */\nexport const VERSION_FOLDER = 'versions'\n\nconst PATH_SEPARATOR = '.'\nconst DRAFTS_PREFIX = `${DRAFTS_FOLDER}${PATH_SEPARATOR}`\nconst VERSION_PREFIX = `${VERSION_FOLDER}${PATH_SEPARATOR}`\n\n/** @internal */\nexport function isDraftId(id: string): id is DraftId {\n return id.startsWith(DRAFTS_PREFIX)\n}\n\n/** @internal */\nexport function isVersionId(id: string): boolean {\n return id.startsWith(VERSION_PREFIX)\n}\n\n/** @internal */\nexport function isPublishedId(id: string): id is PublishedId {\n return !isDraftId(id) && !isVersionId(id)\n}\n\n/** @internal */\nexport function getDraftId(id: string): DraftId {\n if (isVersionId(id)) {\n const publishedId = getPublishedId(id)\n return (DRAFTS_PREFIX + publishedId) as DraftId\n }\n\n return isDraftId(id) ? id : ((DRAFTS_PREFIX + id) as DraftId)\n}\n\n/** @internal */\nexport function getVersionId(id: string, version: string): string {\n if (version === 'drafts' || version === 'published') {\n throw new Error('Version can not be \"published\" or \"drafts\"')\n }\n\n return `${VERSION_PREFIX}${version}${PATH_SEPARATOR}${getPublishedId(id)}`\n}\n\n/**\n * @internal\n * Given an id, returns the versionId if it exists.\n * e.g. `versions.summer-drop.foo` = `summer-drop`\n * e.g. `drafts.foo` = `undefined`\n * e.g. `foo` = `undefined`\n */\nexport function getVersionFromId(id: string): string | undefined {\n if (!isVersionId(id)) return undefined\n // eslint-disable-next-line unused-imports/no-unused-vars\n const [_versionPrefix, versionId, ..._publishedId] = id.split(PATH_SEPARATOR)\n\n return versionId\n}\n\n/** @internal */\nexport function getPublishedId(id: string): PublishedId {\n if (isVersionId(id)) {\n // make sure to only remove the versions prefix and the bundle name\n return id.split(PATH_SEPARATOR).slice(2).join(PATH_SEPARATOR) as PublishedId as PublishedId\n }\n\n if (isDraftId(id)) {\n return id.slice(DRAFTS_PREFIX.length) as PublishedId\n }\n\n return id as PublishedId\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","import {isRecord} from '../util/isRecord'\nimport {isArray} from './isArray'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n // Handle Portable Text in a faster way\n if (value._type === 'block' || value._type === 'span') {\n const result = {...value}\n if (value._type === 'block') {\n result.children = walkMap(value.children, mappingFn, path.concat('children'))\n } else if (value._type === 'span') {\n result.text = walkMap(value.text, mappingFn, path.concat('text'))\n }\n return result\n }\n\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {getPublishedId, getVersionFromId, isPublishedId, isVersionId} from './draftUtils'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (isPublishedId(_id)) {\n searchParams.set('perspective', 'published')\n } else if (isVersionId(_id)) {\n const versionId = getVersionFromId(_id)!\n searchParams.set('perspective', versionId)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n"],"names":["studioPath.fromString","isRecord","studioPath.toString"],"mappings":";;AAYA,MAAM,aACJ,oGAEW,eAAe,4BACtB,eAAe;AAGd,SAAS,eAAe,SAAyC;AAC/D,SAAA,OAAO,WAAY,YAAa,OAAO,WAAY,YAAY,YAAY,KAAK,OAAO;AAChG;AAGO,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAK,CAAC,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AAGO,SAAS,aAAa,SAA6C;AACxE,MAAI,OAAO,WAAY,YAAY,aAAa,KAAK,OAAO;AACnD,WAAA;AAGT,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW;AACzC,WAAA;AAGH,QAAA,CAAC,MAAM,EAAE,IAAI;AACX,UAAA,OAAO,QAAS,YAAY,SAAS,QAAQ,OAAO,MAAO,YAAY,OAAO;AACxF;AAGgB,SAAA,IACd,KACA,MACA,YAC4B;AAC5B,QAAM,SAAS,OAAO,QAAS,WAAW,WAAW,IAAI,IAAI;AACzD,MAAA,CAAC,MAAM,QAAQ,MAAM;AACjB,UAAA,IAAI,MAAM,mCAAmC;AAGrD,MAAI,MAA2B;AAC/B,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AAChC,UAAA,UAAU,OAAO,CAAC;AACpB,Q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AAa,UAAU;AAAA,MAC3C,WAAW;AAAA,MACX,SAAS;AAAA,IACX;AAAA,EAAA;AAIJ;AAGO,SAAS,uBAAuB,WAAuC;AAC5E,MAAI,UAAyB,OAAO,aAAc,WAAW,YAAY,UAAU;AAInF,SAHI,YAAY,QACd,UAAU,QAAQ,QAAQ,OAAO,EAAE,IAEjC,OAAO,aAAc,WAChB,EAAC,YAEH,EAAC,GAAG,WAAW,QAAO;AAC/B;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
function isRecord(value) {
|
|
3
|
+
return typeof value == "object" && value !== null && !Array.isArray(value);
|
|
4
|
+
}
|
|
2
5
|
var s = { 0: 8203, 1: 8204, 2: 8205, 3: 8290, 4: 8291, 5: 8288, 6: 65279, 7: 8289, 8: 119155, 9: 119156, a: 119157, b: 119158, c: 119159, d: 119160, e: 119161, f: 119162 }, c = { 0: 8203, 1: 8204, 2: 8205, 3: 65279 }, u = new Array(4).fill(String.fromCodePoint(c[0])).join("");
|
|
3
6
|
function E(t) {
|
|
4
7
|
let e = JSON.stringify(t);
|
|
@@ -37,6 +40,7 @@ function stegaClean(result) {
|
|
|
37
40
|
}
|
|
38
41
|
const vercelStegaCleanAll = stegaClean;
|
|
39
42
|
exports.C = C;
|
|
43
|
+
exports.isRecord = isRecord;
|
|
40
44
|
exports.stegaClean = stegaClean;
|
|
41
45
|
exports.vercelStegaCleanAll = vercelStegaCleanAll;
|
|
42
46
|
//# sourceMappingURL=stegaClean.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stegaClean.cjs","sources":["../../node_modules/@vercel/stega/dist/index.mjs","../../src/stega/stegaClean.ts"],"sourcesContent":["var s={0:8203,1:8204,2:8205,3:8290,4:8291,5:8288,6:65279,7:8289,8:119155,9:119156,a:119157,b:119158,c:119159,d:119160,e:119161,f:119162},c={0:8203,1:8204,2:8205,3:65279},u=new Array(4).fill(String.fromCodePoint(c[0])).join(\"\"),m=String.fromCharCode(0);function E(t){let e=JSON.stringify(t);return`${u}${Array.from(e).map(r=>{let n=r.charCodeAt(0);if(n>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);return Array.from(n.toString(4).padStart(4,\"0\")).map(o=>String.fromCodePoint(c[o])).join(\"\")}).join(\"\")}`}function y(t){let e=JSON.stringify(t);return Array.from(e).map(r=>{let n=r.charCodeAt(0);if(n>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);return Array.from(n.toString(16).padStart(2,\"0\")).map(o=>String.fromCodePoint(s[o])).join(\"\")}).join(\"\")}function I(t){return!Number.isNaN(Number(t))||/[a-z]/i.test(t)&&!/\\d+(?:[-:\\/]\\d+){2}(?:T\\d+(?:[-:\\/]\\d+){1,2}(\\.\\d+)?Z?)?/.test(t)?!1:Boolean(Date.parse(t))}function T(t){try{new URL(t,t.startsWith(\"/\")?\"https://acme.com\":void 0)}catch{return!1}return!0}function C(t,e,r=\"auto\"){return r===!0||r===\"auto\"&&(I(t)||T(t))?t:`${t}${E(e)}`}var x=Object.fromEntries(Object.entries(c).map(t=>t.reverse())),g=Object.fromEntries(Object.entries(s).map(t=>t.reverse())),S=`${Object.values(s).map(t=>`\\\\u{${t.toString(16)}}`).join(\"\")}`,f=new RegExp(`[${S}]{4,}`,\"gu\");function G(t){let e=t.match(f);if(!!e)return h(e[0],!0)[0]}function $(t){let e=t.match(f);if(!!e)return e.map(r=>h(r)).flat()}function h(t,e=!1){let r=Array.from(t);if(r.length%2===0){if(r.length%4||!t.startsWith(u))return A(r,e)}else throw new Error(\"Encoded data has invalid length\");let n=[];for(let o=r.length*.25;o--;){let p=r.slice(o*4,o*4+4).map(d=>x[d.codePointAt(0)]).join(\"\");n.unshift(String.fromCharCode(parseInt(p,4)))}if(e){n.shift();let o=n.indexOf(m);return o===-1&&(o=n.length),[JSON.parse(n.slice(0,o).join(\"\"))]}return n.join(\"\").split(m).filter(Boolean).map(o=>JSON.parse(o))}function A(t,e){var d;let r=[];for(let i=t.length*.5;i--;){let a=`${g[t[i*2].codePointAt(0)]}${g[t[i*2+1].codePointAt(0)]}`;r.unshift(String.fromCharCode(parseInt(a,16)))}let n=[],o=[r.join(\"\")],p=10;for(;o.length;){let i=o.shift();try{if(n.push(JSON.parse(i)),e)return n}catch(a){if(!p--)throw a;let l=+((d=a.message.match(/\\sposition\\s(\\d+)$/))==null?void 0:d[1]);if(!l)throw a;o.unshift(i.substring(0,l),i.substring(l))}}return n}function _(t){var e;return{cleaned:t.replace(f,\"\"),encoded:((e=t.match(f))==null?void 0:e[0])||\"\"}}function O(t){return t&&JSON.parse(_(JSON.stringify(t)).cleaned)}export{f as VERCEL_STEGA_REGEX,y as legacyStegaEncode,O as vercelStegaClean,C as vercelStegaCombine,G as vercelStegaDecode,$ as vercelStegaDecodeAll,E as vercelStegaEncode,_ as vercelStegaSplit};\n","import {vercelStegaClean} from '@vercel/stega'\n\n/**\n * Can take a `result` JSON from a `const {result} = client.fetch(query, params, {filterResponse: false})`\n * and remove all stega-encoded data from it.\n * @public\n */\nexport function stegaClean<Result = unknown>(result: Result): Result {\n return vercelStegaClean<Result>(result)\n}\n\n/**\n * Can take a `result` JSON from a `const {result} = client.fetch(query, params, {filterResponse: false})`\n * and remove all stega-encoded data from it.\n * @alpha\n * @deprecated Use `stegaClean` instead\n */\nexport const vercelStegaCleanAll = stegaClean\n"],"names":["vercelStegaClean"],"mappings":";
|
|
1
|
+
{"version":3,"file":"stegaClean.cjs","sources":["../../src/util/isRecord.ts","../../node_modules/@vercel/stega/dist/index.mjs","../../src/stega/stegaClean.ts"],"sourcesContent":["/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","var s={0:8203,1:8204,2:8205,3:8290,4:8291,5:8288,6:65279,7:8289,8:119155,9:119156,a:119157,b:119158,c:119159,d:119160,e:119161,f:119162},c={0:8203,1:8204,2:8205,3:65279},u=new Array(4).fill(String.fromCodePoint(c[0])).join(\"\"),m=String.fromCharCode(0);function E(t){let e=JSON.stringify(t);return`${u}${Array.from(e).map(r=>{let n=r.charCodeAt(0);if(n>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);return Array.from(n.toString(4).padStart(4,\"0\")).map(o=>String.fromCodePoint(c[o])).join(\"\")}).join(\"\")}`}function y(t){let e=JSON.stringify(t);return Array.from(e).map(r=>{let n=r.charCodeAt(0);if(n>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);return Array.from(n.toString(16).padStart(2,\"0\")).map(o=>String.fromCodePoint(s[o])).join(\"\")}).join(\"\")}function I(t){return!Number.isNaN(Number(t))||/[a-z]/i.test(t)&&!/\\d+(?:[-:\\/]\\d+){2}(?:T\\d+(?:[-:\\/]\\d+){1,2}(\\.\\d+)?Z?)?/.test(t)?!1:Boolean(Date.parse(t))}function T(t){try{new URL(t,t.startsWith(\"/\")?\"https://acme.com\":void 0)}catch{return!1}return!0}function C(t,e,r=\"auto\"){return r===!0||r===\"auto\"&&(I(t)||T(t))?t:`${t}${E(e)}`}var x=Object.fromEntries(Object.entries(c).map(t=>t.reverse())),g=Object.fromEntries(Object.entries(s).map(t=>t.reverse())),S=`${Object.values(s).map(t=>`\\\\u{${t.toString(16)}}`).join(\"\")}`,f=new RegExp(`[${S}]{4,}`,\"gu\");function G(t){let e=t.match(f);if(!!e)return h(e[0],!0)[0]}function $(t){let e=t.match(f);if(!!e)return e.map(r=>h(r)).flat()}function h(t,e=!1){let r=Array.from(t);if(r.length%2===0){if(r.length%4||!t.startsWith(u))return A(r,e)}else throw new Error(\"Encoded data has invalid length\");let n=[];for(let o=r.length*.25;o--;){let p=r.slice(o*4,o*4+4).map(d=>x[d.codePointAt(0)]).join(\"\");n.unshift(String.fromCharCode(parseInt(p,4)))}if(e){n.shift();let o=n.indexOf(m);return o===-1&&(o=n.length),[JSON.parse(n.slice(0,o).join(\"\"))]}return n.join(\"\").split(m).filter(Boolean).map(o=>JSON.parse(o))}function A(t,e){var d;let r=[];for(let i=t.length*.5;i--;){let a=`${g[t[i*2].codePointAt(0)]}${g[t[i*2+1].codePointAt(0)]}`;r.unshift(String.fromCharCode(parseInt(a,16)))}let n=[],o=[r.join(\"\")],p=10;for(;o.length;){let i=o.shift();try{if(n.push(JSON.parse(i)),e)return n}catch(a){if(!p--)throw a;let l=+((d=a.message.match(/\\sposition\\s(\\d+)$/))==null?void 0:d[1]);if(!l)throw a;o.unshift(i.substring(0,l),i.substring(l))}}return n}function _(t){var e;return{cleaned:t.replace(f,\"\"),encoded:((e=t.match(f))==null?void 0:e[0])||\"\"}}function O(t){return t&&JSON.parse(_(JSON.stringify(t)).cleaned)}export{f as VERCEL_STEGA_REGEX,y as legacyStegaEncode,O as vercelStegaClean,C as vercelStegaCombine,G as vercelStegaDecode,$ as vercelStegaDecodeAll,E as vercelStegaEncode,_ as vercelStegaSplit};\n","import {vercelStegaClean} from '@vercel/stega'\n\n/**\n * Can take a `result` JSON from a `const {result} = client.fetch(query, params, {filterResponse: false})`\n * and remove all stega-encoded data from it.\n * @public\n */\nexport function stegaClean<Result = unknown>(result: Result): Result {\n return vercelStegaClean<Result>(result)\n}\n\n/**\n * Can take a `result` JSON from a `const {result} = client.fetch(query, params, {filterResponse: false})`\n * and remove all stega-encoded data from it.\n * @alpha\n * @deprecated Use `stegaClean` instead\n */\nexport const vercelStegaCleanAll = stegaClean\n"],"names":["vercelStegaClean"],"mappings":";AACO,SAAS,SAAS,OAAkD;AAClE,SAAA,OAAO,SAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;ACHG,IAAC,IAAE,EAAC,GAAE,MAAK,GAAE,MAAK,GAAE,MAAK,GAAE,MAAK,GAAE,MAAK,GAAE,MAAK,GAAE,OAAM,GAAE,MAAK,GAAE,QAAO,GAAE,QAAO,GAAE,QAAO,G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AE,CAAC;AAAI,OAAO,YAAY,OAAO,QAAQ,CAAC,EAAE,IAAI,OAAG,EAAE,QAAS,CAAA,CAAC;AAAC,IAAC,IAAE,GAAG,OAAO,OAAO,CAAC,EAAE,IAAI,OAAG,OAAO,EAAE,SAAS,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,IAAG,IAAE,IAAI,OAAO,IAAI,CAAC,SAAQ,IAAI;AAAugC,SAAS,EAAE,GAAE;AAAC,MAAI;AAAE,SAAM,EAAC,SAAQ,EAAE,QAAQ,GAAE,EAAE,GAAE,WAAU,IAAE,EAAE,MAAM,CAAC,MAAI,OAAK,SAAO,EAAE,CAAC,MAAI,GAAE;AAAC;AAAC,SAAS,EAAE,GAAE;AAAC,SAAO,KAAG,KAAK,MAAM,EAAE,KAAK,UAAU,CAAC,CAAC,EAAE,OAAO;AAAC;ACO1kF,SAAS,WAA6B,QAAwB;AACnE,SAAOA,EAAyB,MAAM;AACxC;AAQO,MAAM,sBAAsB;;;;;","x_google_ignoreList":[1]}
|
|
@@ -104,20 +104,17 @@ function resolveMapping(resultPath, csm) {
|
|
|
104
104
|
function isArray(value) {
|
|
105
105
|
return value !== null && Array.isArray(value);
|
|
106
106
|
}
|
|
107
|
-
function isRecord(value) {
|
|
108
|
-
return typeof value == "object" && value !== null;
|
|
109
|
-
}
|
|
110
107
|
function walkMap(value, mappingFn, path = []) {
|
|
111
108
|
if (isArray(value))
|
|
112
109
|
return value.map((v, idx) => {
|
|
113
|
-
if (isRecord(v)) {
|
|
110
|
+
if (stegaClean.isRecord(v)) {
|
|
114
111
|
const _key = v._key;
|
|
115
112
|
if (typeof _key == "string")
|
|
116
113
|
return walkMap(v, mappingFn, path.concat({ _key, _index: idx }));
|
|
117
114
|
}
|
|
118
115
|
return walkMap(v, mappingFn, path.concat(idx));
|
|
119
116
|
});
|
|
120
|
-
if (isRecord(value)) {
|
|
117
|
+
if (stegaClean.isRecord(value)) {
|
|
121
118
|
if (value._type === "block" || value._type === "span") {
|
|
122
119
|
const result = { ...value };
|
|
123
120
|
return value._type === "block" ? result.children = walkMap(value.children, mappingFn, path.concat("children")) : value._type === "span" && (result.text = walkMap(value.text, mappingFn, path.concat("text"))), result;
|