@uniformdev/canvas-contentful 12.0.1-alpha.94 → 12.2.1-alpha.121

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.txt CHANGED
@@ -1,2 +1,2 @@
1
- © 2021 Uniform Systems, Inc. All Rights Reserved.
1
+ © 2021 Uniform Systems, Inc. All Rights Reserved.
2
2
  See details of Uniform Systems, Inc. Master Subscription Agreement here: https://uniform.dev/eula
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- Contentful data enhancers for Uniform Canvas
2
-
3
- part of the [Uniform Platform](https://uniform.app). See our [documentation](https://docs.uniform.app) for more details.
1
+ Contentful data enhancers for Uniform Canvas
2
+
3
+ part of the [Uniform Platform](https://uniform.app). See our [documentation](https://docs.uniform.app) for more details.
@@ -0,0 +1,140 @@
1
+ import { EnhancerContext, ComponentParameter, ComponentInstance, LimitPolicy, ComponentParameterEnhancer, ComponentParameterEnhancerFunction } from '@uniformdev/canvas';
2
+ import { ContentfulClientApi, Sys } from 'contentful';
3
+
4
+ interface AddClientArgs {
5
+ /**
6
+ * The Contentful source public ID that this client maps to in the composition data.
7
+ * This is used to enable multiple Contentful spaces/environments as data sources.
8
+ * If unspecified, the client will be the default source that is used when no source public ID
9
+ * is in the data, or the source ID is 'default'.
10
+ */
11
+ source?: string;
12
+ /** The Contentful client instance to use when fetching published data */
13
+ client: ContentfulClientApi;
14
+ /**
15
+ * The Contentful client instance to use when fetching preview data.
16
+ * If the preview client is not passed, it defaults to the client.
17
+ */
18
+ previewClient?: ContentfulClientApi;
19
+ }
20
+ declare class ContentfulClientList {
21
+ private _clients;
22
+ constructor(clients?: AddClientArgs[] | AddClientArgs);
23
+ addClient({ source, client, previewClient }: AddClientArgs): void;
24
+ getClient({ source, isPreviewClient, }: {
25
+ source?: string;
26
+ isPreviewClient?: boolean;
27
+ }): ContentfulClientApi | undefined;
28
+ }
29
+
30
+ /** The default shape of the Contentful entry. Note that this can change if the query is altered. */
31
+ declare type ContentfulEntryResult<TFields> = {
32
+ /**
33
+ * The shape of the `fields` that the Contentful REST API is expected to return for this entry
34
+ * https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entry
35
+ *
36
+ * These should line up with the fields in your content model(s) that are allowed for this component.
37
+ */
38
+ fields: TFields;
39
+ /** System fields returned by the Contentful API. If you modify the query parameters to fetch more than fields, you may get more sys data than this. */
40
+ sys: Partial<Pick<Sys, 'id' | 'type'>>;
41
+ };
42
+
43
+ declare type EntrySelectorParameterValue = {
44
+ entryId: string;
45
+ source?: string;
46
+ } | string | null | undefined;
47
+ declare type CreateContentfulQueryOptions<TContext extends EnhancerContext = EnhancerContext> = {
48
+ /** Canvas parameter name being queried for. Not defined if using batching. */
49
+ parameterName?: string;
50
+ /** Canvas parameter value being fetched. Not defined if using batching. */
51
+ parameter?: ComponentParameter<EntrySelectorParameterValue>;
52
+ /** Component containing the parameter being fetched. Not defined if using batching. */
53
+ component?: ComponentInstance;
54
+ /** The default Contentful query expression (select fields + include 1 layer of references) */
55
+ defaultQuery: any;
56
+ /** The enhancer context provided to the enhance() function */
57
+ context: TContext;
58
+ };
59
+ /** The default shape of the result value of the Contentful enhancer. Note that this can change if the query is altered. */
60
+ declare type ContentfulEnhancerResult<TFields> = ContentfulEntryResult<TFields> | null;
61
+ declare type CreateContentfulEnhancerOptions = {
62
+ /** Either a list of Contentful clients for use with multi-space/environment-enabled Canvas projects.
63
+ * Or a single Contentful client for use with legacy Canvas data.*/
64
+ client: ContentfulClientApi | ContentfulClientList;
65
+ /** @deprecated Contentful client instance to use for fetching preview content.
66
+ * This client is _only_ relevant when the `client` property is a single Contentful client intended for use with
67
+ * legacy Canvas data. Conversely, if you use a `ContentfulClientList` for the `client` property, any value for `previewClient`
68
+ * will be ignored. To avoid deprecated use, you should switch to using a `ContentfulClientList` for the `client` property. */
69
+ previewClient?: ContentfulClientApi;
70
+ /** Creates the Contentful client's query params for specific parameters. See https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters */
71
+ createQuery?: (options: CreateContentfulQueryOptions) => any | undefined;
72
+ useBatching?: boolean;
73
+ limitPolicy?: LimitPolicy;
74
+ };
75
+ declare const CANVAS_CONTENTFUL_PARAMETER_TYPES: readonly string[];
76
+ declare function createContentfulEnhancer({ client, previewClient, createQuery, useBatching, limitPolicy, }: CreateContentfulEnhancerOptions): ComponentParameterEnhancer<EntrySelectorParameterValue, ContentfulEnhancerResult<unknown>>;
77
+
78
+ declare type ContentfulMultiEntryParameterValue = {
79
+ entries: string[];
80
+ source: string;
81
+ } | null | undefined;
82
+ declare type CreateContentfulMultiEntryQueryOptions<TContext extends EnhancerContext = EnhancerContext> = {
83
+ /** Canvas parameter name being queried for */
84
+ parameterName: string;
85
+ /** Canvas parameter value being fetched */
86
+ parameter: ComponentParameter<ContentfulMultiEntryParameterValue>;
87
+ /** Component containing the parameter being fetched */
88
+ component: ComponentInstance;
89
+ /** The default Contentful query expression (select fields + include 1 layer of references) */
90
+ defaultQuery: any;
91
+ /** The enhancer context provided to the enhance() function */
92
+ context: TContext;
93
+ };
94
+ /** The default shape of the result value of the Contentful Multi Entry enhancer. Note that this can change if the query is altered. */
95
+ declare type ContentfulMultiEntryEnhancerResult<TFields> = ContentfulEntryResult<TFields>[] | null;
96
+ declare type CreateContentfulMultiEntryEnhancerOptions = {
97
+ /** Either a list of Contentful clients for use with multi-space/environment-enabled Canvas projects. */
98
+ clients: ContentfulClientList;
99
+ /** Creates the Contentful client's query params for specific parameters. See https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters */
100
+ createQuery?: (options: CreateContentfulMultiEntryQueryOptions) => any | undefined;
101
+ limitPolicy?: LimitPolicy;
102
+ };
103
+ declare const CANVAS_CONTENTFUL_MULTI_PARAMETER_TYPES: readonly string[];
104
+ declare function createContentfulMultiEnhancer({ clients, createQuery, limitPolicy, }: CreateContentfulMultiEntryEnhancerOptions): ComponentParameterEnhancer<ContentfulMultiEntryParameterValue, ContentfulMultiEntryEnhancerResult<unknown>>;
105
+
106
+ declare const CANVAS_CONTENTFUL_QUERY_PARAMETER_TYPES: readonly string[];
107
+ declare type ContentfulQueryParameterValue = {
108
+ source: string;
109
+ contentType: string;
110
+ count: number;
111
+ sortBy?: string;
112
+ sortOrder?: 'asc' | 'desc';
113
+ } | null | undefined;
114
+ /** The default shape of the result value of the Contentful Query enhancer. Note that this can change if the query is altered. */
115
+ declare type ContentfulQueryEnhancerResult<TFields> = ContentfulEntryResult<TFields>[] | null;
116
+ declare type CreateContentfulQueryApiQueryOptions<TContext extends EnhancerContext = EnhancerContext> = {
117
+ /** Canvas parameter name being queried for */
118
+ parameterName: string;
119
+ /** Canvas parameter value being fetched */
120
+ parameter: ComponentParameter<ContentfulQueryParameterValue>;
121
+ /** Component containing the parameter being fetched */
122
+ component: ComponentInstance;
123
+ /** The default Contentful query expression (select fields + include 1 layer of references) */
124
+ defaultQuery: any;
125
+ /** The enhancer context provided to the enhance() function */
126
+ context: TContext;
127
+ };
128
+ declare type CreateContentfulQueryEnhancerOptions = {
129
+ /** Either a list of Contentful clients for use with multi-space/environment-enabled Canvas projects. */
130
+ clients: ContentfulClientList;
131
+ /** Creates the Contentful client's query params for specific parameters. See https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters */
132
+ createQuery?: (options: CreateContentfulQueryApiQueryOptions) => any | undefined;
133
+ limitPolicy?: LimitPolicy;
134
+ };
135
+ declare function createContentfulQueryEnhancer({ clients, createQuery, limitPolicy, }: CreateContentfulQueryEnhancerOptions): ComponentParameterEnhancer<ContentfulQueryParameterValue, ContentfulQueryEnhancerResult<unknown>>;
136
+
137
+ declare type EnhancerValue = ContentfulEntryResult<unknown> | ContentfulEntryResult<unknown>[] | null;
138
+ declare const contentfulRichTextToHtmlEnhancer: ComponentParameterEnhancerFunction<EnhancerValue>;
139
+
140
+ export { AddClientArgs, CANVAS_CONTENTFUL_MULTI_PARAMETER_TYPES, CANVAS_CONTENTFUL_PARAMETER_TYPES, CANVAS_CONTENTFUL_QUERY_PARAMETER_TYPES, ContentfulClientList, ContentfulEnhancerResult, ContentfulMultiEntryEnhancerResult, ContentfulMultiEntryParameterValue, ContentfulQueryEnhancerResult, ContentfulQueryParameterValue, CreateContentfulEnhancerOptions, CreateContentfulMultiEntryEnhancerOptions, CreateContentfulMultiEntryQueryOptions, CreateContentfulQueryApiQueryOptions, CreateContentfulQueryEnhancerOptions, CreateContentfulQueryOptions, EntrySelectorParameterValue, contentfulRichTextToHtmlEnhancer, createContentfulEnhancer, createContentfulMultiEnhancer, createContentfulQueryEnhancer };
@@ -0,0 +1 @@
1
+ import{createBatchEnhancer as S,UniqueBatchEntries as _}from"@uniformdev/canvas";var L=class{constructor(t){this._clients={},Array.isArray(t)?t.forEach(n=>this.addClient(n)):t&&this.addClient(t)}addClient({source:t="default",client:n,previewClient:o}){if(this._clients[t])throw new Error(`The source ${t} is always registered`);if(!n)throw new Error("You must provide a Contentful client for the ContentfulClientList");this._clients[t]={client:n,previewClient:o||n}}getClient({source:t="default",isPreviewClient:n}){let o=this._clients[t];if(!!o)return n?o.previewClient:o.client}};import{createLimitPolicy as Q}from"@uniformdev/canvas";var x=Q({throttle:{limit:55,interval:1e3}});function P(e){return typeof e=="string"?e:typeof e=="object"&&e&&"error"in e?e.error:e instanceof Error?e.toString():JSON.stringify(e,null,2)}function V(e,t){if(!!e)return`${t==="desc"?"-":""}${e}`}function T({clients:e,parameterValue:t,parameterName:n,component:o,context:g}){let{source:i="default"}=t,a=e.getClient({source:i,isPreviewClient:g.preview});if(!a)throw new Error(`No Contentful client could be resolved for source key '${i}' referenced in parameter '${n} in component '${o.type}'. Ensure that the 'clients' property you are passing to the enhancer has a client instance registered for the source key.`);return a}var $={select:"fields",include:1},k=Object.freeze(["contentfulEntry"]);function j(e){return e instanceof L}function se({client:e,previewClient:t,createQuery:n,useBatching:o,limitPolicy:g}){if(!e)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the `client` or `clients` property.");let a=(()=>{if(j(e))return e;let s=new L;return s.addClient({client:e,previewClient:t}),s})(),y=g||x;return o?S({handleBatch:async s=>{var c;let l=s.reduce((u,r)=>{let{parameter:f,parameterName:C,component:h,context:m}=r.args,d=f.value;if(!R(d))return u;let E=b({parameterValue:d,parameterName:C,clients:a,component:h,context:m}),p="";if(A(d))p="legacy-group";else{let{source:I="default"}=d;p=I}return u[p]&&Array.isArray(u[p].tasks)?u[p].tasks.push(r):u[p]={client:E,tasks:[r]},u},{});try{console.time("fetch all entries");for await(let[u,r]of Object.entries(l)){let{context:f,component:C}=r.tasks[0].args,h=(c=n==null?void 0:n({component:C,defaultQuery:{...$},context:f}))!=null?c:$,m=new _(r.tasks,E=>A(E.parameter.value)?E.parameter.value:E.parameter.value.entryId),d=Object.keys(m.groups);console.time(`fetch entries ${u}`);try{(await r.client.getEntries({"sys.id[in]":d.join(","),limit:d.length,...h})).items.forEach(p=>{m.resolveKey(p.sys.id,p)}),m.resolveRemaining(null)}finally{console.timeEnd(`fetch entries ${u}`)}}console.timeEnd("fetch all entries")}catch(u){let r=P(u),f=new Error(`Failed loading Contentful entries batch (${s.length}) ${r}`);s.forEach(C=>C.reject(f))}},shouldQueue:({parameter:s})=>O(s),limitPolicy:y}):{enhanceOne:async function({parameter:l,parameterName:c,component:u,context:r}){var f,C;if(O(l)){if(!R(l.value))return null;let h=b({clients:a,parameterName:c,parameterValue:l.value,component:u,context:r}),m=A(l.value)?l.value:l.value.entryId,d=(f=n==null?void 0:n({parameter:l,parameterName:c,component:u,defaultQuery:{...$},context:r}))!=null?f:$;try{return console.time(`fetch entry ${m}`),await h.getEntry(m,d)}catch(E){let p=P(E);throw A(l.value)?new Error(`Failed loading Contentful entry '${l.value}' referenced in parameter '${c}': ${p}`):new Error(`Failed loading Contentful entry '${m}' from source '${(C=l.value.source)!=null?C:"default"}' referenced in parameter '${c}': ${p}`)}finally{console.timeEnd(`fetch entry ${m}`)}}},limitPolicy:y}}function O(e){var t;return e.type===k[0]&&(((t=e.value)==null?void 0:t.entryId)||typeof e.value=="string")}function A(e){return typeof e=="string"}function R(e){return!(!e||!A(e)&&!e.entryId)}function b({clients:e,parameterValue:t,parameterName:n,component:o,context:g}){if(A(t)){let y=e.getClient({isPreviewClient:g.preview});if(!y)throw new Error(`Parameter '${n}' in component '${o.type}' has a value '${t}' that is not compatible with multi-space/environment usage. If you wish to use multiple spaces/environments, you must convert your Canvas component parameters to the multi-space/environment compatible version. Otherwise, you can continue to use your parameters as-is, but must specify one of the clients provided to the Contentful enhancer as the 'default' client by registering it without specifying a source key.`);return y}let{source:i="default"}=t,a=e.getClient({source:i,isPreviewClient:g.preview});if(!a)throw new Error(`No Contentful client could be resolved for source key '${i}' referenced in parameter '${n} in component '${o.type}'. Ensure that the 'clients' property you are passing to the enhancer has a client instance registered for the source key.`);return a}var F={select:"fields",include:1},Y=Object.freeze(["contentfulMultiEntry"]);function Ce({clients:e,createQuery:t,limitPolicy:n}){if(!e)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the ContentfulClientList.");return{enhanceOne:async function({parameter:i,parameterName:a,component:y,context:s}){var l,c;if(B(i)){if(!U(i.value))return null;let u=T({clients:e,parameterName:a,parameterValue:i.value,component:y,context:s}),r=i.value.entries,f=(l=t==null?void 0:t({parameter:i,parameterName:a,component:y,defaultQuery:{...F},context:s}))!=null?l:F;try{return console.time(`fetch entries ${r.join()}`),(await u.getEntries({"sys.id[in]":r.join(),limit:r.length,...f})).items}catch(C){let h=P(C);throw new Error(`Failed loading Contentful entries '${r.join()}' from source '${(c=i.value.source)!=null?c:"default"}' referenced in parameter '${a}': ${h}`)}finally{console.timeEnd(`fetch entries ${r.join()}`)}}},limitPolicy:n||x}}function B(e){return e.type===Y[0]}function U(e){var t;return!(!e||!((t=e.entries)==null?void 0:t.length))}var q=Object.freeze(["contentfulQuery"]),M={select:"fields",include:1};function ye({clients:e,createQuery:t,limitPolicy:n}){if(!e)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the ContentfulClientList.");return{enhanceOne:async function({parameter:i,parameterName:a,component:y,context:s}){var l,c;if(D(i)){if(!z(i.value))return null;let u=T({clients:e,parameterName:a,parameterValue:i.value,component:y,context:s}),r=i.value,f=K(r.count),C=(l=t==null?void 0:t({parameter:i,parameterName:a,component:y,defaultQuery:{...M},context:s}))!=null?l:M,h=`fetch query: ${f} entries with '${r.contentType}' content type`;try{return console.time(h),(await u.getEntries({content_type:r.contentType,order:V(r.sortBy,r.sortOrder),limit:f,...C})).items}catch(m){let d=P(m);throw new Error(`Failed loading Contentful entries with '${r.contentType}' content type from source '${(c=r.source)!=null?c:"default"}' referenced in parameter '${a}': ${d}`)}finally{console.timeEnd(h)}}},limitPolicy:n||x}}function D(e){return e.type===q[0]}function z(e){return!(!e||!e.source||!e.contentType||typeof e.count=="undefined")}function K(e){return!e||e<1?1:e>1e3?1e3:e}import{documentToHtmlString as G}from"@contentful/rich-text-html-renderer";var Ee=({parameter:e})=>{let t=e.value;if(!t)return t;if(!H(t))return N(t),t;for(let n of t)N(n);return t};function N(e){var t;typeof(e==null?void 0:e.fields)=="object"&&Object.entries((t=e.fields)!=null?t:{}).forEach(([n,o])=>{typeof o=="object"&&"nodeType"in o&&o.nodeType==="document"&&(e.fields[n]=G(o))})}function H(e){return Array.isArray(e)}export{Y as CANVAS_CONTENTFUL_MULTI_PARAMETER_TYPES,k as CANVAS_CONTENTFUL_PARAMETER_TYPES,q as CANVAS_CONTENTFUL_QUERY_PARAMETER_TYPES,L as ContentfulClientList,Ee as contentfulRichTextToHtmlEnhancer,se as createContentfulEnhancer,Ce as createContentfulMultiEnhancer,ye as createContentfulQueryEnhancer};
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ var V=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var D=e=>V(e,"__esModule",{value:!0});var z=(e,t)=>{for(var n in t)V(e,n,{get:t[n],enumerable:!0})},K=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of U(t))!q.call(e,c)&&(n||c!=="default")&&V(e,c,{get:()=>t[c],enumerable:!(o=B(t,c))||o.enumerable});return e};var G=(e=>(t,n)=>e&&e.get(t)||(n=K(D({}),t,1),e&&e.set(t,n),n))(typeof WeakMap!="undefined"?new WeakMap:0);var le={};z(le,{CANVAS_CONTENTFUL_MULTI_PARAMETER_TYPES:()=>Q,CANVAS_CONTENTFUL_PARAMETER_TYPES:()=>b,CANVAS_CONTENTFUL_QUERY_PARAMETER_TYPES:()=>S,ContentfulClientList:()=>A,contentfulRichTextToHtmlEnhancer:()=>oe,createContentfulEnhancer:()=>J,createContentfulMultiEnhancer:()=>W,createContentfulQueryEnhancer:()=>ee});var T=require("@uniformdev/canvas");var A=class{constructor(t){this._clients={},Array.isArray(t)?t.forEach(n=>this.addClient(n)):t&&this.addClient(t)}addClient({source:t="default",client:n,previewClient:o}){if(this._clients[t])throw new Error(`The source ${t} is always registered`);if(!n)throw new Error("You must provide a Contentful client for the ContentfulClientList");this._clients[t]={client:n,previewClient:o||n}}getClient({source:t="default",isPreviewClient:n}){let o=this._clients[t];if(!!o)return n?o.previewClient:o.client}};var O=require("@uniformdev/canvas"),w=(0,O.createLimitPolicy)({throttle:{limit:55,interval:1e3}});function P(e){return typeof e=="string"?e:typeof e=="object"&&e&&"error"in e?e.error:e instanceof Error?e.toString():JSON.stringify(e,null,2)}function R(e,t){if(!!e)return`${t==="desc"?"-":""}${e}`}function L({clients:e,parameterValue:t,parameterName:n,component:o,context:c}){let{source:i="default"}=t,a=e.getClient({source:i,isPreviewClient:c.preview});if(!a)throw new Error(`No Contentful client could be resolved for source key '${i}' referenced in parameter '${n} in component '${o.type}'. Ensure that the 'clients' property you are passing to the enhancer has a client instance registered for the source key.`);return a}var $={select:"fields",include:1},b=Object.freeze(["contentfulEntry"]);function H(e){return e instanceof A}function J({client:e,previewClient:t,createQuery:n,useBatching:o,limitPolicy:c}){if(!e)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the `client` or `clients` property.");let a=(()=>{if(H(e))return e;let s=new A;return s.addClient({client:e,previewClient:t}),s})(),d=c||w;return o?(0,T.createBatchEnhancer)({handleBatch:async s=>{var f;let l=s.reduce((u,r)=>{let{parameter:C,parameterName:m,component:E,context:p}=r.args,h=C.value;if(!M(h))return u;let g=N({parameterValue:h,parameterName:m,clients:a,component:E,context:p}),y="";if(x(h))y="legacy-group";else{let{source:Y="default"}=h;y=Y}return u[y]&&Array.isArray(u[y].tasks)?u[y].tasks.push(r):u[y]={client:g,tasks:[r]},u},{});try{console.time("fetch all entries");for await(let[u,r]of Object.entries(l)){let{context:C,component:m}=r.tasks[0].args,E=(f=n==null?void 0:n({component:m,defaultQuery:{...$},context:C}))!=null?f:$,p=new T.UniqueBatchEntries(r.tasks,g=>x(g.parameter.value)?g.parameter.value:g.parameter.value.entryId),h=Object.keys(p.groups);console.time(`fetch entries ${u}`);try{(await r.client.getEntries({"sys.id[in]":h.join(","),limit:h.length,...E})).items.forEach(y=>{p.resolveKey(y.sys.id,y)}),p.resolveRemaining(null)}finally{console.timeEnd(`fetch entries ${u}`)}}console.timeEnd("fetch all entries")}catch(u){let r=P(u),C=new Error(`Failed loading Contentful entries batch (${s.length}) ${r}`);s.forEach(m=>m.reject(C))}},shouldQueue:({parameter:s})=>F(s),limitPolicy:d}):{enhanceOne:async function({parameter:l,parameterName:f,component:u,context:r}){var C,m;if(F(l)){if(!M(l.value))return null;let E=N({clients:a,parameterName:f,parameterValue:l.value,component:u,context:r}),p=x(l.value)?l.value:l.value.entryId,h=(C=n==null?void 0:n({parameter:l,parameterName:f,component:u,defaultQuery:{...$},context:r}))!=null?C:$;try{return console.time(`fetch entry ${p}`),await E.getEntry(p,h)}catch(g){let y=P(g);throw x(l.value)?new Error(`Failed loading Contentful entry '${l.value}' referenced in parameter '${f}': ${y}`):new Error(`Failed loading Contentful entry '${p}' from source '${(m=l.value.source)!=null?m:"default"}' referenced in parameter '${f}': ${y}`)}finally{console.timeEnd(`fetch entry ${p}`)}}},limitPolicy:d}}function F(e){var t;return e.type===b[0]&&(((t=e.value)==null?void 0:t.entryId)||typeof e.value=="string")}function x(e){return typeof e=="string"}function M(e){return!(!e||!x(e)&&!e.entryId)}function N({clients:e,parameterValue:t,parameterName:n,component:o,context:c}){if(x(t)){let d=e.getClient({isPreviewClient:c.preview});if(!d)throw new Error(`Parameter '${n}' in component '${o.type}' has a value '${t}' that is not compatible with multi-space/environment usage. If you wish to use multiple spaces/environments, you must convert your Canvas component parameters to the multi-space/environment compatible version. Otherwise, you can continue to use your parameters as-is, but must specify one of the clients provided to the Contentful enhancer as the 'default' client by registering it without specifying a source key.`);return d}let{source:i="default"}=t,a=e.getClient({source:i,isPreviewClient:c.preview});if(!a)throw new Error(`No Contentful client could be resolved for source key '${i}' referenced in parameter '${n} in component '${o.type}'. Ensure that the 'clients' property you are passing to the enhancer has a client instance registered for the source key.`);return a}var I={select:"fields",include:1},Q=Object.freeze(["contentfulMultiEntry"]);function W({clients:e,createQuery:t,limitPolicy:n}){if(!e)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the ContentfulClientList.");return{enhanceOne:async function({parameter:i,parameterName:a,component:d,context:s}){var l,f;if(X(i)){if(!Z(i.value))return null;let u=L({clients:e,parameterName:a,parameterValue:i.value,component:d,context:s}),r=i.value.entries,C=(l=t==null?void 0:t({parameter:i,parameterName:a,component:d,defaultQuery:{...I},context:s}))!=null?l:I;try{return console.time(`fetch entries ${r.join()}`),(await u.getEntries({"sys.id[in]":r.join(),limit:r.length,...C})).items}catch(m){let E=P(m);throw new Error(`Failed loading Contentful entries '${r.join()}' from source '${(f=i.value.source)!=null?f:"default"}' referenced in parameter '${a}': ${E}`)}finally{console.timeEnd(`fetch entries ${r.join()}`)}}},limitPolicy:n||w}}function X(e){return e.type===Q[0]}function Z(e){var t;return!(!e||!((t=e.entries)==null?void 0:t.length))}var S=Object.freeze(["contentfulQuery"]),_={select:"fields",include:1};function ee({clients:e,createQuery:t,limitPolicy:n}){if(!e)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the ContentfulClientList.");return{enhanceOne:async function({parameter:i,parameterName:a,component:d,context:s}){var l,f;if(te(i)){if(!ne(i.value))return null;let u=L({clients:e,parameterName:a,parameterValue:i.value,component:d,context:s}),r=i.value,C=re(r.count),m=(l=t==null?void 0:t({parameter:i,parameterName:a,component:d,defaultQuery:{..._},context:s}))!=null?l:_,E=`fetch query: ${C} entries with '${r.contentType}' content type`;try{return console.time(E),(await u.getEntries({content_type:r.contentType,order:R(r.sortBy,r.sortOrder),limit:C,...m})).items}catch(p){let h=P(p);throw new Error(`Failed loading Contentful entries with '${r.contentType}' content type from source '${(f=r.source)!=null?f:"default"}' referenced in parameter '${a}': ${h}`)}finally{console.timeEnd(E)}}},limitPolicy:n||w}}function te(e){return e.type===S[0]}function ne(e){return!(!e||!e.source||!e.contentType||typeof e.count=="undefined")}function re(e){return!e||e<1?1:e>1e3?1e3:e}var k=require("@contentful/rich-text-html-renderer"),oe=({parameter:e})=>{let t=e.value;if(!t)return t;if(!ie(t))return j(t),t;for(let n of t)j(n);return t};function j(e){var t;typeof(e==null?void 0:e.fields)=="object"&&Object.entries((t=e.fields)!=null?t:{}).forEach(([n,o])=>{typeof o=="object"&&"nodeType"in o&&o.nodeType==="document"&&(e.fields[n]=(0,k.documentToHtmlString)(o))})}function ie(e){return Array.isArray(e)}module.exports=G(le);0&&(module.exports={CANVAS_CONTENTFUL_MULTI_PARAMETER_TYPES,CANVAS_CONTENTFUL_PARAMETER_TYPES,CANVAS_CONTENTFUL_QUERY_PARAMETER_TYPES,ContentfulClientList,contentfulRichTextToHtmlEnhancer,createContentfulEnhancer,createContentfulMultiEnhancer,createContentfulQueryEnhancer});
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ import{createBatchEnhancer as S,UniqueBatchEntries as _}from"@uniformdev/canvas";var L=class{constructor(t){this._clients={},Array.isArray(t)?t.forEach(n=>this.addClient(n)):t&&this.addClient(t)}addClient({source:t="default",client:n,previewClient:o}){if(this._clients[t])throw new Error(`The source ${t} is always registered`);if(!n)throw new Error("You must provide a Contentful client for the ContentfulClientList");this._clients[t]={client:n,previewClient:o||n}}getClient({source:t="default",isPreviewClient:n}){let o=this._clients[t];if(!!o)return n?o.previewClient:o.client}};import{createLimitPolicy as Q}from"@uniformdev/canvas";var x=Q({throttle:{limit:55,interval:1e3}});function P(e){return typeof e=="string"?e:typeof e=="object"&&e&&"error"in e?e.error:e instanceof Error?e.toString():JSON.stringify(e,null,2)}function V(e,t){if(!!e)return`${t==="desc"?"-":""}${e}`}function T({clients:e,parameterValue:t,parameterName:n,component:o,context:g}){let{source:i="default"}=t,a=e.getClient({source:i,isPreviewClient:g.preview});if(!a)throw new Error(`No Contentful client could be resolved for source key '${i}' referenced in parameter '${n} in component '${o.type}'. Ensure that the 'clients' property you are passing to the enhancer has a client instance registered for the source key.`);return a}var $={select:"fields",include:1},k=Object.freeze(["contentfulEntry"]);function j(e){return e instanceof L}function se({client:e,previewClient:t,createQuery:n,useBatching:o,limitPolicy:g}){if(!e)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the `client` or `clients` property.");let a=(()=>{if(j(e))return e;let s=new L;return s.addClient({client:e,previewClient:t}),s})(),y=g||x;return o?S({handleBatch:async s=>{var c;let l=s.reduce((u,r)=>{let{parameter:f,parameterName:C,component:h,context:m}=r.args,d=f.value;if(!R(d))return u;let E=b({parameterValue:d,parameterName:C,clients:a,component:h,context:m}),p="";if(A(d))p="legacy-group";else{let{source:I="default"}=d;p=I}return u[p]&&Array.isArray(u[p].tasks)?u[p].tasks.push(r):u[p]={client:E,tasks:[r]},u},{});try{console.time("fetch all entries");for await(let[u,r]of Object.entries(l)){let{context:f,component:C}=r.tasks[0].args,h=(c=n==null?void 0:n({component:C,defaultQuery:{...$},context:f}))!=null?c:$,m=new _(r.tasks,E=>A(E.parameter.value)?E.parameter.value:E.parameter.value.entryId),d=Object.keys(m.groups);console.time(`fetch entries ${u}`);try{(await r.client.getEntries({"sys.id[in]":d.join(","),limit:d.length,...h})).items.forEach(p=>{m.resolveKey(p.sys.id,p)}),m.resolveRemaining(null)}finally{console.timeEnd(`fetch entries ${u}`)}}console.timeEnd("fetch all entries")}catch(u){let r=P(u),f=new Error(`Failed loading Contentful entries batch (${s.length}) ${r}`);s.forEach(C=>C.reject(f))}},shouldQueue:({parameter:s})=>O(s),limitPolicy:y}):{enhanceOne:async function({parameter:l,parameterName:c,component:u,context:r}){var f,C;if(O(l)){if(!R(l.value))return null;let h=b({clients:a,parameterName:c,parameterValue:l.value,component:u,context:r}),m=A(l.value)?l.value:l.value.entryId,d=(f=n==null?void 0:n({parameter:l,parameterName:c,component:u,defaultQuery:{...$},context:r}))!=null?f:$;try{return console.time(`fetch entry ${m}`),await h.getEntry(m,d)}catch(E){let p=P(E);throw A(l.value)?new Error(`Failed loading Contentful entry '${l.value}' referenced in parameter '${c}': ${p}`):new Error(`Failed loading Contentful entry '${m}' from source '${(C=l.value.source)!=null?C:"default"}' referenced in parameter '${c}': ${p}`)}finally{console.timeEnd(`fetch entry ${m}`)}}},limitPolicy:y}}function O(e){var t;return e.type===k[0]&&(((t=e.value)==null?void 0:t.entryId)||typeof e.value=="string")}function A(e){return typeof e=="string"}function R(e){return!(!e||!A(e)&&!e.entryId)}function b({clients:e,parameterValue:t,parameterName:n,component:o,context:g}){if(A(t)){let y=e.getClient({isPreviewClient:g.preview});if(!y)throw new Error(`Parameter '${n}' in component '${o.type}' has a value '${t}' that is not compatible with multi-space/environment usage. If you wish to use multiple spaces/environments, you must convert your Canvas component parameters to the multi-space/environment compatible version. Otherwise, you can continue to use your parameters as-is, but must specify one of the clients provided to the Contentful enhancer as the 'default' client by registering it without specifying a source key.`);return y}let{source:i="default"}=t,a=e.getClient({source:i,isPreviewClient:g.preview});if(!a)throw new Error(`No Contentful client could be resolved for source key '${i}' referenced in parameter '${n} in component '${o.type}'. Ensure that the 'clients' property you are passing to the enhancer has a client instance registered for the source key.`);return a}var F={select:"fields",include:1},Y=Object.freeze(["contentfulMultiEntry"]);function Ce({clients:e,createQuery:t,limitPolicy:n}){if(!e)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the ContentfulClientList.");return{enhanceOne:async function({parameter:i,parameterName:a,component:y,context:s}){var l,c;if(B(i)){if(!U(i.value))return null;let u=T({clients:e,parameterName:a,parameterValue:i.value,component:y,context:s}),r=i.value.entries,f=(l=t==null?void 0:t({parameter:i,parameterName:a,component:y,defaultQuery:{...F},context:s}))!=null?l:F;try{return console.time(`fetch entries ${r.join()}`),(await u.getEntries({"sys.id[in]":r.join(),limit:r.length,...f})).items}catch(C){let h=P(C);throw new Error(`Failed loading Contentful entries '${r.join()}' from source '${(c=i.value.source)!=null?c:"default"}' referenced in parameter '${a}': ${h}`)}finally{console.timeEnd(`fetch entries ${r.join()}`)}}},limitPolicy:n||x}}function B(e){return e.type===Y[0]}function U(e){var t;return!(!e||!((t=e.entries)==null?void 0:t.length))}var q=Object.freeze(["contentfulQuery"]),M={select:"fields",include:1};function ye({clients:e,createQuery:t,limitPolicy:n}){if(!e)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the ContentfulClientList.");return{enhanceOne:async function({parameter:i,parameterName:a,component:y,context:s}){var l,c;if(D(i)){if(!z(i.value))return null;let u=T({clients:e,parameterName:a,parameterValue:i.value,component:y,context:s}),r=i.value,f=K(r.count),C=(l=t==null?void 0:t({parameter:i,parameterName:a,component:y,defaultQuery:{...M},context:s}))!=null?l:M,h=`fetch query: ${f} entries with '${r.contentType}' content type`;try{return console.time(h),(await u.getEntries({content_type:r.contentType,order:V(r.sortBy,r.sortOrder),limit:f,...C})).items}catch(m){let d=P(m);throw new Error(`Failed loading Contentful entries with '${r.contentType}' content type from source '${(c=r.source)!=null?c:"default"}' referenced in parameter '${a}': ${d}`)}finally{console.timeEnd(h)}}},limitPolicy:n||x}}function D(e){return e.type===q[0]}function z(e){return!(!e||!e.source||!e.contentType||typeof e.count=="undefined")}function K(e){return!e||e<1?1:e>1e3?1e3:e}import{documentToHtmlString as G}from"@contentful/rich-text-html-renderer";var Ee=({parameter:e})=>{let t=e.value;if(!t)return t;if(!H(t))return N(t),t;for(let n of t)N(n);return t};function N(e){var t;typeof(e==null?void 0:e.fields)=="object"&&Object.entries((t=e.fields)!=null?t:{}).forEach(([n,o])=>{typeof o=="object"&&"nodeType"in o&&o.nodeType==="document"&&(e.fields[n]=G(o))})}function H(e){return Array.isArray(e)}export{Y as CANVAS_CONTENTFUL_MULTI_PARAMETER_TYPES,k as CANVAS_CONTENTFUL_PARAMETER_TYPES,q as CANVAS_CONTENTFUL_QUERY_PARAMETER_TYPES,L as ContentfulClientList,Ee as contentfulRichTextToHtmlEnhancer,se as createContentfulEnhancer,Ce as createContentfulMultiEnhancer,ye as createContentfulQueryEnhancer};
package/package.json CHANGED
@@ -1,49 +1,49 @@
1
1
  {
2
2
  "name": "@uniformdev/canvas-contentful",
3
- "version": "12.0.1-alpha.94+0290763c",
3
+ "version": "12.2.1-alpha.121+3d33c2be",
4
4
  "description": "Contentful data enhancers for Uniform Canvas",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
- "main": "./dist/cjs/index.js",
7
- "module": "./dist/esm/index.js",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.esm.js",
8
8
  "exports": {
9
- "import": "./dist/esm/index.js",
10
- "require": "./dist/cjs/index.js"
9
+ "import": {
10
+ "node": "./dist/index.mjs",
11
+ "default": "./dist/index.esm.js"
12
+ },
13
+ "require": "./dist/index.js"
11
14
  },
12
- "types": "./dist/cjs/index.d.ts",
15
+ "types": "./dist/index.d.ts",
13
16
  "sideEffects": false,
14
17
  "scripts": {
15
- "build": "run-p build:cjs build:esm",
16
- "build:esm": "tsc",
17
- "build:cjs": "tsc -p ./tsconfig.cjs.json",
18
- "dev": "run-p dev:esm dev:cjs",
19
- "dev:esm": "tsc -w",
20
- "dev:cjs": "tsc -w -p ./tsconfig.cjs.json",
18
+ "build": "tsup",
19
+ "dev": "tsup --watch",
21
20
  "clean": "rimraf dist",
22
21
  "test": "jest --maxWorkers=1",
23
22
  "lint": "eslint \"src/**/*.{js,ts,tsx}\"",
24
23
  "format": "prettier --write \"src/**/*.{js,ts,tsx}\"",
25
24
  "ci:verify": "run-p lint test",
26
- "ci:build": "run-s clean build"
25
+ "ci:build": "tsup --minify --clean"
27
26
  },
28
27
  "dependencies": {
29
- "@uniformdev/canvas": "^12.0.1-alpha.94+0290763c"
28
+ "@uniformdev/canvas": "^12.2.1-alpha.121+3d33c2be"
30
29
  },
31
30
  "peerDependencies": {
32
31
  "@contentful/rich-text-html-renderer": ">= 14",
33
32
  "contentful": ">= 8"
34
33
  },
35
34
  "devDependencies": {
36
- "@contentful/rich-text-html-renderer": "15.4.0",
37
- "@types/jest": "27.0.2",
38
- "@types/node": "16.7.1",
39
- "contentful": "9.1.3",
40
- "eslint": "7.32.0",
41
- "eslint-plugin-react": "7.26.1",
42
- "eslint-plugin-react-hooks": "4.2.0",
43
- "jest": "27.3.1",
35
+ "@contentful/rich-text-html-renderer": "15.11.1",
36
+ "@types/jest": "27.4.0",
37
+ "@types/node": "16.11.19",
38
+ "contentful": "9.1.5",
39
+ "eslint": "8.6.0",
40
+ "eslint-plugin-react": "7.28.0",
41
+ "eslint-plugin-react-hooks": "4.3.0",
42
+ "jest": "27.4.7",
44
43
  "npm-run-all": "4.1.5",
45
44
  "rimraf": "3.0.2",
46
- "ts-jest": "27.0.7"
45
+ "ts-jest": "27.1.2",
46
+ "tsup": "5.11.11"
47
47
  },
48
48
  "files": [
49
49
  "/dist"
@@ -51,5 +51,5 @@
51
51
  "publishConfig": {
52
52
  "access": "public"
53
53
  },
54
- "gitHead": "0290763c5d9801ad4293fd59cb4cbeb35f5e1408"
54
+ "gitHead": "3d33c2be484210ce3f056e80176fc6f56b69dabc"
55
55
  }
@@ -1,36 +0,0 @@
1
- import { ContentfulClientApi } from 'contentful';
2
- export interface AddClientArgs {
3
- spaceId: string;
4
- environmentId: string;
5
- client: ContentfulClientApi;
6
- previewClient?: ContentfulClientApi;
7
- /** Specifies whether or not this client instance is the default instance in the ContentfulClientList.
8
- * The default instance is typically used by an enhancer when handling legacy Canvas data that is not in
9
- * multi-space/environment format or if no client can be resolved for a Contentful parameter.
10
- */
11
- isDefault?: boolean;
12
- }
13
- export declare class ContentfulClientList {
14
- private _clients;
15
- constructor(clients?: AddClientArgs[]);
16
- addClient({ spaceId, environmentId, client, previewClient, isDefault }: AddClientArgs): void;
17
- addClientWithKey({ client, clientKey, isDefault, previewClient, }: {
18
- clientKey: string;
19
- client: ContentfulClientApi;
20
- previewClient?: ContentfulClientApi;
21
- isDefault?: boolean;
22
- }): void;
23
- getClient({ spaceId, environmentId, isPreviewClient, }: {
24
- spaceId: string;
25
- environmentId: string;
26
- isPreviewClient?: boolean;
27
- }): ContentfulClientApi | undefined;
28
- getDefaultClient({ isPreviewClient, }?: {
29
- isPreviewClient?: boolean;
30
- }): ContentfulClientApi | undefined;
31
- getClientByKey({ clientKey, isPreviewClient, }: {
32
- clientKey: string;
33
- isPreviewClient?: boolean;
34
- }): ContentfulClientApi | undefined;
35
- generateClientKey(spaceId: string, environmentId: string): string;
36
- }
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ContentfulClientList=void 0;var ContentfulClientList=function(){function e(e){var t=this;this._clients={},e&&e.forEach(function(e){return t.addClient(e)})}return e.prototype.addClient=function(e){var t=e.spaceId,n=e.environmentId,i=e.client,r=e.previewClient,e=e.isDefault;if(!t)throw new Error("You must provide a space id for the Contentful client being added.");if(!n)throw new Error("You must provide an environment id for the Contentful client being added.");if(e&&Object.values(this._clients).some(function(e){return null==e?void 0:e.isDefault}))throw new Error("Only one Contentful client can be designated as the default client. You are attempting to designate the Contentful client for space '"+t+"' and environment '"+n+"' as the default client, but another client is already designated as the default.");n=this.generateClientKey(t,n);this.addClientWithKey({client:i,clientKey:n,isDefault:e,previewClient:r})},e.prototype.addClientWithKey=function(e){var t=e.client,n=e.clientKey,i=e.isDefault,e=e.previewClient;if(!t)throw new Error("You must provide a Contentful client for the ContentfulClientList");if(i&&Object.values(this._clients).some(function(e){return null==e?void 0:e.isDefault}))throw new Error("Only one Contentful client can be designated as the default client. You are attempting to designate the Contentful client with key '"+n+"'' as the default client, but another client is already designated as the default.");this._clients[n]={isDefault:i,client:t,previewClient:e||t}},e.prototype.getClient=function(e){var t=e.spaceId,n=e.environmentId,e=e.isPreviewClient;if(!t)throw new Error("You must provide a space id for the Contentful client you wish to retrieve.");if(!n)throw new Error("You must provide an environment id for the Contentful client you wish to retrieve.");n=this.generateClientKey(t,n);return e?this._clients[n].previewClient:this._clients[n].client},e.prototype.getDefaultClient=function(e){var t=(void 0===e?{}:e).isPreviewClient,e=Object.values(this._clients).find(function(e){return null==e?void 0:e.isDefault});if(e)return t?e.previewClient:e.client},e.prototype.getClientByKey=function(e){var t=e.clientKey,e=e.isPreviewClient,t=this._clients[t];if(t)return e?t.previewClient:t.client},e.prototype.generateClientKey=function(e,t){return e+"-"+t},e}();exports.ContentfulClientList=ContentfulClientList;
@@ -1,3 +0,0 @@
1
- import { ComponentParameterEnhancerFunction } from '@uniformdev/canvas';
2
- import { ContentfulEnhancerResult } from './createContentfulEnhancer';
3
- export declare const contentfulRichTextToHtmlEnhancer: ComponentParameterEnhancerFunction<ContentfulEnhancerResult<unknown>>;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.contentfulRichTextToHtmlEnhancer=void 0;var rich_text_html_renderer_1=require("@contentful/rich-text-html-renderer"),contentfulRichTextToHtmlEnhancer=function(e){var n=e.parameter;return"object"!=typeof(null===(e=n.value)||void 0===e?void 0:e.fields)||Object.entries(null!==(e=null===(e=n.value)||void 0===e?void 0:e.fields)&&void 0!==e?e:{}).forEach(function(e){var t=e[0],e=e[1];"object"==typeof e&&"nodeType"in e&&"document"===e.nodeType&&(n.value.fields[t]=(0,rich_text_html_renderer_1.documentToHtmlString)(e))}),n.value};exports.contentfulRichTextToHtmlEnhancer=contentfulRichTextToHtmlEnhancer;
@@ -1,54 +0,0 @@
1
- import { ComponentParameterEnhancer, ComponentInstance, ComponentParameter, LimitPolicy, EnhancerContext } from '@uniformdev/canvas';
2
- import { ContentfulClientApi, Sys } from 'contentful';
3
- import { ContentfulClientList } from './ContentfulClientList';
4
- export declare type EntrySelectorParameterValue = {
5
- entryId: string;
6
- space: {
7
- id: string;
8
- name: string;
9
- };
10
- environment: {
11
- id: string;
12
- name: string;
13
- };
14
- } | string | null | undefined;
15
- export declare type CreateContentfulQueryOptions<TContext extends EnhancerContext = EnhancerContext> = {
16
- /** Canvas parameter name being queried for. Not defined if using batching. */
17
- parameterName?: string;
18
- /** Canvas parameter value being fetched. Not defined if using batching. */
19
- parameter?: ComponentParameter<EntrySelectorParameterValue>;
20
- /** Component containing the parameter being fetched. Not defined if using batching. */
21
- component?: ComponentInstance;
22
- /** The default Contentful query expression (select fields + include 1 layer of references) */
23
- defaultQuery: any;
24
- /** The enhancer context provided to the enhance() function */
25
- context: TContext;
26
- };
27
- /** The default shape of the result value of the Contentful enhancer. Note that this can change if the query is altered. */
28
- export declare type ContentfulEnhancerResult<TFields> = {
29
- /**
30
- * The shape of the `fields` that the Contentful REST API is expected to return for this entry
31
- * https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entry
32
- *
33
- * These should line up with the fields in your content model(s) that are allowed for this component.
34
- */
35
- fields: TFields;
36
- /** System fields returned by the Contentful API. If you modify the query parameters to fetch more than fields, you may get more sys data than this. */
37
- sys: Partial<Pick<Sys, 'id' | 'type'>>;
38
- } | null;
39
- export declare type CreateContentfulEnhancerOptions = {
40
- /** Either a list of Contentful clients for use with multi-space/environment-enabled Canvas projects.
41
- * Or a single Contentful client for use with legacy Canvas data.*/
42
- client: ContentfulClientApi | ContentfulClientList;
43
- /** @deprecated Contentful client instance to use for fetching preview content.
44
- * This client is _only_ relevant when the `client` property is a single Contentful client intended for use with
45
- * legacy Canvas data. Conversely, if you use a `ContentfulClientList` for the `client` property, any value for `previewClient`
46
- * will be ignored. To avoid deprecated use, you should switch to using a `ContentfulClientList` for the `client` property. */
47
- previewClient?: ContentfulClientApi;
48
- /** Creates the Contentful client's query params for specific parameters. See https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters */
49
- createQuery?: (options: CreateContentfulQueryOptions) => any | undefined;
50
- useBatching?: boolean;
51
- limitPolicy?: LimitPolicy;
52
- };
53
- export declare const CANVAS_CONTENTFUL_PARAMETER_TYPES: readonly string[];
54
- export declare function createContentfulEnhancer({ client, previewClient, createQuery, useBatching, limitPolicy, }: CreateContentfulEnhancerOptions): ComponentParameterEnhancer<EntrySelectorParameterValue, ContentfulEnhancerResult<unknown>>;
@@ -1 +0,0 @@
1
- "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(n,t){function r(e){try{i(l.next(e))}catch(e){t(e)}}function a(e){try{i(l.throw(e))}catch(e){t(e)}}function i(e){var t;e.done?n(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(r,a)}i((l=l.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(n,r){var a,i,o,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},e={next:t(0),throw:t(1),return:t(2)};return"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(t){return function(e){return function(t){if(a)throw new TypeError("Generator is already executing.");for(;s;)try{if(a=1,i&&(o=2&t[0]?i.return:t[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,t[1])).done)return o;switch(i=0,(t=o?[2&t[0],o.value]:t)[0]){case 0:case 1:o=t;break;case 4:return s.label++,{value:t[1],done:!1};case 5:s.label++,i=t[1],t=[0];continue;case 7:t=s.ops.pop(),s.trys.pop();continue;default:if(!(o=0<(o=s.trys).length&&o[o.length-1])&&(6===t[0]||2===t[0])){s=0;continue}if(3===t[0]&&(!o||t[1]>o[0]&&t[1]<o[3])){s.label=t[1];break}if(6===t[0]&&s.label<o[1]){s.label=o[1],o=t;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(t);break}o[2]&&s.ops.pop(),s.trys.pop();continue}t=r.call(n,s)}catch(e){t=[6,e],i=0}finally{a=o=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,e])}}},__asyncValues=this&&this.__asyncValues||function(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,t=o[Symbol.asyncIterator];return t?t.call(o):(o="function"==typeof __values?__values(o):o[Symbol.iterator](),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(i){e[i]=o[i]&&function(a){return new Promise(function(e,t){var n,r;a=o[i](a),n=e,e=t,r=a.done,t=a.value,Promise.resolve(t).then(function(e){n({value:e,done:r})},e)})}}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.createContentfulEnhancer=exports.CANVAS_CONTENTFUL_PARAMETER_TYPES=void 0;var canvas_1=require("@uniformdev/canvas"),ContentfulClientList_1=require("./ContentfulClientList"),defaultQuery={select:"fields",include:1};function isClientList(e){return e instanceof ContentfulClientList_1.ContentfulClientList}function createContentfulEnhancer(e){var t=this,n=e.client,r=e.previewClient,m=e.createQuery,a=e.useBatching,e=e.limitPolicy;if(!n)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the `client` or `clients` property.");var y=function(){if(isClientList(n))return n;var e=new ContentfulClientList_1.ContentfulClientList;return e.addClientWithKey({clientKey:"default-client",client:n,previewClient:r,isDefault:!0}),e}(),e=e||(0,canvas_1.createLimitPolicy)({throttle:{limit:55,interval:1e3}});return a?(0,canvas_1.createBatchEnhancer)({handleBatch:function(v){return __awaiter(t,void 0,void 0,function(){var t,n,r,a,i,o,s,l,u,c,f,p;return __generator(this,function(e){switch(e.label){case 0:t=v.reduce(function(e,t){var n=t.args,r=n.parameter,a=n.parameterName,i=n.component,n=n.context,r=r.value;if(!isParameterValueDefined(r))return e;a=resolveClientForParameter({parameterValue:r,parameterName:a,clients:y,component:i,context:n}),i="";return e[i=isLegacyValue(r)?"legacy-group":(n=r.environment,r=r.space,y.generateClientKey(r.id,n.id))]&&Array.isArray(e[i].tasks)?e[i].tasks.push(t):e[i]={client:a,tasks:[t]},e},{}),e.label=1;case 1:e.trys.push([1,17,,18]),console.time("fetch all entries"),e.label=2;case 2:e.trys.push([2,10,11,16]),n=__asyncValues(Object.entries(t)),e.label=3;case 3:return[4,n.next()];case 4:if((r=e.sent()).done)return[3,9];p=r.value,a=p[0],i=p[1],o=i.tasks[0].args.context,o=null!==(p=null==m?void 0:m({defaultQuery:__assign({},defaultQuery),context:o}))&&void 0!==p?p:defaultQuery,s=new canvas_1.UniqueBatchEntries(i.tasks,function(e){return isLegacyValue(e.parameter.value)?e.parameter.value:e.parameter.value.entryId}),p=Object.keys(s.groups),console.time("fetch entries "+a),e.label=5;case 5:return e.trys.push([5,,7,8]),[4,i.client.getEntries(__assign({"sys.id[in]":p.join(","),limit:p.length},o))];case 6:return e.sent().items.forEach(function(e){s.resolveKey(e.sys.id,e)}),s.resolveRemaining(null),[3,8];case 7:return console.timeEnd("fetch entries "+a),[7];case 8:return[3,3];case 9:return[3,16];case 10:return l=e.sent(),c={error:l},[3,16];case 11:return e.trys.push([11,,14,15]),r&&!r.done&&(f=n.return)?[4,f.call(n)]:[3,13];case 12:e.sent(),e.label=13;case 13:return[3,15];case 14:if(c)throw c.error;return[7];case 15:return[7];case 16:return console.timeEnd("fetch all entries"),[3,18];case 17:return l=e.sent(),l=getErrorMessageFromContentfulError(l),u=new Error("Failed loading Contentful entries batch ("+v.length+") "+l),v.forEach(function(e){return e.reject(u)}),[3,18];case 18:return[2]}})})},shouldQueue:function(e){return parameterIsContentfulEntrySelector(e.parameter)},limitPolicy:e}):{enhanceOne:function(e){var i,o=e.parameter,s=e.parameterName,l=e.component,u=e.context;return __awaiter(this,void 0,void 0,function(){var t,n,r,a;return __generator(this,function(e){switch(e.label){case 0:if(!parameterIsContentfulEntrySelector(o))return[3,5];if(!isParameterValueDefined(o.value))return[2,null];t=resolveClientForParameter({clients:y,parameterName:s,parameterValue:o.value,component:l,context:u}),n=isLegacyValue(o.value)?o.value:o.value.entryId,r=null!==(i=null==m?void 0:m({parameter:o,parameterName:s,component:l,defaultQuery:__assign({},defaultQuery),context:u}))&&void 0!==i?i:defaultQuery,e.label=1;case 1:return e.trys.push([1,3,4,5]),console.time("fetch entry "+n),[4,t.getEntry(n,r)];case 2:return[2,e.sent()];case 3:throw a=e.sent(),a=getErrorMessageFromContentfulError(a),isLegacyValue(o.value)?new Error("Failed loading Contentful entry '"+o.value+"' referenced in parameter '"+s+"': "+a):new Error("Failed loading Contentful entry '"+n+"' from space '"+o.value.space.id+"' and environment '"+o.value.environment.id+"' referenced in parameter '"+s+"': "+a);case 4:return console.timeEnd("fetch entry "+n),[7];case 5:return[2]}})})},limitPolicy:e}}function parameterIsContentfulEntrySelector(e){var t;return e.type===exports.CANVAS_CONTENTFUL_PARAMETER_TYPES[0]&&((null===(t=e.value)||void 0===t?void 0:t.entryId)||"string"==typeof e.value)}function getErrorMessageFromContentfulError(e){return"string"==typeof e?e:"object"==typeof e&&e&&"error"in e?e.error:e instanceof Error?e.toString():JSON.stringify(e,null,2)}function isLegacyValue(e){return"string"==typeof e}function isParameterValueDefined(e){return!(!e||!(isLegacyValue(e)||e.entryId&&e.space&&e.environment))}function resolveClientForParameter(e){var t=e.clients,n=e.parameterValue,r=e.parameterName,a=e.component,e=e.context;if(isLegacyValue(n)){var i=t.getDefaultClient({isPreviewClient:e.preview});if(!i)throw new Error("Parameter '"+r+"' in component '"+a.type+"' has a value '"+n+"' that is not compatible with multi-space/environment usage. If you wish to use multiple spaces/environments, you must convert your Canvas component parameters to the multi-space/environment compatible version. Otherwise, you can continue to use your parameters as-is, but must specify one of the clients provided to the Contentful enhancer as the 'default' client using the 'isDefault' option available in the 'addClient' method.");return i}i=n.environment,n=n.space,e=t.getClient({spaceId:n.id,environmentId:i.id,isPreviewClient:e.preview})||t.getDefaultClient({isPreviewClient:e.preview});if(!e)throw new Error("No Contentful client could be resolved for space '"+n.name+" ("+n.id+")' and environment '"+i.name+" ("+i.id+")' referenced in parameter '"+r+" in component '"+a.type+"'. Ensure that the 'clients' property you are passing to the enhancer has a client instance for the previously mentioned space and environment.");return e}exports.CANVAS_CONTENTFUL_PARAMETER_TYPES=Object.freeze(["contentfulEntry"]),exports.createContentfulEnhancer=createContentfulEnhancer;
@@ -1,3 +0,0 @@
1
- export * from './createContentfulEnhancer';
2
- export * from './contentfulRichTextToHtmlEnhancer';
3
- export * from './ContentfulClientList';
package/dist/cjs/index.js DELETED
@@ -1 +0,0 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){e[n=void 0===n?r:n]=t[r]}),__exportStar=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||__createBinding(t,e,r)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(require("./createContentfulEnhancer"),exports),__exportStar(require("./contentfulRichTextToHtmlEnhancer"),exports),__exportStar(require("./ContentfulClientList"),exports);
@@ -1,36 +0,0 @@
1
- import { ContentfulClientApi } from 'contentful';
2
- export interface AddClientArgs {
3
- spaceId: string;
4
- environmentId: string;
5
- client: ContentfulClientApi;
6
- previewClient?: ContentfulClientApi;
7
- /** Specifies whether or not this client instance is the default instance in the ContentfulClientList.
8
- * The default instance is typically used by an enhancer when handling legacy Canvas data that is not in
9
- * multi-space/environment format or if no client can be resolved for a Contentful parameter.
10
- */
11
- isDefault?: boolean;
12
- }
13
- export declare class ContentfulClientList {
14
- private _clients;
15
- constructor(clients?: AddClientArgs[]);
16
- addClient({ spaceId, environmentId, client, previewClient, isDefault }: AddClientArgs): void;
17
- addClientWithKey({ client, clientKey, isDefault, previewClient, }: {
18
- clientKey: string;
19
- client: ContentfulClientApi;
20
- previewClient?: ContentfulClientApi;
21
- isDefault?: boolean;
22
- }): void;
23
- getClient({ spaceId, environmentId, isPreviewClient, }: {
24
- spaceId: string;
25
- environmentId: string;
26
- isPreviewClient?: boolean;
27
- }): ContentfulClientApi | undefined;
28
- getDefaultClient({ isPreviewClient, }?: {
29
- isPreviewClient?: boolean;
30
- }): ContentfulClientApi | undefined;
31
- getClientByKey({ clientKey, isPreviewClient, }: {
32
- clientKey: string;
33
- isPreviewClient?: boolean;
34
- }): ContentfulClientApi | undefined;
35
- generateClientKey(spaceId: string, environmentId: string): string;
36
- }
@@ -1 +0,0 @@
1
- var ContentfulClientList=function(){function e(e){var t=this;this._clients={},e&&e.forEach(function(e){return t.addClient(e)})}return e.prototype.addClient=function(e){var t=e.spaceId,n=e.environmentId,i=e.client,r=e.previewClient,e=e.isDefault;if(!t)throw new Error("You must provide a space id for the Contentful client being added.");if(!n)throw new Error("You must provide an environment id for the Contentful client being added.");if(e&&Object.values(this._clients).some(function(e){return null==e?void 0:e.isDefault}))throw new Error("Only one Contentful client can be designated as the default client. You are attempting to designate the Contentful client for space '"+t+"' and environment '"+n+"' as the default client, but another client is already designated as the default.");n=this.generateClientKey(t,n);this.addClientWithKey({client:i,clientKey:n,isDefault:e,previewClient:r})},e.prototype.addClientWithKey=function(e){var t=e.client,n=e.clientKey,i=e.isDefault,e=e.previewClient;if(!t)throw new Error("You must provide a Contentful client for the ContentfulClientList");if(i&&Object.values(this._clients).some(function(e){return null==e?void 0:e.isDefault}))throw new Error("Only one Contentful client can be designated as the default client. You are attempting to designate the Contentful client with key '"+n+"'' as the default client, but another client is already designated as the default.");this._clients[n]={isDefault:i,client:t,previewClient:e||t}},e.prototype.getClient=function(e){var t=e.spaceId,n=e.environmentId,e=e.isPreviewClient;if(!t)throw new Error("You must provide a space id for the Contentful client you wish to retrieve.");if(!n)throw new Error("You must provide an environment id for the Contentful client you wish to retrieve.");n=this.generateClientKey(t,n);return e?this._clients[n].previewClient:this._clients[n].client},e.prototype.getDefaultClient=function(e){var t=(void 0===e?{}:e).isPreviewClient,e=Object.values(this._clients).find(function(e){return null==e?void 0:e.isDefault});if(e)return t?e.previewClient:e.client},e.prototype.getClientByKey=function(e){var t=e.clientKey,e=e.isPreviewClient,t=this._clients[t];if(t)return e?t.previewClient:t.client},e.prototype.generateClientKey=function(e,t){return e+"-"+t},e}();export{ContentfulClientList};
@@ -1,3 +0,0 @@
1
- import { ComponentParameterEnhancerFunction } from '@uniformdev/canvas';
2
- import { ContentfulEnhancerResult } from './createContentfulEnhancer';
3
- export declare const contentfulRichTextToHtmlEnhancer: ComponentParameterEnhancerFunction<ContentfulEnhancerResult<unknown>>;
@@ -1 +0,0 @@
1
- import{documentToHtmlString}from"@contentful/rich-text-html-renderer";var contentfulRichTextToHtmlEnhancer=function(e){var n=e.parameter;return"object"!=typeof(null===(e=n.value)||void 0===e?void 0:e.fields)||Object.entries(null!==(e=null===(e=n.value)||void 0===e?void 0:e.fields)&&void 0!==e?e:{}).forEach(function(e){var t=e[0],e=e[1];"object"==typeof e&&"nodeType"in e&&"document"===e.nodeType&&(n.value.fields[t]=documentToHtmlString(e))}),n.value};export{contentfulRichTextToHtmlEnhancer};
@@ -1,54 +0,0 @@
1
- import { ComponentParameterEnhancer, ComponentInstance, ComponentParameter, LimitPolicy, EnhancerContext } from '@uniformdev/canvas';
2
- import { ContentfulClientApi, Sys } from 'contentful';
3
- import { ContentfulClientList } from './ContentfulClientList';
4
- export declare type EntrySelectorParameterValue = {
5
- entryId: string;
6
- space: {
7
- id: string;
8
- name: string;
9
- };
10
- environment: {
11
- id: string;
12
- name: string;
13
- };
14
- } | string | null | undefined;
15
- export declare type CreateContentfulQueryOptions<TContext extends EnhancerContext = EnhancerContext> = {
16
- /** Canvas parameter name being queried for. Not defined if using batching. */
17
- parameterName?: string;
18
- /** Canvas parameter value being fetched. Not defined if using batching. */
19
- parameter?: ComponentParameter<EntrySelectorParameterValue>;
20
- /** Component containing the parameter being fetched. Not defined if using batching. */
21
- component?: ComponentInstance;
22
- /** The default Contentful query expression (select fields + include 1 layer of references) */
23
- defaultQuery: any;
24
- /** The enhancer context provided to the enhance() function */
25
- context: TContext;
26
- };
27
- /** The default shape of the result value of the Contentful enhancer. Note that this can change if the query is altered. */
28
- export declare type ContentfulEnhancerResult<TFields> = {
29
- /**
30
- * The shape of the `fields` that the Contentful REST API is expected to return for this entry
31
- * https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entry
32
- *
33
- * These should line up with the fields in your content model(s) that are allowed for this component.
34
- */
35
- fields: TFields;
36
- /** System fields returned by the Contentful API. If you modify the query parameters to fetch more than fields, you may get more sys data than this. */
37
- sys: Partial<Pick<Sys, 'id' | 'type'>>;
38
- } | null;
39
- export declare type CreateContentfulEnhancerOptions = {
40
- /** Either a list of Contentful clients for use with multi-space/environment-enabled Canvas projects.
41
- * Or a single Contentful client for use with legacy Canvas data.*/
42
- client: ContentfulClientApi | ContentfulClientList;
43
- /** @deprecated Contentful client instance to use for fetching preview content.
44
- * This client is _only_ relevant when the `client` property is a single Contentful client intended for use with
45
- * legacy Canvas data. Conversely, if you use a `ContentfulClientList` for the `client` property, any value for `previewClient`
46
- * will be ignored. To avoid deprecated use, you should switch to using a `ContentfulClientList` for the `client` property. */
47
- previewClient?: ContentfulClientApi;
48
- /** Creates the Contentful client's query params for specific parameters. See https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters */
49
- createQuery?: (options: CreateContentfulQueryOptions) => any | undefined;
50
- useBatching?: boolean;
51
- limitPolicy?: LimitPolicy;
52
- };
53
- export declare const CANVAS_CONTENTFUL_PARAMETER_TYPES: readonly string[];
54
- export declare function createContentfulEnhancer({ client, previewClient, createQuery, useBatching, limitPolicy, }: CreateContentfulEnhancerOptions): ComponentParameterEnhancer<EntrySelectorParameterValue, ContentfulEnhancerResult<unknown>>;
@@ -1 +0,0 @@
1
- var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,l,s){return new(l=l||Promise)(function(n,t){function r(e){try{i(s.next(e))}catch(e){t(e)}}function a(e){try{i(s.throw(e))}catch(e){t(e)}}function i(e){var t;e.done?n(e.value):((t=e.value)instanceof l?t:new l(function(e){e(t)})).then(r,a)}i((s=s.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(n,r){var a,i,o,l={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},e={next:t(0),throw:t(1),return:t(2)};return"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(t){return function(e){return function(t){if(a)throw new TypeError("Generator is already executing.");for(;l;)try{if(a=1,i&&(o=2&t[0]?i.return:t[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,t[1])).done)return o;switch(i=0,(t=o?[2&t[0],o.value]:t)[0]){case 0:case 1:o=t;break;case 4:return l.label++,{value:t[1],done:!1};case 5:l.label++,i=t[1],t=[0];continue;case 7:t=l.ops.pop(),l.trys.pop();continue;default:if(!(o=0<(o=l.trys).length&&o[o.length-1])&&(6===t[0]||2===t[0])){l=0;continue}if(3===t[0]&&(!o||t[1]>o[0]&&t[1]<o[3])){l.label=t[1];break}if(6===t[0]&&l.label<o[1]){l.label=o[1],o=t;break}if(o&&l.label<o[2]){l.label=o[2],l.ops.push(t);break}o[2]&&l.ops.pop(),l.trys.pop();continue}t=r.call(n,l)}catch(e){t=[6,e],i=0}finally{a=o=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,e])}}},__asyncValues=this&&this.__asyncValues||function(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,t=o[Symbol.asyncIterator];return t?t.call(o):(o="function"==typeof __values?__values(o):o[Symbol.iterator](),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(i){e[i]=o[i]&&function(a){return new Promise(function(e,t){var n,r;a=o[i](a),n=e,e=t,r=a.done,t=a.value,Promise.resolve(t).then(function(e){n({value:e,done:r})},e)})}}};import{createBatchEnhancer,UniqueBatchEntries,createLimitPolicy}from"@uniformdev/canvas";import{ContentfulClientList}from"./ContentfulClientList";var defaultQuery={select:"fields",include:1},CANVAS_CONTENTFUL_PARAMETER_TYPES=Object.freeze(["contentfulEntry"]);function isClientList(e){return e instanceof ContentfulClientList}function createContentfulEnhancer(e){var t=this,n=e.client,r=e.previewClient,y=e.createQuery,a=e.useBatching,e=e.limitPolicy;if(!n)throw new Error("No Contentful clients were provided to the enhancer. You must provide at least one client via the `client` or `clients` property.");var h=function(){if(isClientList(n))return n;var e=new ContentfulClientList;return e.addClientWithKey({clientKey:"default-client",client:n,previewClient:r,isDefault:!0}),e}(),e=e||createLimitPolicy({throttle:{limit:55,interval:1e3}});return a?createBatchEnhancer({handleBatch:function(m){return __awaiter(t,void 0,void 0,function(){var t,n,r,a,i,o,l,s,u,c,f,p;return __generator(this,function(e){switch(e.label){case 0:t=m.reduce(function(e,t){var n=t.args,r=n.parameter,a=n.parameterName,i=n.component,n=n.context,r=r.value;if(!isParameterValueDefined(r))return e;a=resolveClientForParameter({parameterValue:r,parameterName:a,clients:h,component:i,context:n}),i="";return e[i=isLegacyValue(r)?"legacy-group":(n=r.environment,r=r.space,h.generateClientKey(r.id,n.id))]&&Array.isArray(e[i].tasks)?e[i].tasks.push(t):e[i]={client:a,tasks:[t]},e},{}),e.label=1;case 1:e.trys.push([1,17,,18]),console.time("fetch all entries"),e.label=2;case 2:e.trys.push([2,10,11,16]),n=__asyncValues(Object.entries(t)),e.label=3;case 3:return[4,n.next()];case 4:if((r=e.sent()).done)return[3,9];p=r.value,a=p[0],i=p[1],o=i.tasks[0].args.context,o=null!==(p=null==y?void 0:y({defaultQuery:__assign({},defaultQuery),context:o}))&&void 0!==p?p:defaultQuery,l=new UniqueBatchEntries(i.tasks,function(e){return isLegacyValue(e.parameter.value)?e.parameter.value:e.parameter.value.entryId}),p=Object.keys(l.groups),console.time("fetch entries "+a),e.label=5;case 5:return e.trys.push([5,,7,8]),[4,i.client.getEntries(__assign({"sys.id[in]":p.join(","),limit:p.length},o))];case 6:return e.sent().items.forEach(function(e){l.resolveKey(e.sys.id,e)}),l.resolveRemaining(null),[3,8];case 7:return console.timeEnd("fetch entries "+a),[7];case 8:return[3,3];case 9:return[3,16];case 10:return s=e.sent(),c={error:s},[3,16];case 11:return e.trys.push([11,,14,15]),r&&!r.done&&(f=n.return)?[4,f.call(n)]:[3,13];case 12:e.sent(),e.label=13;case 13:return[3,15];case 14:if(c)throw c.error;return[7];case 15:return[7];case 16:return console.timeEnd("fetch all entries"),[3,18];case 17:return s=e.sent(),s=getErrorMessageFromContentfulError(s),u=new Error("Failed loading Contentful entries batch ("+m.length+") "+s),m.forEach(function(e){return e.reject(u)}),[3,18];case 18:return[2]}})})},shouldQueue:function(e){return parameterIsContentfulEntrySelector(e.parameter)},limitPolicy:e}):{enhanceOne:function(e){var i,o=e.parameter,l=e.parameterName,s=e.component,u=e.context;return __awaiter(this,void 0,void 0,function(){var t,n,r,a;return __generator(this,function(e){switch(e.label){case 0:if(!parameterIsContentfulEntrySelector(o))return[3,5];if(!isParameterValueDefined(o.value))return[2,null];t=resolveClientForParameter({clients:h,parameterName:l,parameterValue:o.value,component:s,context:u}),n=isLegacyValue(o.value)?o.value:o.value.entryId,r=null!==(i=null==y?void 0:y({parameter:o,parameterName:l,component:s,defaultQuery:__assign({},defaultQuery),context:u}))&&void 0!==i?i:defaultQuery,e.label=1;case 1:return e.trys.push([1,3,4,5]),console.time("fetch entry "+n),[4,t.getEntry(n,r)];case 2:return[2,e.sent()];case 3:throw a=e.sent(),a=getErrorMessageFromContentfulError(a),isLegacyValue(o.value)?new Error("Failed loading Contentful entry '"+o.value+"' referenced in parameter '"+l+"': "+a):new Error("Failed loading Contentful entry '"+n+"' from space '"+o.value.space.id+"' and environment '"+o.value.environment.id+"' referenced in parameter '"+l+"': "+a);case 4:return console.timeEnd("fetch entry "+n),[7];case 5:return[2]}})})},limitPolicy:e}}function parameterIsContentfulEntrySelector(e){var t;return e.type===CANVAS_CONTENTFUL_PARAMETER_TYPES[0]&&((null===(t=e.value)||void 0===t?void 0:t.entryId)||"string"==typeof e.value)}function getErrorMessageFromContentfulError(e){return"string"==typeof e?e:"object"==typeof e&&e&&"error"in e?e.error:e instanceof Error?e.toString():JSON.stringify(e,null,2)}function isLegacyValue(e){return"string"==typeof e}function isParameterValueDefined(e){return!(!e||!(isLegacyValue(e)||e.entryId&&e.space&&e.environment))}function resolveClientForParameter(e){var t=e.clients,n=e.parameterValue,r=e.parameterName,a=e.component,e=e.context;if(isLegacyValue(n)){var i=t.getDefaultClient({isPreviewClient:e.preview});if(!i)throw new Error("Parameter '"+r+"' in component '"+a.type+"' has a value '"+n+"' that is not compatible with multi-space/environment usage. If you wish to use multiple spaces/environments, you must convert your Canvas component parameters to the multi-space/environment compatible version. Otherwise, you can continue to use your parameters as-is, but must specify one of the clients provided to the Contentful enhancer as the 'default' client using the 'isDefault' option available in the 'addClient' method.");return i}i=n.environment,n=n.space,e=t.getClient({spaceId:n.id,environmentId:i.id,isPreviewClient:e.preview})||t.getDefaultClient({isPreviewClient:e.preview});if(!e)throw new Error("No Contentful client could be resolved for space '"+n.name+" ("+n.id+")' and environment '"+i.name+" ("+i.id+")' referenced in parameter '"+r+" in component '"+a.type+"'. Ensure that the 'clients' property you are passing to the enhancer has a client instance for the previously mentioned space and environment.");return e}export{CANVAS_CONTENTFUL_PARAMETER_TYPES,createContentfulEnhancer};
@@ -1,3 +0,0 @@
1
- export * from './createContentfulEnhancer';
2
- export * from './contentfulRichTextToHtmlEnhancer';
3
- export * from './ContentfulClientList';
package/dist/esm/index.js DELETED
@@ -1 +0,0 @@
1
- export*from"./createContentfulEnhancer";export*from"./contentfulRichTextToHtmlEnhancer";export*from"./ContentfulClientList";