@washingtonpost/subs-de-inputs 0.2.1-canary.3 → 0.2.1
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/CHANGELOG.md +25 -0
- package/dist/services/dataEnrichment.d.ts +1 -1
- package/dist/subs-de-inputs.cjs.development.js +4 -1
- package/dist/subs-de-inputs.cjs.development.js.map +1 -1
- package/dist/subs-de-inputs.cjs.production.min.js +1 -1
- package/dist/subs-de-inputs.cjs.production.min.js.map +1 -1
- package/dist/subs-de-inputs.esm.js +4 -1
- package/dist/subs-de-inputs.esm.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Change Log
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file. See
|
|
4
|
+
[Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
|
+
|
|
6
|
+
**[0.2.1 - 2024-05-02]**:
|
|
7
|
+
* Revert "ESM build only"
|
|
8
|
+
* `ingest()` function throws error if `submitData.value` is not an array (required by BE)
|
|
9
|
+
|
|
10
|
+
**[0.2.0 - 2024-05-01]**:
|
|
11
|
+
* Adds `ingest()` function
|
|
12
|
+
* ESM build only
|
|
13
|
+
* Babel config to target recent browsers only
|
|
14
|
+
|
|
15
|
+
**[0.1.1 - 2024-04-30]**:
|
|
16
|
+
* Fix build by removing unused file
|
|
17
|
+
|
|
18
|
+
**[0.1.0 - 2024-04-25]**:
|
|
19
|
+
* Add initial `<DESelect />` component
|
|
20
|
+
|
|
21
|
+
**[0.0.2 - 2024-04-24]**:
|
|
22
|
+
* Fix build error
|
|
23
|
+
|
|
24
|
+
**[0.0.1 - 2024-04-09]**:
|
|
25
|
+
* Initial setup
|
|
@@ -10,7 +10,7 @@ declare type IngestType = ({ submitData: { fieldName, value }, source, }: {
|
|
|
10
10
|
fieldName: string;
|
|
11
11
|
value: string[];
|
|
12
12
|
};
|
|
13
|
-
type
|
|
13
|
+
type?: (typeof IngestType)[keyof typeof IngestType];
|
|
14
14
|
source: string;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
status: ResponseStatus;
|
|
@@ -81,7 +81,7 @@ const ingest = async _ref2 => {
|
|
|
81
81
|
fieldName,
|
|
82
82
|
value
|
|
83
83
|
},
|
|
84
|
-
type,
|
|
84
|
+
type = IngestType.IMPLICIT,
|
|
85
85
|
source
|
|
86
86
|
} = _ref2;
|
|
87
87
|
const url = `${base}/ingest`;
|
|
@@ -89,6 +89,9 @@ const ingest = async _ref2 => {
|
|
|
89
89
|
if (!hasRequiredPrivacyCookies()) {
|
|
90
90
|
throw new Error('does not satisfy cookie check');
|
|
91
91
|
}
|
|
92
|
+
if (!Array.isArray(value)) {
|
|
93
|
+
throw new Error('value is not an array');
|
|
94
|
+
}
|
|
92
95
|
let attributeInfo = attributesCache[fieldName];
|
|
93
96
|
if (!attributeInfo) {
|
|
94
97
|
attributeInfo = await getAttributes({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subs-de-inputs.cjs.development.js","sources":["../src/interfaces/index.ts","../src/utils/hasRequiredPrivacyCookies.ts","../src/services/dataEnrichment.ts","../src/components/DESelect/index.tsx"],"sourcesContent":["export type AttributeValue = {\n name: string;\n date_created: Number;\n last_modified_date: Number;\n archived: boolean;\n order: number;\n};\n\nexport const CollectionBehaviors = {\n COLLECT: 'COLLECT',\n DO_NOT_COLLECT: 'DO_NOT_COLLECT',\n} as const;\n\nexport type Attribute = {\n name: string;\n approved_for_use?: boolean;\n collection_behavior?: (typeof CollectionBehaviors)[keyof typeof CollectionBehaviors];\n datatype: 'string';\n explicit: boolean;\n multiple_value: boolean;\n last_modified_date: Number;\n date_created: Number;\n values: Array<AttributeValue>;\n};\n\nexport const AttributesState = {\n SUCCESS: '100',\n} as const;\n\nexport const IngestType = {\n EXPLICIT: 'explicit',\n IMPLICIT: 'implicit',\n} as const;\n\nexport const IngestResponseState = {\n SUCCESS: '100',\n SYSTEM_ERROR: '101',\n INVALID_TYPE: '102',\n INVALID_IDENTIFIER: '103',\n INVALID_DATA: '104',\n INVALID_ATTRIBUTE_DEFINITION: '105',\n INVALID_META_DEFINITION: '106',\n UNAUTHENTICATED: '107',\n MISMATCHED_IDENTIFIER: '108',\n DISABLED_ATTRIBUTE_DEFINITION: '109',\n DO_NOT_COLLECT: '110',\n} as const;\n","import { WPGeo, getCookie } from '@washingtonpost/subs-sdk';\n\nexport const hasRequiredPrivacyCookies = () => {\n if (typeof window === 'undefined') {\n return false;\n }\n\n const wp_usp = getCookie('wp_usp');\n\n const countryCode = WPGeo()?.country_code;\n\n return !!(wp_usp && countryCode === 'US');\n};\n","import {\n ENDPOINTS,\n ResponseStatus,\n JSON_HEADERS,\n getCookie,\n} from '@washingtonpost/subs-sdk';\nimport {\n Attribute,\n CollectionBehaviors,\n IngestResponseState,\n IngestType,\n} from '../interfaces';\nimport { hasRequiredPrivacyCookies } from '../utils/hasRequiredPrivacyCookies';\n\nconst base = `${ENDPOINTS.base}/de/v1`;\n\nconst attributesCache: Record<string, any> = {};\nexport const getAttributes: GetAttributesType = async ({\n fieldName,\n}: {\n fieldName: string;\n}) => {\n if (attributesCache[fieldName]) {\n return attributesCache[fieldName];\n }\n\n const fieldNames = [fieldName];\n\n try {\n const url = new URL(`${base}/attributes`);\n url.searchParams.set('attributes', fieldNames.join(','));\n\n const data = await fetch(url.toString(), {\n credentials: 'include',\n headers: JSON_HEADERS,\n });\n const json = await data.json();\n\n if (data.ok && json.status === ResponseStatus.SUCCESS) {\n const attributes = json.attributes || [];\n attributesCache[fieldName] = attributes;\n return attributes;\n } else {\n return [];\n }\n } catch (e) {\n console.debug(e);\n return [];\n }\n};\n\ntype GetAttributesType = ({\n fieldName,\n}: {\n fieldName: string;\n}) => Promise<Attribute[]>;\n\nexport const ingest: IngestType = async ({\n submitData: { fieldName, value },\n type,\n source,\n}) => {\n const url = `${base}/ingest`;\n\n const wapo_login_id = getCookie('wapo_login_id');\n\n if (!hasRequiredPrivacyCookies()) {\n throw new Error('does not satisfy cookie check');\n }\n\n let attributeInfo = attributesCache[fieldName];\n if (!attributeInfo) {\n attributeInfo = await getAttributes({ fieldName });\n }\n\n if (\n attributeInfo[0] &&\n attributeInfo[0].name === fieldName &&\n attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT\n ) {\n throw new Error('do not collect');\n }\n\n const jucid = localStorage.getItem('uuid');\n const ga = getCookie('_ga');\n\n const payload = {\n jucid,\n ga,\n type,\n wapo_login_id, // TODO: move this to BE to read from cookie headers\n data: {\n fieldName,\n value,\n },\n metadata: { source },\n };\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: JSON_HEADERS,\n body: JSON.stringify(payload),\n });\n\n const json = await response.json();\n\n return json;\n } catch (e) {\n console.debug(e);\n return null;\n }\n};\n\ntype IngestType = ({\n submitData: { fieldName, value },\n source,\n}: {\n submitData: {\n fieldName: string;\n value: string[];\n };\n type: (typeof IngestType)[keyof typeof IngestType];\n source: string;\n}) => Promise<{\n status: ResponseStatus;\n state: (typeof IngestResponseState)[keyof typeof IngestResponseState];\n} | null>;\n","import React, { useState, useEffect } from 'react';\nimport { Select, styled, theme } from '@washingtonpost/wpds-ui-kit';\nimport { Attribute, AttributeValue, IngestType } from '../../interfaces';\nimport { ingest } from '../../services/dataEnrichment';\nimport { ENDPOINTS, ResponseStatus } from '@washingtonpost/subs-sdk';\nimport { useScript, ScriptStatus } from '@washingtonpost/subs-hooks';\n\ninterface DESelectProps {\n source: string;\n fieldName: string;\n label?: string;\n dataDictionaryConfig?: Attribute;\n defaultValue?: string;\n disabled?: boolean;\n submit: boolean;\n onChange?: ({ value }: { value: string }) => void;\n onFinished?: ({\n isFinished,\n isError,\n }: {\n isFinished: boolean;\n isError: boolean;\n }) => void;\n valuesFilter?: (value: AttributeValue) => boolean;\n selectProps?: {\n root?: any;\n trigger?: any;\n label?: any;\n value?: any;\n content?: any;\n item?: any;\n };\n children?: React.ReactNode;\n}\n\nconst scriptSrc = `${\n ENDPOINTS.staticAssets === 'https://subscribe.washingtonpost.com/static'\n ? 'https://www.washingtonpost.com/subscribe/static/'\n : ENDPOINTS.staticAssets\n}/de-utils/twpdeu.min.js`;\n\nexport const DESelect: React.FC<DESelectProps> = ({\n source,\n fieldName,\n label,\n dataDictionaryConfig,\n defaultValue,\n disabled,\n submit,\n onChange = () => {},\n onFinished = () => {},\n valuesFilter = () => true,\n children,\n}) => {\n const [config, setConfig] = useState(dataDictionaryConfig);\n\n const [selected, setSelected] = useState('');\n\n const scriptStatus = useScript(scriptSrc);\n\n useEffect(() => {\n const fetchConfig = async () => {\n try {\n const config = await window?.__twpdeu?.getFieldConfigs({ fieldName });\n if (config) {\n setConfig(config[0]);\n } else {\n console.error('unable to get config', fieldName);\n }\n } catch (e) {\n console.warn('unable to get config', fieldName, e);\n }\n };\n\n if (scriptStatus === ScriptStatus.READY && !(children || config)) {\n fetchConfig();\n }\n }, [scriptStatus]);\n\n useEffect(() => {\n const submitSelected = async () => {\n try {\n // TODO: Switch to window.__twpdeu.push\n // TODO: Log to GA\n const result = await ingest({\n submitData: { fieldName, value: [selected] },\n type: config?.explicit ? IngestType.EXPLICIT : IngestType.IMPLICIT,\n source,\n });\n const isError = result\n ? result.status !== ResponseStatus.SUCCESS\n : true;\n\n onFinished({\n isFinished: true,\n isError,\n });\n } catch (e) {\n onFinished({\n isFinished: false,\n isError: true,\n });\n }\n };\n\n if (submit && selected) {\n submitSelected();\n }\n }, [submit, selected]);\n\n if (!(children || config)) {\n return <span>loading</span>;\n }\n\n const defaultValueProp = defaultValue ? { defaultValue } : {};\n\n const disabledProp = disabled ? { disabled: true } : {};\n\n // sort and filter out archived values\n const values = config\n ? config.values\n .sort((a, b) => a.order - b.order)\n .filter((value) => value.archived !== true)\n .filter(valuesFilter)\n : [];\n\n return (\n <SelectWrapper>\n <Select.Root\n onValueChange={(e: string) => {\n onChange({ value: e });\n setSelected(e);\n }}\n {...defaultValueProp}\n {...disabledProp}\n >\n {children ? children : null}\n {!children && config && (\n <>\n <Select.Trigger data-test-id={`${config.name}-select-trigger`}>\n <Select.Label>{label || config.name}</Select.Label>\n <Select.Value />\n </Select.Trigger>\n <Select.Content\n css={{ zIndex: theme.zIndices.page }}\n data-test-id={`${config.name}-select-content`}\n >\n {values.map((value) => (\n <Select.Item value={value.name} key={value.name}>\n {value.name}\n </Select.Item>\n ))}\n </Select.Content>\n </>\n )}\n </Select.Root>\n </SelectWrapper>\n );\n};\n\nconst SelectWrapper = styled('div', {\n boxSizing: 'border-box',\n display: 'flex',\n marginBottom: '$100',\n flexDirection: 'column',\n '& button': {\n padding: '1px 6px',\n },\n '& *': { boxSizing: 'border-box' },\n});\n"],"names":["CollectionBehaviors","COLLECT","DO_NOT_COLLECT","AttributesState","SUCCESS","IngestType","EXPLICIT","IMPLICIT","IngestResponseState","SYSTEM_ERROR","INVALID_TYPE","INVALID_IDENTIFIER","INVALID_DATA","INVALID_ATTRIBUTE_DEFINITION","INVALID_META_DEFINITION","UNAUTHENTICATED","MISMATCHED_IDENTIFIER","DISABLED_ATTRIBUTE_DEFINITION","hasRequiredPrivacyCookies","window","wp_usp","getCookie","countryCode","_WPGeo","WPGeo","country_code","base","ENDPOINTS","attributesCache","getAttributes","_ref","fieldName","fieldNames","url","URL","searchParams","set","join","data","fetch","toString","credentials","headers","JSON_HEADERS","json","ok","status","ResponseStatus","attributes","e","console","debug","ingest","_ref2","submitData","value","type","source","wapo_login_id","Error","attributeInfo","name","collection_behavior","jucid","localStorage","getItem","ga","payload","metadata","response","method","body","JSON","stringify","scriptSrc","staticAssets","DESelect","label","dataDictionaryConfig","defaultValue","disabled","submit","onChange","onFinished","valuesFilter","children","config","setConfig","useState","selected","setSelected","scriptStatus","useScript","useEffect","fetchConfig","_window","__twpdeu","getFieldConfigs","error","warn","ScriptStatus","READY","submitSelected","result","explicit","isError","isFinished","React","defaultValueProp","disabledProp","values","sort","a","b","order","filter","archived","SelectWrapper","Select","Root","onValueChange","Trigger","Label","Value","Content","css","zIndex","theme","zIndices","page","map","Item","key","styled","boxSizing","display","marginBottom","flexDirection","padding"],"mappings":";;;;;;;;;;;;MAQaA,mBAAmB,GAAG;EACjCC,OAAO,EAAE,SAAS;EAClBC,cAAc,EAAE;;MAeLC,eAAe,GAAG;EAC7BC,OAAO,EAAE;;MAGEC,UAAU,GAAG;EACxBC,QAAQ,EAAE,UAAU;EACpBC,QAAQ,EAAE;;MAGCC,mBAAmB,GAAG;EACjCJ,OAAO,EAAE,KAAK;EACdK,YAAY,EAAE,KAAK;EACnBC,YAAY,EAAE,KAAK;EACnBC,kBAAkB,EAAE,KAAK;EACzBC,YAAY,EAAE,KAAK;EACnBC,4BAA4B,EAAE,KAAK;EACnCC,uBAAuB,EAAE,KAAK;EAC9BC,eAAe,EAAE,KAAK;EACtBC,qBAAqB,EAAE,KAAK;EAC5BC,6BAA6B,EAAE,KAAK;EACpCf,cAAc,EAAE;;;MC3CLgB,yBAAyB,GAAGA;;EACvC,IAAI,OAAOC,MAAM,KAAK,WAAW,EAAE;IACjC,OAAO,KAAK;;EAGd,MAAMC,MAAM,GAAGC,iBAAS,CAAC,QAAQ,CAAC;EAElC,MAAMC,WAAW,IAAAC,MAAA,GAAGC,aAAK,EAAE,cAAAD,MAAA,uBAAPA,MAAA,CAASE,YAAY;EAEzC,OAAO,CAAC,EAAEL,MAAM,IAAIE,WAAW,KAAK,IAAI,CAAC;AAC3C,CAAC;;ACED,MAAMI,IAAI,MAAMC,iBAAS,CAACD,YAAY;AAEtC,MAAME,eAAe,GAAwB,EAAE;AAC/C,MAAaC,aAAa,GAAsB,MAAAC,IAAA;MAAO;IACrDC;GAGD,GAAAD,IAAA;EACC,IAAIF,eAAe,CAACG,SAAS,CAAC,EAAE;IAC9B,OAAOH,eAAe,CAACG,SAAS,CAAC;;EAGnC,MAAMC,UAAU,GAAG,CAACD,SAAS,CAAC;EAE9B,IAAI;IACF,MAAME,GAAG,GAAG,IAAIC,GAAG,I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K,KAAK,OAAG,CACD,EACjBhB,6BAACW,gBAAM,CAACM,OAAO;IACbC,GAAG,EAAE;MAAEC,MAAM,EAAEC,eAAK,CAACC,QAAQ,CAACC;KAAM;uBACnB3C,MAAM,CAACzB;KAEvBiD,MAAM,CAACoB,GAAG,CAAE3E,KAAK,IAChBoD,6BAACW,gBAAM,CAACa,IAAI;IAAC5E,KAAK,EAAEA,KAAK,CAACM,IAAI;IAAEuE,GAAG,EAAE7E,KAAK,CAACM;KACxCN,KAAK,CAACM,IAAI,CAEd,CAAC,CACa,CAEpB,CACW,CACA;AAEpB,CAAC;AAED,MAAMwD,aAAa,gBAAGgB,gBAAM,CAAC,KAAK,EAAE;EAClCC,SAAS,EAAE,YAAY;EACvBC,OAAO,EAAE,MAAM;EACfC,YAAY,EAAE,MAAM;EACpBC,aAAa,EAAE,QAAQ;EACvB,UAAU,EAAE;IACVC,OAAO,EAAE;GACV;EACD,KAAK,EAAE;IAAEJ,SAAS,EAAE;;CACrB,CAAC;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"subs-de-inputs.cjs.development.js","sources":["../src/interfaces/index.ts","../src/utils/hasRequiredPrivacyCookies.ts","../src/services/dataEnrichment.ts","../src/components/DESelect/index.tsx"],"sourcesContent":["export type AttributeValue = {\n name: string;\n date_created: Number;\n last_modified_date: Number;\n archived: boolean;\n order: number;\n};\n\nexport const CollectionBehaviors = {\n COLLECT: 'COLLECT',\n DO_NOT_COLLECT: 'DO_NOT_COLLECT',\n} as const;\n\nexport type Attribute = {\n name: string;\n approved_for_use?: boolean;\n collection_behavior?: (typeof CollectionBehaviors)[keyof typeof CollectionBehaviors];\n datatype: 'string';\n explicit: boolean;\n multiple_value: boolean;\n last_modified_date: Number;\n date_created: Number;\n values: Array<AttributeValue>;\n};\n\nexport const AttributesState = {\n SUCCESS: '100',\n} as const;\n\nexport const IngestType = {\n EXPLICIT: 'explicit',\n IMPLICIT: 'implicit',\n} as const;\n\nexport const IngestResponseState = {\n SUCCESS: '100',\n SYSTEM_ERROR: '101',\n INVALID_TYPE: '102',\n INVALID_IDENTIFIER: '103',\n INVALID_DATA: '104',\n INVALID_ATTRIBUTE_DEFINITION: '105',\n INVALID_META_DEFINITION: '106',\n UNAUTHENTICATED: '107',\n MISMATCHED_IDENTIFIER: '108',\n DISABLED_ATTRIBUTE_DEFINITION: '109',\n DO_NOT_COLLECT: '110',\n} as const;\n","import { WPGeo, getCookie } from '@washingtonpost/subs-sdk';\n\nexport const hasRequiredPrivacyCookies = () => {\n if (typeof window === 'undefined') {\n return false;\n }\n\n const wp_usp = getCookie('wp_usp');\n\n const countryCode = WPGeo()?.country_code;\n\n return !!(wp_usp && countryCode === 'US');\n};\n","import {\n ENDPOINTS,\n ResponseStatus,\n JSON_HEADERS,\n getCookie,\n} from '@washingtonpost/subs-sdk';\nimport {\n Attribute,\n CollectionBehaviors,\n IngestResponseState,\n IngestType,\n} from '../interfaces';\nimport { hasRequiredPrivacyCookies } from '../utils/hasRequiredPrivacyCookies';\n\nconst base = `${ENDPOINTS.base}/de/v1`;\n\nconst attributesCache: Record<string, any> = {};\nexport const getAttributes: GetAttributesType = async ({\n fieldName,\n}: {\n fieldName: string;\n}) => {\n if (attributesCache[fieldName]) {\n return attributesCache[fieldName];\n }\n\n const fieldNames = [fieldName];\n\n try {\n const url = new URL(`${base}/attributes`);\n url.searchParams.set('attributes', fieldNames.join(','));\n\n const data = await fetch(url.toString(), {\n credentials: 'include',\n headers: JSON_HEADERS,\n });\n const json = await data.json();\n\n if (data.ok && json.status === ResponseStatus.SUCCESS) {\n const attributes = json.attributes || [];\n attributesCache[fieldName] = attributes;\n return attributes;\n } else {\n return [];\n }\n } catch (e) {\n console.debug(e);\n return [];\n }\n};\n\ntype GetAttributesType = ({\n fieldName,\n}: {\n fieldName: string;\n}) => Promise<Attribute[]>;\n\nexport const ingest: IngestType = async ({\n submitData: { fieldName, value },\n type = IngestType.IMPLICIT,\n source,\n}) => {\n const url = `${base}/ingest`;\n\n const wapo_login_id = getCookie('wapo_login_id');\n\n if (!hasRequiredPrivacyCookies()) {\n throw new Error('does not satisfy cookie check');\n }\n\n if (!Array.isArray(value)) {\n throw new Error('value is not an array');\n }\n\n let attributeInfo = attributesCache[fieldName];\n if (!attributeInfo) {\n attributeInfo = await getAttributes({ fieldName });\n }\n\n if (\n attributeInfo[0] &&\n attributeInfo[0].name === fieldName &&\n attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT\n ) {\n throw new Error('do not collect');\n }\n\n const jucid = localStorage.getItem('uuid');\n const ga = getCookie('_ga');\n\n const payload = {\n jucid,\n ga,\n type,\n wapo_login_id, // TODO: move this to BE to read from cookie headers\n data: {\n fieldName,\n value,\n },\n metadata: { source },\n };\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: JSON_HEADERS,\n body: JSON.stringify(payload),\n });\n\n const json = await response.json();\n\n return json;\n } catch (e) {\n console.debug(e);\n return null;\n }\n};\n\ntype IngestType = ({\n submitData: { fieldName, value },\n source,\n}: {\n submitData: {\n fieldName: string;\n value: string[];\n };\n type?: (typeof IngestType)[keyof typeof IngestType];\n source: string;\n}) => Promise<{\n status: ResponseStatus;\n state: (typeof IngestResponseState)[keyof typeof IngestResponseState];\n} | null>;\n","import React, { useState, useEffect } from 'react';\nimport { Select, styled, theme } from '@washingtonpost/wpds-ui-kit';\nimport { Attribute, AttributeValue, IngestType } from '../../interfaces';\nimport { ingest } from '../../services/dataEnrichment';\nimport { ENDPOINTS, ResponseStatus } from '@washingtonpost/subs-sdk';\nimport { useScript, ScriptStatus } from '@washingtonpost/subs-hooks';\n\ninterface DESelectProps {\n source: string;\n fieldName: string;\n label?: string;\n dataDictionaryConfig?: Attribute;\n defaultValue?: string;\n disabled?: boolean;\n submit: boolean;\n onChange?: ({ value }: { value: string }) => void;\n onFinished?: ({\n isFinished,\n isError,\n }: {\n isFinished: boolean;\n isError: boolean;\n }) => void;\n valuesFilter?: (value: AttributeValue) => boolean;\n selectProps?: {\n root?: any;\n trigger?: any;\n label?: any;\n value?: any;\n content?: any;\n item?: any;\n };\n children?: React.ReactNode;\n}\n\nconst scriptSrc = `${\n ENDPOINTS.staticAssets === 'https://subscribe.washingtonpost.com/static'\n ? 'https://www.washingtonpost.com/subscribe/static/'\n : ENDPOINTS.staticAssets\n}/de-utils/twpdeu.min.js`;\n\nexport const DESelect: React.FC<DESelectProps> = ({\n source,\n fieldName,\n label,\n dataDictionaryConfig,\n defaultValue,\n disabled,\n submit,\n onChange = () => {},\n onFinished = () => {},\n valuesFilter = () => true,\n children,\n}) => {\n const [config, setConfig] = useState(dataDictionaryConfig);\n\n const [selected, setSelected] = useState('');\n\n const scriptStatus = useScript(scriptSrc);\n\n useEffect(() => {\n const fetchConfig = async () => {\n try {\n const config = await window?.__twpdeu?.getFieldConfigs({ fieldName });\n if (config) {\n setConfig(config[0]);\n } else {\n console.error('unable to get config', fieldName);\n }\n } catch (e) {\n console.warn('unable to get config', fieldName, e);\n }\n };\n\n if (scriptStatus === ScriptStatus.READY && !(children || config)) {\n fetchConfig();\n }\n }, [scriptStatus]);\n\n useEffect(() => {\n const submitSelected = async () => {\n try {\n // TODO: Switch to window.__twpdeu.push\n // TODO: Log to GA\n const result = await ingest({\n submitData: { fieldName, value: [selected] },\n type: config?.explicit ? IngestType.EXPLICIT : IngestType.IMPLICIT,\n source,\n });\n const isError = result\n ? result.status !== ResponseStatus.SUCCESS\n : true;\n\n onFinished({\n isFinished: true,\n isError,\n });\n } catch (e) {\n onFinished({\n isFinished: false,\n isError: true,\n });\n }\n };\n\n if (submit && selected) {\n submitSelected();\n }\n }, [submit, selected]);\n\n if (!(children || config)) {\n return <span>loading</span>;\n }\n\n const defaultValueProp = defaultValue ? { defaultValue } : {};\n\n const disabledProp = disabled ? { disabled: true } : {};\n\n // sort and filter out archived values\n const values = config\n ? config.values\n .sort((a, b) => a.order - b.order)\n .filter((value) => value.archived !== true)\n .filter(valuesFilter)\n : [];\n\n return (\n <SelectWrapper>\n <Select.Root\n onValueChange={(e: string) => {\n onChange({ value: e });\n setSelected(e);\n }}\n {...defaultValueProp}\n {...disabledProp}\n >\n {children ? children : null}\n {!children && config && (\n <>\n <Select.Trigger data-test-id={`${config.name}-select-trigger`}>\n <Select.Label>{label || config.name}</Select.Label>\n <Select.Value />\n </Select.Trigger>\n <Select.Content\n css={{ zIndex: theme.zIndices.page }}\n data-test-id={`${config.name}-select-content`}\n >\n {values.map((value) => (\n <Select.Item value={value.name} key={value.name}>\n {value.name}\n </Select.Item>\n ))}\n </Select.Content>\n </>\n )}\n </Select.Root>\n </SelectWrapper>\n );\n};\n\nconst SelectWrapper = styled('div', {\n boxSizing: 'border-box',\n display: 'flex',\n marginBottom: '$100',\n flexDirection: 'column',\n '& button': {\n padding: '1px 6px',\n },\n '& *': { boxSizing: 'border-box' },\n});\n"],"names":["CollectionBehaviors","COLLECT","DO_NOT_COLLECT","AttributesState","SUCCESS","IngestType","EXPLICIT","IMPLICIT","IngestResponseState","SYSTEM_ERROR","INVALID_TYPE","INVALID_IDENTIFIER","INVALID_DATA","INVALID_ATTRIBUTE_DEFINITION","INVALID_META_DEFINITION","UNAUTHENTICATED","MISMATCHED_IDENTIFIER","DISABLED_ATTRIBUTE_DEFINITION","hasRequiredPrivacyCookies","window","wp_usp","getCookie","countryCode","_WPGeo","WPGeo","country_code","base","ENDPOINTS","attributesCache","getAttributes","_ref","fieldName","fieldNames","url","URL","searchParams","set","join","data","fetch","toString","credentials","headers","JSON_HEADERS","json","ok","status","ResponseStatus","attributes","e","console","debug","ingest","_ref2","submitData","value","type","source","wapo_login_id","Error","Array","isArray","attributeInfo","name","collection_behavior","jucid","localStorage","getItem","ga","payload","metadata","response","method","body","JSON","stringify","scriptSrc","staticAssets","DESelect","label","dataDictionaryConfig","defaultValue","disabled","submit","onChange","onFinished","valuesFilter","children","config","setConfig","useState","selected","setSelected","scriptStatus","useScript","useEffect","fetchConfig","_window","__twpdeu","getFieldConfigs","error","warn","ScriptStatus","READY","submitSelected","result","explicit","isError","isFinished","React","defaultValueProp","disabledProp","values","sort","a","b","order","filter","archived","SelectWrapper","Select","Root","onValueChange","Trigger","Label","Value","Content","css","zIndex","theme","zIndices","page","map","Item","key","styled","boxSizing","display","marginBottom","flexDirection","padding"],"mappings":";;;;;;;;;;;;MAQaA,mBAAmB,GAAG;EACjCC,OAAO,EAAE,SAAS;EAClBC,cAAc,EAAE;;MAeLC,eAAe,GAAG;EAC7BC,OAAO,EAAE;;MAGEC,UAAU,GAAG;EACxBC,QAAQ,EAAE,UAAU;EACpBC,QAAQ,EAAE;;MAGCC,mBAAmB,GAAG;EACjCJ,OAAO,EAAE,KAAK;EACdK,YAAY,EAAE,KAAK;EACnBC,YAAY,EAAE,KAAK;EACnBC,kBAAkB,EAAE,KAAK;EACzBC,YAAY,EAAE,KAAK;EACnBC,4BAA4B,EAAE,KAAK;EACnCC,uBAAuB,EAAE,KAAK;EAC9BC,eAAe,EAAE,KAAK;EACtBC,qBAAqB,EAAE,KAAK;EAC5BC,6BAA6B,EAAE,KAAK;EACpCf,cAAc,EAAE;;;MC3CLgB,yBAAyB,GAAGA;;EACvC,IAAI,OAAOC,MAAM,KAAK,WAAW,EAAE;IACjC,OAAO,KAAK;;EAGd,MAAMC,MAAM,GAAGC,iBAAS,CAAC,QAAQ,CAAC;EAElC,MAAMC,WAAW,IAAAC,MAAA,GAAGC,aAAK,EAAE,cAAAD,MAAA,uBAAPA,MAAA,CAASE,YAAY;EAEzC,OAAO,CAAC,EAAEL,MAAM,IAAIE,WAAW,KAAK,IAAI,CAAC;AAC3C,CAAC;;ACED,MAAMI,IAAI,MAAMC,iBAAS,CAACD,YAAY;AAEtC,MAAME,eAAe,GAAwB,EAAE;AAC/C,MAAaC,aAAa,GAAsB,MAAAC,IAAA;MAAO;IACrDC;GAGD,GAAAD,IAAA;EACC,IAAIF,eAAe,CAACG,SAAS,CAAC,EAAE;IAC9B,OAAOH,eAAe,CAACG,SAAS,CAAC;;EAGnC,MAAMC,U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,GAAG,IAAI,EAC1B,CAACA,QAAQ,IAAIC,MAAM,IAClBqB,4DACEA,6BAACW,gBAAM,CAACG,OAAO;uBAAkBnC,MAAM,CAACzB;KACtC8C,6BAACW,gBAAM,CAACI,KAAK,QAAE7C,KAAK,IAAIS,MAAM,CAACzB,IAAI,CAAgB,EACnD8C,6BAACW,gBAAM,CAACK,KAAK,OAAG,CACD,EACjBhB,6BAACW,gBAAM,CAACM,OAAO;IACbC,GAAG,EAAE;MAAEC,MAAM,EAAEC,eAAK,CAACC,QAAQ,CAACC;KAAM;uBACnB3C,MAAM,CAACzB;KAEvBiD,MAAM,CAACoB,GAAG,CAAE7E,KAAK,IAChBsD,6BAACW,gBAAM,CAACa,IAAI;IAAC9E,KAAK,EAAEA,KAAK,CAACQ,IAAI;IAAEuE,GAAG,EAAE/E,KAAK,CAACQ;KACxCR,KAAK,CAACQ,IAAI,CAEd,CAAC,CACa,CAEpB,CACW,CACA;AAEpB,CAAC;AAED,MAAMwD,aAAa,gBAAGgB,gBAAM,CAAC,KAAK,EAAE;EAClCC,SAAS,EAAE,YAAY;EACvBC,OAAO,EAAE,MAAM;EACfC,YAAY,EAAE,MAAM;EACpBC,aAAa,EAAE,QAAQ;EACvB,UAAU,EAAE;IACVC,OAAO,EAAE;GACV;EACD,KAAK,EAAE;IAAEJ,SAAS,EAAE;;CACrB,CAAC;;;;;;;;;;;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("@washingtonpost/subs-sdk"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("@washingtonpost/subs-sdk"),a=require("react"),s=(e=a)&&"object"==typeof e&&"default"in e?e.default:e,o=require("@washingtonpost/wpds-ui-kit"),i=require("@washingtonpost/subs-hooks");const n={COLLECT:"COLLECT",DO_NOT_COLLECT:"DO_NOT_COLLECT"},r={EXPLICIT:"explicit",IMPLICIT:"implicit"},l=()=>{var e;if("undefined"==typeof window)return!1;const a=t.getCookie("wp_usp"),s=null===(e=t.WPGeo())||void 0===e?void 0:e.country_code;return!(!a||"US"!==s)},c=t.ENDPOINTS.base+"/de/v1",u={},d=async e=>{let{fieldName:a}=e;if(u[a])return u[a];const s=[a];try{const e=new URL(c+"/attributes");e.searchParams.set("attributes",s.join(","));const o=await fetch(e.toString(),{credentials:"include",headers:t.JSON_HEADERS}),i=await o.json();if(o.ok&&i.status===t.ResponseStatus.SUCCESS){const e=i.attributes||[];return u[a]=e,e}return[]}catch(e){return console.debug(e),[]}},E=async e=>{let{submitData:{fieldName:a,value:s},type:o=r.IMPLICIT,source:i}=e;const E=c+"/ingest",I=t.getCookie("wapo_login_id");if(!l())throw new Error("does not satisfy cookie check");if(!Array.isArray(s))throw new Error("value is not an array");let S=u[a];if(S||(S=await d({fieldName:a})),S[0]&&S[0].name===a&&S[0].collection_behavior===n.DO_NOT_COLLECT)throw new Error("do not collect");const p={jucid:localStorage.getItem("uuid"),ga:t.getCookie("_ga"),type:o,wapo_login_id:I,data:{fieldName:a,value:s},metadata:{source:i}};try{const e=await fetch(E,{method:"POST",credentials:"include",headers:t.JSON_HEADERS,body:JSON.stringify(p)});return await e.json()}catch(e){return console.debug(e),null}},I=("https://subscribe.washingtonpost.com/static"===t.ENDPOINTS.staticAssets?"https://www.washingtonpost.com/subscribe/static/":t.ENDPOINTS.staticAssets)+"/de-utils/twpdeu.min.js",S=o.styled("div",{boxSizing:"border-box",display:"flex",marginBottom:"$100",flexDirection:"column","& button":{padding:"1px 6px"},"& *":{boxSizing:"border-box"}});exports.AttributesState={SUCCESS:"100"},exports.CollectionBehaviors=n,exports.DESelect=e=>{let{source:n,fieldName:l,label:c,dataDictionaryConfig:u,defaultValue:d,disabled:p,submit:g,onChange:m=(()=>{}),onFinished:T=(()=>{}),valuesFilter:f=(()=>!0),children:C}=e;const[N,b]=a.useState(u),[h,w]=a.useState(""),_=i.useScript(I);if(a.useEffect(()=>{_!==i.ScriptStatus.READY||C||N||(async()=>{try{var e;const t=await(null===(e=window)||void 0===e||null===(e=e.__twpdeu)||void 0===e?void 0:e.getFieldConfigs({fieldName:l}));t?b(t[0]):console.error("unable to get config",l)}catch(e){console.warn("unable to get config",l,e)}})()},[_]),a.useEffect(()=>{g&&h&&(async()=>{try{const e=await E({submitData:{fieldName:l,value:[h]},type:null!=N&&N.explicit?r.EXPLICIT:r.IMPLICIT,source:n});T({isFinished:!0,isError:!e||e.status!==t.ResponseStatus.SUCCESS})}catch(e){T({isFinished:!1,isError:!0})}})()},[g,h]),!C&&!N)return s.createElement("span",null,"loading");const D=d?{defaultValue:d}:{},y=p?{disabled:!0}:{},O=N?N.values.sort((e,t)=>e.order-t.order).filter(e=>!0!==e.archived).filter(f):[];return s.createElement(S,null,s.createElement(o.Select.Root,{onValueChange:e=>{m({value:e}),w(e)},...D,...y},C||null,!C&&N&&s.createElement(s.Fragment,null,s.createElement(o.Select.Trigger,{"data-test-id":N.name+"-select-trigger"},s.createElement(o.Select.Label,null,c||N.name),s.createElement(o.Select.Value,null)),s.createElement(o.Select.Content,{css:{zIndex:o.theme.zIndices.page},"data-test-id":N.name+"-select-content"},O.map(e=>s.createElement(o.Select.Item,{value:e.name,key:e.name},e.name))))))},exports.IngestResponseState={SUCCESS:"100",SYSTEM_ERROR:"101",INVALID_TYPE:"102",INVALID_IDENTIFIER:"103",INVALID_DATA:"104",INVALID_ATTRIBUTE_DEFINITION:"105",INVALID_META_DEFINITION:"106",UNAUTHENTICATED:"107",MISMATCHED_IDENTIFIER:"108",DISABLED_ATTRIBUTE_DEFINITION:"109",DO_NOT_COLLECT:"110"},exports.IngestType=r,exports.getAttributes=d,exports.hasRequiredPrivacyCookies=l,exports.ingest=E;
|
|
2
2
|
//# sourceMappingURL=subs-de-inputs.cjs.production.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subs-de-inputs.cjs.production.min.js","sources":["../src/interfaces/index.ts","../src/utils/hasRequiredPrivacyCookies.ts","../src/services/dataEnrichment.ts","../src/components/DESelect/index.tsx"],"sourcesContent":["export type AttributeValue = {\n name: string;\n date_created: Number;\n last_modified_date: Number;\n archived: boolean;\n order: number;\n};\n\nexport const CollectionBehaviors = {\n COLLECT: 'COLLECT',\n DO_NOT_COLLECT: 'DO_NOT_COLLECT',\n} as const;\n\nexport type Attribute = {\n name: string;\n approved_for_use?: boolean;\n collection_behavior?: (typeof CollectionBehaviors)[keyof typeof CollectionBehaviors];\n datatype: 'string';\n explicit: boolean;\n multiple_value: boolean;\n last_modified_date: Number;\n date_created: Number;\n values: Array<AttributeValue>;\n};\n\nexport const AttributesState = {\n SUCCESS: '100',\n} as const;\n\nexport const IngestType = {\n EXPLICIT: 'explicit',\n IMPLICIT: 'implicit',\n} as const;\n\nexport const IngestResponseState = {\n SUCCESS: '100',\n SYSTEM_ERROR: '101',\n INVALID_TYPE: '102',\n INVALID_IDENTIFIER: '103',\n INVALID_DATA: '104',\n INVALID_ATTRIBUTE_DEFINITION: '105',\n INVALID_META_DEFINITION: '106',\n UNAUTHENTICATED: '107',\n MISMATCHED_IDENTIFIER: '108',\n DISABLED_ATTRIBUTE_DEFINITION: '109',\n DO_NOT_COLLECT: '110',\n} as const;\n","import { WPGeo, getCookie } from '@washingtonpost/subs-sdk';\n\nexport const hasRequiredPrivacyCookies = () => {\n if (typeof window === 'undefined') {\n return false;\n }\n\n const wp_usp = getCookie('wp_usp');\n\n const countryCode = WPGeo()?.country_code;\n\n return !!(wp_usp && countryCode === 'US');\n};\n","import {\n ENDPOINTS,\n ResponseStatus,\n JSON_HEADERS,\n getCookie,\n} from '@washingtonpost/subs-sdk';\nimport {\n Attribute,\n CollectionBehaviors,\n IngestResponseState,\n IngestType,\n} from '../interfaces';\nimport { hasRequiredPrivacyCookies } from '../utils/hasRequiredPrivacyCookies';\n\nconst base = `${ENDPOINTS.base}/de/v1`;\n\nconst attributesCache: Record<string, any> = {};\nexport const getAttributes: GetAttributesType = async ({\n fieldName,\n}: {\n fieldName: string;\n}) => {\n if (attributesCache[fieldName]) {\n return attributesCache[fieldName];\n }\n\n const fieldNames = [fieldName];\n\n try {\n const url = new URL(`${base}/attributes`);\n url.searchParams.set('attributes', fieldNames.join(','));\n\n const data = await fetch(url.toString(), {\n credentials: 'include',\n headers: JSON_HEADERS,\n });\n const json = await data.json();\n\n if (data.ok && json.status === ResponseStatus.SUCCESS) {\n const attributes = json.attributes || [];\n attributesCache[fieldName] = attributes;\n return attributes;\n } else {\n return [];\n }\n } catch (e) {\n console.debug(e);\n return [];\n }\n};\n\ntype GetAttributesType = ({\n fieldName,\n}: {\n fieldName: string;\n}) => Promise<Attribute[]>;\n\nexport const ingest: IngestType = async ({\n submitData: { fieldName, value },\n type,\n source,\n}) => {\n const url = `${base}/ingest`;\n\n const wapo_login_id = getCookie('wapo_login_id');\n\n if (!hasRequiredPrivacyCookies()) {\n throw new Error('does not satisfy cookie check');\n }\n\n let attributeInfo = attributesCache[fieldName];\n if (!attributeInfo) {\n attributeInfo = await getAttributes({ fieldName });\n }\n\n if (\n attributeInfo[0] &&\n attributeInfo[0].name === fieldName &&\n attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT\n ) {\n throw new Error('do not collect');\n }\n\n const jucid = localStorage.getItem('uuid');\n const ga = getCookie('_ga');\n\n const payload = {\n jucid,\n ga,\n type,\n wapo_login_id, // TODO: move this to BE to read from cookie headers\n data: {\n fieldName,\n value,\n },\n metadata: { source },\n };\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: JSON_HEADERS,\n body: JSON.stringify(payload),\n });\n\n const json = await response.json();\n\n return json;\n } catch (e) {\n console.debug(e);\n return null;\n }\n};\n\ntype IngestType = ({\n submitData: { fieldName, value },\n source,\n}: {\n submitData: {\n fieldName: string;\n value: string[];\n };\n type: (typeof IngestType)[keyof typeof IngestType];\n source: string;\n}) => Promise<{\n status: ResponseStatus;\n state: (typeof IngestResponseState)[keyof typeof IngestResponseState];\n} | null>;\n","import React, { useState, useEffect } from 'react';\nimport { Select, styled, theme } from '@washingtonpost/wpds-ui-kit';\nimport { Attribute, AttributeValue, IngestType } from '../../interfaces';\nimport { ingest } from '../../services/dataEnrichment';\nimport { ENDPOINTS, ResponseStatus } from '@washingtonpost/subs-sdk';\nimport { useScript, ScriptStatus } from '@washingtonpost/subs-hooks';\n\ninterface DESelectProps {\n source: string;\n fieldName: string;\n label?: string;\n dataDictionaryConfig?: Attribute;\n defaultValue?: string;\n disabled?: boolean;\n submit: boolean;\n onChange?: ({ value }: { value: string }) => void;\n onFinished?: ({\n isFinished,\n isError,\n }: {\n isFinished: boolean;\n isError: boolean;\n }) => void;\n valuesFilter?: (value: AttributeValue) => boolean;\n selectProps?: {\n root?: any;\n trigger?: any;\n label?: any;\n value?: any;\n content?: any;\n item?: any;\n };\n children?: React.ReactNode;\n}\n\nconst scriptSrc = `${\n ENDPOINTS.staticAssets === 'https://subscribe.washingtonpost.com/static'\n ? 'https://www.washingtonpost.com/subscribe/static/'\n : ENDPOINTS.staticAssets\n}/de-utils/twpdeu.min.js`;\n\nexport const DESelect: React.FC<DESelectProps> = ({\n source,\n fieldName,\n label,\n dataDictionaryConfig,\n defaultValue,\n disabled,\n submit,\n onChange = () => {},\n onFinished = () => {},\n valuesFilter = () => true,\n children,\n}) => {\n const [config, setConfig] = useState(dataDictionaryConfig);\n\n const [selected, setSelected] = useState('');\n\n const scriptStatus = useScript(scriptSrc);\n\n useEffect(() => {\n const fetchConfig = async () => {\n try {\n const config = await window?.__twpdeu?.getFieldConfigs({ fieldName });\n if (config) {\n setConfig(config[0]);\n } else {\n console.error('unable to get config', fieldName);\n }\n } catch (e) {\n console.warn('unable to get config', fieldName, e);\n }\n };\n\n if (scriptStatus === ScriptStatus.READY && !(children || config)) {\n fetchConfig();\n }\n }, [scriptStatus]);\n\n useEffect(() => {\n const submitSelected = async () => {\n try {\n // TODO: Switch to window.__twpdeu.push\n // TODO: Log to GA\n const result = await ingest({\n submitData: { fieldName, value: [selected] },\n type: config?.explicit ? IngestType.EXPLICIT : IngestType.IMPLICIT,\n source,\n });\n const isError = result\n ? result.status !== ResponseStatus.SUCCESS\n : true;\n\n onFinished({\n isFinished: true,\n isError,\n });\n } catch (e) {\n onFinished({\n isFinished: false,\n isError: true,\n });\n }\n };\n\n if (submit && selected) {\n submitSelected();\n }\n }, [submit, selected]);\n\n if (!(children || config)) {\n return <span>loading</span>;\n }\n\n const defaultValueProp = defaultValue ? { defaultValue } : {};\n\n const disabledProp = disabled ? { disabled: true } : {};\n\n // sort and filter out archived values\n const values = config\n ? config.values\n .sort((a, b) => a.order - b.order)\n .filter((value) => value.archived !== true)\n .filter(valuesFilter)\n : [];\n\n return (\n <SelectWrapper>\n <Select.Root\n onValueChange={(e: string) => {\n onChange({ value: e });\n setSelected(e);\n }}\n {...defaultValueProp}\n {...disabledProp}\n >\n {children ? children : null}\n {!children && config && (\n <>\n <Select.Trigger data-test-id={`${config.name}-select-trigger`}>\n <Select.Label>{label || config.name}</Select.Label>\n <Select.Value />\n </Select.Trigger>\n <Select.Content\n css={{ zIndex: theme.zIndices.page }}\n data-test-id={`${config.name}-select-content`}\n >\n {values.map((value) => (\n <Select.Item value={value.name} key={value.name}>\n {value.name}\n </Select.Item>\n ))}\n </Select.Content>\n </>\n )}\n </Select.Root>\n </SelectWrapper>\n );\n};\n\nconst SelectWrapper = styled('div', {\n boxSizing: 'border-box',\n display: 'flex',\n marginBottom: '$100',\n flexDirection: 'column',\n '& button': {\n padding: '1px 6px',\n },\n '& *': { boxSizing: 'border-box' },\n});\n"],"names":["CollectionBehaviors","COLLECT","DO_NOT_COLLECT","IngestType","EXPLICIT","IMPLICIT","hasRequiredPrivacyCookies","window","wp_usp","getCookie","countryCode","_WPGeo","WPGeo","country_code","base","ENDPOINTS","attributesCache","getAttributes","async","fieldName","_ref","fieldNames","url","URL","searchParams","set","join","data","fetch","toString","credentials","headers","JSON_HEADERS","json","ok","status","ResponseStatus","SUCCESS","attributes","e","console","debug","ingest","submitData","value","type","source","_ref2","wapo_login_id","Error","attributeInfo","name","collection_behavior","payload","jucid","localStorage","getItem","ga","metadata","response","method","body","JSON","stringify","scriptSrc","staticAssets","SelectWrapper","styled","boxSizing","display","marginBottom","flexDirection","& button","padding","& *","label","dataDictionaryConfig","defaultValue","disabled","submit","onChange","onFinished","valuesFilter","children","config","setConfig","useState","selected","setSelected","scriptStatus","useScript","useEffect","ScriptStatus","READY","_window","__twpdeu","getFieldConfigs","error","warn","fetchConfig","result","explicit","isFinished","isError","submitSelected","React","defaultValueProp","disabledProp","values","sort","a","b","order","filter","archived","Select","Root","onValueChange","Trigger","Label","Value","Content","css","zIndex","theme","zIndices","page","map","Item","key","SYSTEM_ERROR","INVALID_TYPE","INVALID_IDENTIFIER","INVALID_DATA","INVALID_ATTRIBUTE_DEFINITION","INVALID_META_DEFINITION","UNAUTHENTICATED","MISMATCHED_IDENTIFIER","DISABLED_ATTRIBUTE_DEFINITION"],"mappings":"iRAQaA,EAAsB,CACjCC,QAAS,UACTC,eAAgB,kBAmBLC,EAAa,CACxBC,SAAU,WACVC,SAAU,YC7BCC,EAA4BA,WACvC,GAAsB,oBAAXC,OACT,OAAO,EAGT,MAAMC,EAASC,YAAU,UAEnBC,UAAWC,EAAGC,qBAAOD,SAAPA,EAASE,aAE7B,SAAUL,GAA0B,OAAhBE,ICGhBI,EAAUC,YAAUD,cAEpBE,EAAuC,GAChCC,EAAmCC,MAAAA,QAAOC,UACrDA,GAGDC,EACC,GAAIJ,EAAgBG,GAClB,OAAOH,EAAgBG,GAGzB,MAAME,EAAa,CAACF,GAEpB,IACE,MAAMG,EAAM,IAAIC,IAAOT,iBACvBQ,EAAIE,aAAaC,IAAI,aAAcJ,EAAWK,KAAK,MAEnD,MAAMC,QAAaC,MAAMN,EAAIO,WAAY,CACvCC,YAAa,UACbC,QAASC,iBAELC,QAAaN,EAAKM,OAExB,GAAIN,EAAKO,IAAMD,EAAKE,SAAWC,iBAAeC,QAAS,CACrD,MA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ZqB,gCACEA,gBAACU,SAAOG,wBAAyBlC,EAAOjC,wBACtCsD,gBAACU,SAAOI,WAAO5C,GAASS,EAAOjC,MAC/BsD,gBAACU,SAAOK,aAEVf,gBAACU,SAAOM,SACNC,IAAK,CAAEC,OAAQC,QAAMC,SAASC,qBACb1C,EAAOjC,wBAEvByD,EAAOmB,IAAKnF,GACX6D,gBAACU,SAAOa,MAAKpF,MAAOA,EAAMO,KAAM8E,IAAKrF,EAAMO,MACxCP,EAAMO,wCHnHU,CACjCd,QAAS,MACT6F,aAAc,MACdC,aAAc,MACdC,mBAAoB,MACpBC,aAAc,MACdC,6BAA8B,MAC9BC,wBAAyB,MACzBC,gBAAiB,MACjBC,sBAAuB,MACvBC,8BAA+B,MAC/BxI,eAAgB"}
|
|
1
|
+
{"version":3,"file":"subs-de-inputs.cjs.production.min.js","sources":["../src/interfaces/index.ts","../src/utils/hasRequiredPrivacyCookies.ts","../src/services/dataEnrichment.ts","../src/components/DESelect/index.tsx"],"sourcesContent":["export type AttributeValue = {\n name: string;\n date_created: Number;\n last_modified_date: Number;\n archived: boolean;\n order: number;\n};\n\nexport const CollectionBehaviors = {\n COLLECT: 'COLLECT',\n DO_NOT_COLLECT: 'DO_NOT_COLLECT',\n} as const;\n\nexport type Attribute = {\n name: string;\n approved_for_use?: boolean;\n collection_behavior?: (typeof CollectionBehaviors)[keyof typeof CollectionBehaviors];\n datatype: 'string';\n explicit: boolean;\n multiple_value: boolean;\n last_modified_date: Number;\n date_created: Number;\n values: Array<AttributeValue>;\n};\n\nexport const AttributesState = {\n SUCCESS: '100',\n} as const;\n\nexport const IngestType = {\n EXPLICIT: 'explicit',\n IMPLICIT: 'implicit',\n} as const;\n\nexport const IngestResponseState = {\n SUCCESS: '100',\n SYSTEM_ERROR: '101',\n INVALID_TYPE: '102',\n INVALID_IDENTIFIER: '103',\n INVALID_DATA: '104',\n INVALID_ATTRIBUTE_DEFINITION: '105',\n INVALID_META_DEFINITION: '106',\n UNAUTHENTICATED: '107',\n MISMATCHED_IDENTIFIER: '108',\n DISABLED_ATTRIBUTE_DEFINITION: '109',\n DO_NOT_COLLECT: '110',\n} as const;\n","import { WPGeo, getCookie } from '@washingtonpost/subs-sdk';\n\nexport const hasRequiredPrivacyCookies = () => {\n if (typeof window === 'undefined') {\n return false;\n }\n\n const wp_usp = getCookie('wp_usp');\n\n const countryCode = WPGeo()?.country_code;\n\n return !!(wp_usp && countryCode === 'US');\n};\n","import {\n ENDPOINTS,\n ResponseStatus,\n JSON_HEADERS,\n getCookie,\n} from '@washingtonpost/subs-sdk';\nimport {\n Attribute,\n CollectionBehaviors,\n IngestResponseState,\n IngestType,\n} from '../interfaces';\nimport { hasRequiredPrivacyCookies } from '../utils/hasRequiredPrivacyCookies';\n\nconst base = `${ENDPOINTS.base}/de/v1`;\n\nconst attributesCache: Record<string, any> = {};\nexport const getAttributes: GetAttributesType = async ({\n fieldName,\n}: {\n fieldName: string;\n}) => {\n if (attributesCache[fieldName]) {\n return attributesCache[fieldName];\n }\n\n const fieldNames = [fieldName];\n\n try {\n const url = new URL(`${base}/attributes`);\n url.searchParams.set('attributes', fieldNames.join(','));\n\n const data = await fetch(url.toString(), {\n credentials: 'include',\n headers: JSON_HEADERS,\n });\n const json = await data.json();\n\n if (data.ok && json.status === ResponseStatus.SUCCESS) {\n const attributes = json.attributes || [];\n attributesCache[fieldName] = attributes;\n return attributes;\n } else {\n return [];\n }\n } catch (e) {\n console.debug(e);\n return [];\n }\n};\n\ntype GetAttributesType = ({\n fieldName,\n}: {\n fieldName: string;\n}) => Promise<Attribute[]>;\n\nexport const ingest: IngestType = async ({\n submitData: { fieldName, value },\n type = IngestType.IMPLICIT,\n source,\n}) => {\n const url = `${base}/ingest`;\n\n const wapo_login_id = getCookie('wapo_login_id');\n\n if (!hasRequiredPrivacyCookies()) {\n throw new Error('does not satisfy cookie check');\n }\n\n if (!Array.isArray(value)) {\n throw new Error('value is not an array');\n }\n\n let attributeInfo = attributesCache[fieldName];\n if (!attributeInfo) {\n attributeInfo = await getAttributes({ fieldName });\n }\n\n if (\n attributeInfo[0] &&\n attributeInfo[0].name === fieldName &&\n attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT\n ) {\n throw new Error('do not collect');\n }\n\n const jucid = localStorage.getItem('uuid');\n const ga = getCookie('_ga');\n\n const payload = {\n jucid,\n ga,\n type,\n wapo_login_id, // TODO: move this to BE to read from cookie headers\n data: {\n fieldName,\n value,\n },\n metadata: { source },\n };\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: JSON_HEADERS,\n body: JSON.stringify(payload),\n });\n\n const json = await response.json();\n\n return json;\n } catch (e) {\n console.debug(e);\n return null;\n }\n};\n\ntype IngestType = ({\n submitData: { fieldName, value },\n source,\n}: {\n submitData: {\n fieldName: string;\n value: string[];\n };\n type?: (typeof IngestType)[keyof typeof IngestType];\n source: string;\n}) => Promise<{\n status: ResponseStatus;\n state: (typeof IngestResponseState)[keyof typeof IngestResponseState];\n} | null>;\n","import React, { useState, useEffect } from 'react';\nimport { Select, styled, theme } from '@washingtonpost/wpds-ui-kit';\nimport { Attribute, AttributeValue, IngestType } from '../../interfaces';\nimport { ingest } from '../../services/dataEnrichment';\nimport { ENDPOINTS, ResponseStatus } from '@washingtonpost/subs-sdk';\nimport { useScript, ScriptStatus } from '@washingtonpost/subs-hooks';\n\ninterface DESelectProps {\n source: string;\n fieldName: string;\n label?: string;\n dataDictionaryConfig?: Attribute;\n defaultValue?: string;\n disabled?: boolean;\n submit: boolean;\n onChange?: ({ value }: { value: string }) => void;\n onFinished?: ({\n isFinished,\n isError,\n }: {\n isFinished: boolean;\n isError: boolean;\n }) => void;\n valuesFilter?: (value: AttributeValue) => boolean;\n selectProps?: {\n root?: any;\n trigger?: any;\n label?: any;\n value?: any;\n content?: any;\n item?: any;\n };\n children?: React.ReactNode;\n}\n\nconst scriptSrc = `${\n ENDPOINTS.staticAssets === 'https://subscribe.washingtonpost.com/static'\n ? 'https://www.washingtonpost.com/subscribe/static/'\n : ENDPOINTS.staticAssets\n}/de-utils/twpdeu.min.js`;\n\nexport const DESelect: React.FC<DESelectProps> = ({\n source,\n fieldName,\n label,\n dataDictionaryConfig,\n defaultValue,\n disabled,\n submit,\n onChange = () => {},\n onFinished = () => {},\n valuesFilter = () => true,\n children,\n}) => {\n const [config, setConfig] = useState(dataDictionaryConfig);\n\n const [selected, setSelected] = useState('');\n\n const scriptStatus = useScript(scriptSrc);\n\n useEffect(() => {\n const fetchConfig = async () => {\n try {\n const config = await window?.__twpdeu?.getFieldConfigs({ fieldName });\n if (config) {\n setConfig(config[0]);\n } else {\n console.error('unable to get config', fieldName);\n }\n } catch (e) {\n console.warn('unable to get config', fieldName, e);\n }\n };\n\n if (scriptStatus === ScriptStatus.READY && !(children || config)) {\n fetchConfig();\n }\n }, [scriptStatus]);\n\n useEffect(() => {\n const submitSelected = async () => {\n try {\n // TODO: Switch to window.__twpdeu.push\n // TODO: Log to GA\n const result = await ingest({\n submitData: { fieldName, value: [selected] },\n type: config?.explicit ? IngestType.EXPLICIT : IngestType.IMPLICIT,\n source,\n });\n const isError = result\n ? result.status !== ResponseStatus.SUCCESS\n : true;\n\n onFinished({\n isFinished: true,\n isError,\n });\n } catch (e) {\n onFinished({\n isFinished: false,\n isError: true,\n });\n }\n };\n\n if (submit && selected) {\n submitSelected();\n }\n }, [submit, selected]);\n\n if (!(children || config)) {\n return <span>loading</span>;\n }\n\n const defaultValueProp = defaultValue ? { defaultValue } : {};\n\n const disabledProp = disabled ? { disabled: true } : {};\n\n // sort and filter out archived values\n const values = config\n ? config.values\n .sort((a, b) => a.order - b.order)\n .filter((value) => value.archived !== true)\n .filter(valuesFilter)\n : [];\n\n return (\n <SelectWrapper>\n <Select.Root\n onValueChange={(e: string) => {\n onChange({ value: e });\n setSelected(e);\n }}\n {...defaultValueProp}\n {...disabledProp}\n >\n {children ? children : null}\n {!children && config && (\n <>\n <Select.Trigger data-test-id={`${config.name}-select-trigger`}>\n <Select.Label>{label || config.name}</Select.Label>\n <Select.Value />\n </Select.Trigger>\n <Select.Content\n css={{ zIndex: theme.zIndices.page }}\n data-test-id={`${config.name}-select-content`}\n >\n {values.map((value) => (\n <Select.Item value={value.name} key={value.name}>\n {value.name}\n </Select.Item>\n ))}\n </Select.Content>\n </>\n )}\n </Select.Root>\n </SelectWrapper>\n );\n};\n\nconst SelectWrapper = styled('div', {\n boxSizing: 'border-box',\n display: 'flex',\n marginBottom: '$100',\n flexDirection: 'column',\n '& button': {\n padding: '1px 6px',\n },\n '& *': { boxSizing: 'border-box' },\n});\n"],"names":["CollectionBehaviors","COLLECT","DO_NOT_COLLECT","IngestType","EXPLICIT","IMPLICIT","hasRequiredPrivacyCookies","window","wp_usp","getCookie","countryCode","_WPGeo","WPGeo","country_code","base","ENDPOINTS","attributesCache","getAttributes","async","fieldName","_ref","fieldNames","url","URL","searchParams","set","join","data","fetch","toString","credentials","headers","JSON_HEADERS","json","ok","status","ResponseStatus","SUCCESS","attributes","e","console","debug","ingest","submitData","value","type","source","_ref2","wapo_login_id","Error","Array","isArray","attributeInfo","name","collection_behavior","payload","jucid","localStorage","getItem","ga","metadata","response","method","body","JSON","stringify","scriptSrc","staticAssets","SelectWrapper","styled","boxSizing","display","marginBottom","flexDirection","& button","padding","& *","label","dataDictionaryConfig","defaultValue","disabled","submit","onChange","onFinished","valuesFilter","children","config","setConfig","useState","selected","setSelected","scriptStatus","useScript","useEffect","ScriptStatus","READY","_window","__twpdeu","getFieldConfigs","error","warn","fetchConfig","result","explicit","isFinished","isError","submitSelected","React","defaultValueProp","disabledProp","values","sort","a","b","order","filter","archived","Select","Root","onValueChange","Trigger","Label","Value","Content","css","zIndex","theme","zIndices","page","map","Item","key","SYSTEM_ERROR","INVALID_TYPE","INVALID_IDENTIFIER","INVALID_DATA","INVALID_ATTRIBUTE_DEFINITION","INVALID_META_DEFINITION","UNAUTHENTICATED","MISMATCHED_IDENTIFIER","DISABLED_ATTRIBUTE_DEFINITION"],"m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
|
74
74
|
fieldName,
|
|
75
75
|
value
|
|
76
76
|
},
|
|
77
|
-
type,
|
|
77
|
+
type = IngestType.IMPLICIT,
|
|
78
78
|
source
|
|
79
79
|
} = _ref2;
|
|
80
80
|
const url = `${base}/ingest`;
|
|
@@ -82,6 +82,9 @@ const ingest = async _ref2 => {
|
|
|
82
82
|
if (!hasRequiredPrivacyCookies()) {
|
|
83
83
|
throw new Error('does not satisfy cookie check');
|
|
84
84
|
}
|
|
85
|
+
if (!Array.isArray(value)) {
|
|
86
|
+
throw new Error('value is not an array');
|
|
87
|
+
}
|
|
85
88
|
let attributeInfo = attributesCache[fieldName];
|
|
86
89
|
if (!attributeInfo) {
|
|
87
90
|
attributeInfo = await getAttributes({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subs-de-inputs.esm.js","sources":["../src/interfaces/index.ts","../src/utils/hasRequiredPrivacyCookies.ts","../src/services/dataEnrichment.ts","../src/components/DESelect/index.tsx"],"sourcesContent":["export type AttributeValue = {\n name: string;\n date_created: Number;\n last_modified_date: Number;\n archived: boolean;\n order: number;\n};\n\nexport const CollectionBehaviors = {\n COLLECT: 'COLLECT',\n DO_NOT_COLLECT: 'DO_NOT_COLLECT',\n} as const;\n\nexport type Attribute = {\n name: string;\n approved_for_use?: boolean;\n collection_behavior?: (typeof CollectionBehaviors)[keyof typeof CollectionBehaviors];\n datatype: 'string';\n explicit: boolean;\n multiple_value: boolean;\n last_modified_date: Number;\n date_created: Number;\n values: Array<AttributeValue>;\n};\n\nexport const AttributesState = {\n SUCCESS: '100',\n} as const;\n\nexport const IngestType = {\n EXPLICIT: 'explicit',\n IMPLICIT: 'implicit',\n} as const;\n\nexport const IngestResponseState = {\n SUCCESS: '100',\n SYSTEM_ERROR: '101',\n INVALID_TYPE: '102',\n INVALID_IDENTIFIER: '103',\n INVALID_DATA: '104',\n INVALID_ATTRIBUTE_DEFINITION: '105',\n INVALID_META_DEFINITION: '106',\n UNAUTHENTICATED: '107',\n MISMATCHED_IDENTIFIER: '108',\n DISABLED_ATTRIBUTE_DEFINITION: '109',\n DO_NOT_COLLECT: '110',\n} as const;\n","import { WPGeo, getCookie } from '@washingtonpost/subs-sdk';\n\nexport const hasRequiredPrivacyCookies = () => {\n if (typeof window === 'undefined') {\n return false;\n }\n\n const wp_usp = getCookie('wp_usp');\n\n const countryCode = WPGeo()?.country_code;\n\n return !!(wp_usp && countryCode === 'US');\n};\n","import {\n ENDPOINTS,\n ResponseStatus,\n JSON_HEADERS,\n getCookie,\n} from '@washingtonpost/subs-sdk';\nimport {\n Attribute,\n CollectionBehaviors,\n IngestResponseState,\n IngestType,\n} from '../interfaces';\nimport { hasRequiredPrivacyCookies } from '../utils/hasRequiredPrivacyCookies';\n\nconst base = `${ENDPOINTS.base}/de/v1`;\n\nconst attributesCache: Record<string, any> = {};\nexport const getAttributes: GetAttributesType = async ({\n fieldName,\n}: {\n fieldName: string;\n}) => {\n if (attributesCache[fieldName]) {\n return attributesCache[fieldName];\n }\n\n const fieldNames = [fieldName];\n\n try {\n const url = new URL(`${base}/attributes`);\n url.searchParams.set('attributes', fieldNames.join(','));\n\n const data = await fetch(url.toString(), {\n credentials: 'include',\n headers: JSON_HEADERS,\n });\n const json = await data.json();\n\n if (data.ok && json.status === ResponseStatus.SUCCESS) {\n const attributes = json.attributes || [];\n attributesCache[fieldName] = attributes;\n return attributes;\n } else {\n return [];\n }\n } catch (e) {\n console.debug(e);\n return [];\n }\n};\n\ntype GetAttributesType = ({\n fieldName,\n}: {\n fieldName: string;\n}) => Promise<Attribute[]>;\n\nexport const ingest: IngestType = async ({\n submitData: { fieldName, value },\n type,\n source,\n}) => {\n const url = `${base}/ingest`;\n\n const wapo_login_id = getCookie('wapo_login_id');\n\n if (!hasRequiredPrivacyCookies()) {\n throw new Error('does not satisfy cookie check');\n }\n\n let attributeInfo = attributesCache[fieldName];\n if (!attributeInfo) {\n attributeInfo = await getAttributes({ fieldName });\n }\n\n if (\n attributeInfo[0] &&\n attributeInfo[0].name === fieldName &&\n attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT\n ) {\n throw new Error('do not collect');\n }\n\n const jucid = localStorage.getItem('uuid');\n const ga = getCookie('_ga');\n\n const payload = {\n jucid,\n ga,\n type,\n wapo_login_id, // TODO: move this to BE to read from cookie headers\n data: {\n fieldName,\n value,\n },\n metadata: { source },\n };\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: JSON_HEADERS,\n body: JSON.stringify(payload),\n });\n\n const json = await response.json();\n\n return json;\n } catch (e) {\n console.debug(e);\n return null;\n }\n};\n\ntype IngestType = ({\n submitData: { fieldName, value },\n source,\n}: {\n submitData: {\n fieldName: string;\n value: string[];\n };\n type: (typeof IngestType)[keyof typeof IngestType];\n source: string;\n}) => Promise<{\n status: ResponseStatus;\n state: (typeof IngestResponseState)[keyof typeof IngestResponseState];\n} | null>;\n","import React, { useState, useEffect } from 'react';\nimport { Select, styled, theme } from '@washingtonpost/wpds-ui-kit';\nimport { Attribute, AttributeValue, IngestType } from '../../interfaces';\nimport { ingest } from '../../services/dataEnrichment';\nimport { ENDPOINTS, ResponseStatus } from '@washingtonpost/subs-sdk';\nimport { useScript, ScriptStatus } from '@washingtonpost/subs-hooks';\n\ninterface DESelectProps {\n source: string;\n fieldName: string;\n label?: string;\n dataDictionaryConfig?: Attribute;\n defaultValue?: string;\n disabled?: boolean;\n submit: boolean;\n onChange?: ({ value }: { value: string }) => void;\n onFinished?: ({\n isFinished,\n isError,\n }: {\n isFinished: boolean;\n isError: boolean;\n }) => void;\n valuesFilter?: (value: AttributeValue) => boolean;\n selectProps?: {\n root?: any;\n trigger?: any;\n label?: any;\n value?: any;\n content?: any;\n item?: any;\n };\n children?: React.ReactNode;\n}\n\nconst scriptSrc = `${\n ENDPOINTS.staticAssets === 'https://subscribe.washingtonpost.com/static'\n ? 'https://www.washingtonpost.com/subscribe/static/'\n : ENDPOINTS.staticAssets\n}/de-utils/twpdeu.min.js`;\n\nexport const DESelect: React.FC<DESelectProps> = ({\n source,\n fieldName,\n label,\n dataDictionaryConfig,\n defaultValue,\n disabled,\n submit,\n onChange = () => {},\n onFinished = () => {},\n valuesFilter = () => true,\n children,\n}) => {\n const [config, setConfig] = useState(dataDictionaryConfig);\n\n const [selected, setSelected] = useState('');\n\n const scriptStatus = useScript(scriptSrc);\n\n useEffect(() => {\n const fetchConfig = async () => {\n try {\n const config = await window?.__twpdeu?.getFieldConfigs({ fieldName });\n if (config) {\n setConfig(config[0]);\n } else {\n console.error('unable to get config', fieldName);\n }\n } catch (e) {\n console.warn('unable to get config', fieldName, e);\n }\n };\n\n if (scriptStatus === ScriptStatus.READY && !(children || config)) {\n fetchConfig();\n }\n }, [scriptStatus]);\n\n useEffect(() => {\n const submitSelected = async () => {\n try {\n // TODO: Switch to window.__twpdeu.push\n // TODO: Log to GA\n const result = await ingest({\n submitData: { fieldName, value: [selected] },\n type: config?.explicit ? IngestType.EXPLICIT : IngestType.IMPLICIT,\n source,\n });\n const isError = result\n ? result.status !== ResponseStatus.SUCCESS\n : true;\n\n onFinished({\n isFinished: true,\n isError,\n });\n } catch (e) {\n onFinished({\n isFinished: false,\n isError: true,\n });\n }\n };\n\n if (submit && selected) {\n submitSelected();\n }\n }, [submit, selected]);\n\n if (!(children || config)) {\n return <span>loading</span>;\n }\n\n const defaultValueProp = defaultValue ? { defaultValue } : {};\n\n const disabledProp = disabled ? { disabled: true } : {};\n\n // sort and filter out archived values\n const values = config\n ? config.values\n .sort((a, b) => a.order - b.order)\n .filter((value) => value.archived !== true)\n .filter(valuesFilter)\n : [];\n\n return (\n <SelectWrapper>\n <Select.Root\n onValueChange={(e: string) => {\n onChange({ value: e });\n setSelected(e);\n }}\n {...defaultValueProp}\n {...disabledProp}\n >\n {children ? children : null}\n {!children && config && (\n <>\n <Select.Trigger data-test-id={`${config.name}-select-trigger`}>\n <Select.Label>{label || config.name}</Select.Label>\n <Select.Value />\n </Select.Trigger>\n <Select.Content\n css={{ zIndex: theme.zIndices.page }}\n data-test-id={`${config.name}-select-content`}\n >\n {values.map((value) => (\n <Select.Item value={value.name} key={value.name}>\n {value.name}\n </Select.Item>\n ))}\n </Select.Content>\n </>\n )}\n </Select.Root>\n </SelectWrapper>\n );\n};\n\nconst SelectWrapper = styled('div', {\n boxSizing: 'border-box',\n display: 'flex',\n marginBottom: '$100',\n flexDirection: 'column',\n '& button': {\n padding: '1px 6px',\n },\n '& *': { boxSizing: 'border-box' },\n});\n"],"names":["CollectionBehaviors","COLLECT","DO_NOT_COLLECT","AttributesState","SUCCESS","IngestType","EXPLICIT","IMPLICIT","IngestResponseState","SYSTEM_ERROR","INVALID_TYPE","INVALID_IDENTIFIER","INVALID_DATA","INVALID_ATTRIBUTE_DEFINITION","INVALID_META_DEFINITION","UNAUTHENTICATED","MISMATCHED_IDENTIFIER","DISABLED_ATTRIBUTE_DEFINITION","hasRequiredPrivacyCookies","window","wp_usp","getCookie","countryCode","_WPGeo","WPGeo","country_code","base","ENDPOINTS","attributesCache","getAttributes","_ref","fieldName","fieldNames","url","URL","searchParams","set","join","data","fetch","toString","credentials","headers","JSON_HEADERS","json","ok","status","ResponseStatus","attributes","e","console","debug","ingest","_ref2","submitData","value","type","source","wapo_login_id","Error","attributeInfo","name","collection_behavior","jucid","localStorage","getItem","ga","payload","metadata","response","method","body","JSON","stringify","scriptSrc","staticAssets","DESelect","label","dataDictionaryConfig","defaultValue","disabled","submit","onChange","onFinished","valuesFilter","children","config","setConfig","useState","selected","setSelected","scriptStatus","useScript","useEffect","fetchConfig","_window","__twpdeu","getFieldConfigs","error","warn","ScriptStatus","READY","submitSelected","result","explicit","isError","isFinished","React","defaultValueProp","disabledProp","values","sort","a","b","order","filter","archived","SelectWrapper","Select","Root","onValueChange","Trigger","Label","Value","Content","css","zIndex","theme","zIndices","page","map","Item","key","styled","boxSizing","display","marginBottom","flexDirection","padding"],"mappings":";;;;;MAQaA,mBAAmB,GAAG;EACjCC,OAAO,EAAE,SAAS;EAClBC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E3E,KAAK,IAChBoD,oBAACW,MAAM,CAACa,IAAI;IAAC5E,KAAK,EAAEA,KAAK,CAACM,IAAI;IAAEuE,GAAG,EAAE7E,KAAK,CAACM;KACxCN,KAAK,CAACM,IAAI,CAEd,CAAC,CACa,CAEpB,CACW,CACA;AAEpB,CAAC;AAED,MAAMwD,aAAa,gBAAGgB,MAAM,CAAC,KAAK,EAAE;EAClCC,SAAS,EAAE,YAAY;EACvBC,OAAO,EAAE,MAAM;EACfC,YAAY,EAAE,MAAM;EACpBC,aAAa,EAAE,QAAQ;EACvB,UAAU,EAAE;IACVC,OAAO,EAAE;GACV;EACD,KAAK,EAAE;IAAEJ,SAAS,EAAE;;CACrB,CAAC;;;;"}
|
|
1
|
+
{"version":3,"file":"subs-de-inputs.esm.js","sources":["../src/interfaces/index.ts","../src/utils/hasRequiredPrivacyCookies.ts","../src/services/dataEnrichment.ts","../src/components/DESelect/index.tsx"],"sourcesContent":["export type AttributeValue = {\n name: string;\n date_created: Number;\n last_modified_date: Number;\n archived: boolean;\n order: number;\n};\n\nexport const CollectionBehaviors = {\n COLLECT: 'COLLECT',\n DO_NOT_COLLECT: 'DO_NOT_COLLECT',\n} as const;\n\nexport type Attribute = {\n name: string;\n approved_for_use?: boolean;\n collection_behavior?: (typeof CollectionBehaviors)[keyof typeof CollectionBehaviors];\n datatype: 'string';\n explicit: boolean;\n multiple_value: boolean;\n last_modified_date: Number;\n date_created: Number;\n values: Array<AttributeValue>;\n};\n\nexport const AttributesState = {\n SUCCESS: '100',\n} as const;\n\nexport const IngestType = {\n EXPLICIT: 'explicit',\n IMPLICIT: 'implicit',\n} as const;\n\nexport const IngestResponseState = {\n SUCCESS: '100',\n SYSTEM_ERROR: '101',\n INVALID_TYPE: '102',\n INVALID_IDENTIFIER: '103',\n INVALID_DATA: '104',\n INVALID_ATTRIBUTE_DEFINITION: '105',\n INVALID_META_DEFINITION: '106',\n UNAUTHENTICATED: '107',\n MISMATCHED_IDENTIFIER: '108',\n DISABLED_ATTRIBUTE_DEFINITION: '109',\n DO_NOT_COLLECT: '110',\n} as const;\n","import { WPGeo, getCookie } from '@washingtonpost/subs-sdk';\n\nexport const hasRequiredPrivacyCookies = () => {\n if (typeof window === 'undefined') {\n return false;\n }\n\n const wp_usp = getCookie('wp_usp');\n\n const countryCode = WPGeo()?.country_code;\n\n return !!(wp_usp && countryCode === 'US');\n};\n","import {\n ENDPOINTS,\n ResponseStatus,\n JSON_HEADERS,\n getCookie,\n} from '@washingtonpost/subs-sdk';\nimport {\n Attribute,\n CollectionBehaviors,\n IngestResponseState,\n IngestType,\n} from '../interfaces';\nimport { hasRequiredPrivacyCookies } from '../utils/hasRequiredPrivacyCookies';\n\nconst base = `${ENDPOINTS.base}/de/v1`;\n\nconst attributesCache: Record<string, any> = {};\nexport const getAttributes: GetAttributesType = async ({\n fieldName,\n}: {\n fieldName: string;\n}) => {\n if (attributesCache[fieldName]) {\n return attributesCache[fieldName];\n }\n\n const fieldNames = [fieldName];\n\n try {\n const url = new URL(`${base}/attributes`);\n url.searchParams.set('attributes', fieldNames.join(','));\n\n const data = await fetch(url.toString(), {\n credentials: 'include',\n headers: JSON_HEADERS,\n });\n const json = await data.json();\n\n if (data.ok && json.status === ResponseStatus.SUCCESS) {\n const attributes = json.attributes || [];\n attributesCache[fieldName] = attributes;\n return attributes;\n } else {\n return [];\n }\n } catch (e) {\n console.debug(e);\n return [];\n }\n};\n\ntype GetAttributesType = ({\n fieldName,\n}: {\n fieldName: string;\n}) => Promise<Attribute[]>;\n\nexport const ingest: IngestType = async ({\n submitData: { fieldName, value },\n type = IngestType.IMPLICIT,\n source,\n}) => {\n const url = `${base}/ingest`;\n\n const wapo_login_id = getCookie('wapo_login_id');\n\n if (!hasRequiredPrivacyCookies()) {\n throw new Error('does not satisfy cookie check');\n }\n\n if (!Array.isArray(value)) {\n throw new Error('value is not an array');\n }\n\n let attributeInfo = attributesCache[fieldName];\n if (!attributeInfo) {\n attributeInfo = await getAttributes({ fieldName });\n }\n\n if (\n attributeInfo[0] &&\n attributeInfo[0].name === fieldName &&\n attributeInfo[0].collection_behavior === CollectionBehaviors.DO_NOT_COLLECT\n ) {\n throw new Error('do not collect');\n }\n\n const jucid = localStorage.getItem('uuid');\n const ga = getCookie('_ga');\n\n const payload = {\n jucid,\n ga,\n type,\n wapo_login_id, // TODO: move this to BE to read from cookie headers\n data: {\n fieldName,\n value,\n },\n metadata: { source },\n };\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: JSON_HEADERS,\n body: JSON.stringify(payload),\n });\n\n const json = await response.json();\n\n return json;\n } catch (e) {\n console.debug(e);\n return null;\n }\n};\n\ntype IngestType = ({\n submitData: { fieldName, value },\n source,\n}: {\n submitData: {\n fieldName: string;\n value: string[];\n };\n type?: (typeof IngestType)[keyof typeof IngestType];\n source: string;\n}) => Promise<{\n status: ResponseStatus;\n state: (typeof IngestResponseState)[keyof typeof IngestResponseState];\n} | null>;\n","import React, { useState, useEffect } from 'react';\nimport { Select, styled, theme } from '@washingtonpost/wpds-ui-kit';\nimport { Attribute, AttributeValue, IngestType } from '../../interfaces';\nimport { ingest } from '../../services/dataEnrichment';\nimport { ENDPOINTS, ResponseStatus } from '@washingtonpost/subs-sdk';\nimport { useScript, ScriptStatus } from '@washingtonpost/subs-hooks';\n\ninterface DESelectProps {\n source: string;\n fieldName: string;\n label?: string;\n dataDictionaryConfig?: Attribute;\n defaultValue?: string;\n disabled?: boolean;\n submit: boolean;\n onChange?: ({ value }: { value: string }) => void;\n onFinished?: ({\n isFinished,\n isError,\n }: {\n isFinished: boolean;\n isError: boolean;\n }) => void;\n valuesFilter?: (value: AttributeValue) => boolean;\n selectProps?: {\n root?: any;\n trigger?: any;\n label?: any;\n value?: any;\n content?: any;\n item?: any;\n };\n children?: React.ReactNode;\n}\n\nconst scriptSrc = `${\n ENDPOINTS.staticAssets === 'https://subscribe.washingtonpost.com/static'\n ? 'https://www.washingtonpost.com/subscribe/static/'\n : ENDPOINTS.staticAssets\n}/de-utils/twpdeu.min.js`;\n\nexport const DESelect: React.FC<DESelectProps> = ({\n source,\n fieldName,\n label,\n dataDictionaryConfig,\n defaultValue,\n disabled,\n submit,\n onChange = () => {},\n onFinished = () => {},\n valuesFilter = () => true,\n children,\n}) => {\n const [config, setConfig] = useState(dataDictionaryConfig);\n\n const [selected, setSelected] = useState('');\n\n const scriptStatus = useScript(scriptSrc);\n\n useEffect(() => {\n const fetchConfig = async () => {\n try {\n const config = await window?.__twpdeu?.getFieldConfigs({ fieldName });\n if (config) {\n setConfig(config[0]);\n } else {\n console.error('unable to get config', fieldName);\n }\n } catch (e) {\n console.warn('unable to get config', fieldName, e);\n }\n };\n\n if (scriptStatus === ScriptStatus.READY && !(children || config)) {\n fetchConfig();\n }\n }, [scriptStatus]);\n\n useEffect(() => {\n const submitSelected = async () => {\n try {\n // TODO: Switch to window.__twpdeu.push\n // TODO: Log to GA\n const result = await ingest({\n submitData: { fieldName, value: [selected] },\n type: config?.explicit ? IngestType.EXPLICIT : IngestType.IMPLICIT,\n source,\n });\n const isError = result\n ? result.status !== ResponseStatus.SUCCESS\n : true;\n\n onFinished({\n isFinished: true,\n isError,\n });\n } catch (e) {\n onFinished({\n isFinished: false,\n isError: true,\n });\n }\n };\n\n if (submit && selected) {\n submitSelected();\n }\n }, [submit, selected]);\n\n if (!(children || config)) {\n return <span>loading</span>;\n }\n\n const defaultValueProp = defaultValue ? { defaultValue } : {};\n\n const disabledProp = disabled ? { disabled: true } : {};\n\n // sort and filter out archived values\n const values = config\n ? config.values\n .sort((a, b) => a.order - b.order)\n .filter((value) => value.archived !== true)\n .filter(valuesFilter)\n : [];\n\n return (\n <SelectWrapper>\n <Select.Root\n onValueChange={(e: string) => {\n onChange({ value: e });\n setSelected(e);\n }}\n {...defaultValueProp}\n {...disabledProp}\n >\n {children ? children : null}\n {!children && config && (\n <>\n <Select.Trigger data-test-id={`${config.name}-select-trigger`}>\n <Select.Label>{label || config.name}</Select.Label>\n <Select.Value />\n </Select.Trigger>\n <Select.Content\n css={{ zIndex: theme.zIndices.page }}\n data-test-id={`${config.name}-select-content`}\n >\n {values.map((value) => (\n <Select.Item value={value.name} key={value.name}>\n {value.name}\n </Select.Item>\n ))}\n </Select.Content>\n </>\n )}\n </Select.Root>\n </SelectWrapper>\n );\n};\n\nconst SelectWrapper = styled('div', {\n boxSizing: 'border-box',\n display: 'flex',\n marginBottom: '$100',\n flexDirection: 'column',\n '& button': {\n padding: '1px 6px',\n },\n '& *': { boxSizing: 'border-box' },\n});\n"],"names":["CollectionBehaviors","COLLECT","DO_NOT_COLLECT","AttributesState","SUCCESS","IngestType","EXPLICIT","IMPLICIT","IngestResponseState","SYSTEM_ERROR","INVALID_TYPE","INVALID_IDENTIFIER","INVALID_DATA","INVALID_ATTRIBUTE_DEFINITION","INVALID_META_DEFINITION","UNAUTHENTICATED","MISMATCHED_IDENTIFIER","DISABLED_ATTRIBUTE_DEFINITION","hasRequiredPrivacyCookies","window","wp_usp","getCookie","countryCode","_WPGeo","WPGeo","country_code","base","ENDPOINTS","attributesCache","getAttributes","_ref","fieldName","fieldNames","url","URL","searchParams","set","join","data","fetch","toString","credentials","headers","JSON_HEADERS","json","ok","status","ResponseStatus","attributes","e","console","debug","ingest","_ref2","submitData","value","type","source","wapo_login_id","Error","Array","isArray","attributeInfo","name","collection_behavior","jucid","localStorage","getItem","ga","payload","metadata","response","method","body","JSON","stringify","scriptSrc","staticAssets","DESelect","label","dataDictionaryConfig","defaultValue","disabled","submit","onChange","onFinished","valuesFilter","children","config","setConfig","useState","selected","setSelected","scriptStatus","useScript","useEffect","fetchConfig","_window","__twpdeu","getFieldConfigs","error","warn","ScriptStatus","READY","submitSelected","result","explicit","isError","isFinished","React","defaultValueProp","disabledProp","values","sort","a","b","order","filter","archived","SelectWrapper","Select","Root","onValueChange","Trigger","Label","Value","Content","css","zIndex","theme","zIndices","page","map","Item","key","styled","boxSizing","display","marginBottom","flexDirection","padding"],"mappings":";;;;;MAQaA,mBAAmB,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