@playpilot/tpi 8.10.4-beta.1 → 8.10.4-beta.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@playpilot/tpi",
3
- "version": "8.10.4-beta.1",
3
+ "version": "8.10.4-beta.2",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "dev": "vite dev",
@@ -6,6 +6,7 @@ import type { LinkInjectionResponse, LinkInjection } from '../types/injection'
6
6
  import { getFullUrlPath } from '../url'
7
7
  import { api } from './api'
8
8
  import { getApiToken } from '$lib/token'
9
+ import { getPageTextAndElements } from '$lib/injectionElements'
9
10
 
10
11
  let pollTimeout: ReturnType<typeof setTimeout> | null = null
11
12
 
@@ -13,13 +14,14 @@ let pollTimeout: ReturnType<typeof setTimeout> | null = null
13
14
  * Fetch link injections for a URL. This will be either a POST or a GET request depending on whether on not the AI should run.
14
15
  */
15
16
  export async function fetchLinkInjections(
16
- pageText: string | null,
17
- { url = getFullUrlPath(), hash = stringToHash(pageText || ''), params = {}, method = 'GET' }:
18
- { url?: string, hash?: string, params?: Record<string, any>, method?: 'GET' | 'POST' } = {},
17
+ { url = getFullUrlPath(), params = {}, method = 'GET' }:
18
+ { url?: string, params?: Record<string, any>, method?: 'GET' | 'POST' } = {},
19
19
  ): Promise<LinkInjectionResponse> {
20
20
  const apiToken = getApiToken()
21
21
  const isEditorialMode = isEditorialModeEnabled() ? await authorize() : false
22
22
  const language = getLanguage()
23
+ const { pageText } = getPageTextAndElements()
24
+ const hash = stringToHash(pageText || '')
23
25
 
24
26
  if (!apiToken) throw new Error('No token was provided')
25
27
 
@@ -62,10 +64,11 @@ export async function fetchLinkInjections(
62
64
  * The results return `injections_ready=false` while the injections are not yet ready.
63
65
  */
64
66
  export async function pollLinkInjections(
65
- pageText: string,
66
67
  { requireCompletedResult = false, runAiWhenRelevant = false, pollInterval = 3000, maxTries = 600, onpoll = () => null }:
67
68
  { requireCompletedResult?: boolean, runAiWhenRelevant?: boolean, pollInterval?: number, maxTries?: number, onpoll?: (_response: LinkInjectionResponse) => void } = {},
68
69
  ): Promise<LinkInjectionResponse> {
70
+ const { pageText } = getPageTextAndElements()
71
+
69
72
  let currentTry = 0
70
73
 
71
74
  // Clear pollTimeout if it is already running to prevent multiple timeouts from running at the same time
@@ -81,14 +84,14 @@ export async function pollLinkInjections(
81
84
  // if it does. We're still interested in handling the response from here and don't want it to short circuit
82
85
  // just because the fetch failed.
83
86
  try {
84
- response = await fetchLinkInjections(pageText)
87
+ response = await fetchLinkInjections()
85
88
  } catch(error: any) {
86
89
  if (error?.status === 404) {
87
90
  // If the GET endpoint returns a 404 no article has been generated yet and we can safely generate
88
91
  // a new article. We can safely throw here (meaning we poll again) as nothing will be returned.
89
92
  // The first POST indexes the article, the second runs the AI if needed.
90
- response = await fetchLinkInjections(pageText, { method: 'POST' })
91
- if (response.ai_enabled) response = await fetchLinkInjections(pageText, { params: { run_ai: true }, method: 'POST' })
93
+ response = await fetchLinkInjections({ method: 'POST' })
94
+ if (response.ai_enabled) response = await fetchLinkInjections({ params: { run_ai: true }, method: 'POST' })
92
95
  }
93
96
 
94
97
  throw new Error
@@ -137,10 +140,10 @@ export async function runAiBasedOnResponse(pageText: string, response: LinkInjec
137
140
  if (response.ai_last_run && isCurrentTimeEqualToResponseTime) return response
138
141
  if (new Date(currentModifiedTime || 0) <= new Date(responseModifiedTime || 0)) return response
139
142
 
140
- return await fetchLinkInjections(pageText, { params: { run_ai: true }, method: 'POST' })
143
+ return await fetchLinkInjections({ params: { run_ai: true }, method: 'POST' })
141
144
  }
142
145
 
143
- export async function saveLinkInjections(linkInjections: LinkInjection[], pageText: string): Promise<LinkInjection[]> {
146
+ export async function saveLinkInjections(linkInjections: LinkInjection[]): Promise<LinkInjection[]> {
144
147
  const selector = window.PlayPilotLinkInjections?.selector
145
148
 
146
149
  // Only save manual injections, AI injections should be left intact and can't be saved over
@@ -160,7 +163,7 @@ export async function saveLinkInjections(linkInjections: LinkInjection[], pageTe
160
163
  removed: !!linkInjection.removed,
161
164
  }))
162
165
 
163
- const response = await fetchLinkInjections(pageText, {
166
+ const response = await fetchLinkInjections({
164
167
  method: 'POST',
165
168
  params: {
166
169
  private_token: getAuthToken(),
@@ -11,10 +11,9 @@ export const sessionPeriodMilliseconds = sessionPollPeriodMilliseconds * 2
11
11
  * where we save the session.
12
12
  * Along with that, we also return ai_enabled and injections_enabled as they are used to update the state of
13
13
  * the current editing session.
14
- * @param pageText Despite not being used, the request still requires a valid pageText string
15
14
  */
16
- export async function fetchAsSession(pageText: string): Promise<SessionResponse> {
17
- const { ai_enabled, injections_enabled, ai_last_run, session_id, session_last_ping } = await fetchLinkInjections(pageText)
15
+ export async function fetchAsSession(): Promise<SessionResponse> {
16
+ const { ai_enabled, injections_enabled, ai_last_run, session_id, session_last_ping } = await fetchLinkInjections()
18
17
 
19
18
  const isCurrentlyAllowToEdit = isAllowedToEdit(session_id || null, session_last_ping || null)
20
19
 
@@ -28,15 +27,14 @@ export async function fetchAsSession(pageText: string): Promise<SessionResponse>
28
27
 
29
28
  if (!isCurrentlyAllowToEdit) return response
30
29
 
31
- return await saveCurrentSession(pageText)
30
+ return await saveCurrentSession()
32
31
  }
33
32
 
34
33
  /**
35
34
  * Save the current users session id as the currently active session. This is always completed regardless of if the user
36
35
  * is the current owner of the session, so check that first if necessary!
37
- * @param pageText Despite not being used, the request still requires a valid pageText string
38
36
  */
39
- export async function saveCurrentSession(pageText: string): Promise<SessionResponse> {
37
+ export async function saveCurrentSession(): Promise<SessionResponse> {
40
38
  const sessionId = getSessionId()
41
39
  const now = new Date(Date.now()).toISOString()
42
40
 
@@ -45,7 +43,7 @@ export async function saveCurrentSession(pageText: string): Promise<SessionRespo
45
43
  session_last_ping: now.toString(),
46
44
  }
47
45
 
48
- const { ai_enabled, injections_enabled, ai_last_run } = await fetchLinkInjections(pageText, { params })
46
+ const { ai_enabled, injections_enabled, ai_last_run } = await fetchLinkInjections({ params })
49
47
 
50
48
  return {
51
49
  ai_enabled,
@@ -91,9 +91,9 @@ export function getPageText(elements: HTMLElement[]): string {
91
91
  return elements.map(element => element.innerText).join('\n\n')
92
92
  }
93
93
 
94
- export function getPageTextAndElements(config: ConfigResponse | null): { parentElement: HTMLElement, elements: HTMLElement[], pageText: string } {
94
+ export function getPageTextAndElements(config: ConfigResponse = window.PlayPilotLinkInjections?.config): { parentElement: HTMLElement, elements: HTMLElement[], pageText: string } {
95
95
  const parentElement = getLinkInjectionsParentElement()
96
- const elements = getLinkInjectionElements(parentElement, config?.exclude_elements_selector || '')
96
+ const elements = getLinkInjectionElements(parentElement, config.exclude_elements_selector || '')
97
97
  const pageText = getPageText(elements)
98
98
 
99
99
  return { parentElement, elements, pageText }
package/src/main.ts CHANGED
@@ -3,7 +3,6 @@ import { fetchConfig } from '$lib/api/config'
3
3
  import { pollLinkInjections } from '$lib/api/externalPages'
4
4
  import { setConsent } from '$lib/consent'
5
5
  import { isCrawler } from '$lib/crawler'
6
- import { getPageTextAndElements } from '$lib/injectionElements'
7
6
  import { isUrlExcludedViaConfig } from '$lib/url'
8
7
 
9
8
  window.PlayPilotLinkInjections ||= {
@@ -70,9 +69,7 @@ window.PlayPilotLinkInjections ||= {
70
69
 
71
70
  if (isUrlExcludedViaConfig(this.config)) return
72
71
 
73
- const { pageText } = getPageTextAndElements(this.config)
74
-
75
- this.initial_link_injections_promise = pollLinkInjections(pageText, { maxTries: 1, runAiWhenRelevant: !isCrawler() })
72
+ this.initial_link_injections_promise = pollLinkInjections({ maxTries: 1, runAiWhenRelevant: !isCrawler() })
76
73
 
77
74
  this.mount()
78
75
  },
@@ -2,7 +2,6 @@
2
2
  import { onDestroy } from 'svelte'
3
3
  import { pollLinkInjections } from '$lib/api/externalPages'
4
4
  import { clearLinkInjections, injectLinksInDocument, separateLinkInjectionTypes } from '$lib/injection'
5
- import { getPageText, getPageTextAndElements } from '$lib/injectionElements'
6
5
  import { fireQueuedTrackingEvents, setTrackingSids, track } from '$lib/tracking'
7
6
  import { isUrlExcludedViaConfig } from '$lib/url'
8
7
  import { isCrawler } from '$lib/crawler'
@@ -11,6 +10,7 @@
11
10
  import { fetchConfig } from '$lib/api/config'
12
11
  import { insertExplore, insertExploreIntoNavigation } from '$lib/explore'
13
12
  import { authorize, getAuthToken, isEditorialModeEnabled, removeAuthCookie, setEditorialParamInUrl } from '$lib/api/auth'
13
+ import { getPageTextAndElements } from '$lib/injectionElements'
14
14
  import type { LinkInjectionResponse, LinkInjection, LinkInjectionTypes } from '$lib/types/injection'
15
15
  import Editor from './components/Editorial/Editor.svelte'
16
16
  import EditorTrigger from './components/Editorial/EditorTrigger.svelte'
@@ -22,8 +22,6 @@
22
22
  import PostersScrollReveal from './components/PostersScrollReveal.svelte'
23
23
  import TrackingPixelsForTitleDataPerLink from './components/TrackingPixelsForTitleDataPerLink.svelte'
24
24
 
25
- let elements: HTMLElement[] = $state([])
26
-
27
25
  let response: LinkInjectionResponse | null = $state(null)
28
26
  let isEditorialMode = $state(isEditorialModeEnabled())
29
27
  let hasAuthToken = $state(!!getAuthToken())
@@ -35,10 +33,6 @@
35
33
  // @ts-ignore It's ok if the response is empty
36
34
  const { ai_injections: aiInjections = [], manual_injections: manualInjections = [] } = $derived(response || {})
37
35
 
38
- const pageText = $derived(getPageText(elements))
39
-
40
- $inspect({ thing: 'pageText in page.svelte', pageText })
41
-
42
36
  const initializePromise = initialize()
43
37
 
44
38
  $effect(() => {
@@ -88,8 +82,6 @@
88
82
  if (isUrlExcluded) return
89
83
 
90
84
  if (config?.html_selector) window.PlayPilotLinkInjections.selector = config?.html_selector
91
-
92
- elements = getPageTextAndElements(window.PlayPilotLinkInjections.config).elements
93
85
  } catch(error) {
94
86
  // We return if the config did not get fetched properly, as we can't determine what should and should
95
87
  // get injected without it.
@@ -100,7 +92,7 @@
100
92
 
101
93
  try {
102
94
  response = await window.PlayPilotLinkInjections.initial_link_injections_promise || null
103
- response ||= await pollLinkInjections(pageText, { maxTries: 1, runAiWhenRelevant: !isCrawler() })
95
+ response ||= await pollLinkInjections({ maxTries: 1, runAiWhenRelevant: !isCrawler() })
104
96
 
105
97
  loading = false
106
98
 
@@ -116,7 +108,7 @@
116
108
 
117
109
  if (!isEditorialMode || isCrawler()) return
118
110
 
119
- response = await pollLinkInjections(pageText, { requireCompletedResult: true, onpoll: (update) => response = update })
111
+ response = await pollLinkInjections({ requireCompletedResult: true, onpoll: (update) => response = update })
120
112
  inject({ aiInjections, manualInjections })
121
113
  } catch(error: unknown) {
122
114
  console.error(error)
@@ -138,6 +130,7 @@
138
130
  }
139
131
 
140
132
  function inject(injections: LinkInjectionTypes = { aiInjections, manualInjections }): void {
133
+ const { elements } = getPageTextAndElements()
141
134
  const filteredInjections = injectLinksInDocument(elements, injections)
142
135
 
143
136
  if (JSON.stringify(filteredInjections) !== JSON.stringify(linkInjections)) {
@@ -208,7 +201,6 @@
208
201
  <svelte:boundary onerror={(error) => track(TrackingEvent.EditorError, null, { message: (error as Error).message })}>
209
202
  <Editor
210
203
  bind:linkInjections
211
- {pageText}
212
204
  {loading}
213
205
  onreinitialize={reinitializeEditor}
214
206
  injectionsEnabled={response?.injections_enabled}
@@ -33,7 +33,6 @@
33
33
 
34
34
  let {
35
35
  linkInjections = $bindable(),
36
- pageText = '',
37
36
  loading = false,
38
37
  injectionsEnabled = false,
39
38
  aiStatus = {},
@@ -46,6 +45,8 @@
46
45
  const position: Position = JSON.parse(localStorage.getItem(editorPositionKey) || '{ "x": 0, "y": 0 }')
47
46
  const height: number = parseInt(localStorage.getItem(editorHeightKey) || '0')
48
47
 
48
+
49
+
49
50
  let editorElement: HTMLElement | null = $state(null)
50
51
  let manualInjectionActive = $state(false)
51
52
  let saving = $state(false)
@@ -85,7 +86,7 @@
85
86
  saving = true
86
87
  hasError = false
87
88
 
88
- linkInjections = await saveLinkInjections(linkInjections, pageText)
89
+ linkInjections = await saveLinkInjections(linkInjections)
89
90
  initialStateString = linkInjectionsString
90
91
  } catch {
91
92
  hasError = true
@@ -177,7 +178,6 @@
177
178
 
178
179
  {#if !loading}
179
180
  <Session
180
- {pageText}
181
181
  onallow={() => allowEditing = true}
182
182
  ondisallow={() => allowEditing = false}
183
183
  ontakeover={onreinitialize}
@@ -231,7 +231,6 @@
231
231
  style:top="{scrollDistance}px"
232
232
  transition:fly={{ x: Math.min(window.innerWidth, 320), duration: 200, opacity: 1 }}>
233
233
  <ManualInjection
234
- {pageText}
235
234
  onclose={() => manualInjectionActive = false}
236
235
  onsave={(linkInjection) => linkInjections.push(linkInjection)} />
237
236
  </div>
@@ -4,7 +4,7 @@
4
4
  import { onMount } from 'svelte'
5
5
  import { playPilotBaseUrl } from '$lib/constants'
6
6
  import { generateInjectionKey } from '$lib/api/externalPages'
7
- import { getLinkInjectionsParentElement } from '$lib/injectionElements'
7
+ import { getLinkInjectionsParentElement, getPageTextAndElements } from '$lib/injectionElements'
8
8
  import { heading } from '$lib/actions/heading'
9
9
  import { findSurroundingPhrases, cleanPhrase } from '$lib/text'
10
10
  import { getIndexOfSelection } from '$lib/selection'
@@ -15,12 +15,13 @@
15
15
  import TitleSearch from './Search/TitleSearch.svelte'
16
16
 
17
17
  interface Props {
18
- pageText: string
19
18
  onsave: (linkInjection: LinkInjection) => void
20
19
  onclose?: () => void
21
20
  }
22
21
 
23
- const { pageText = '', onsave, onclose = () => null }: Props = $props()
22
+ const { onsave, onclose = () => null }: Props = $props()
23
+
24
+ const { pageText } = getPageTextAndElements()
24
25
 
25
26
  let currentSelection = $state('')
26
27
  let selectionSentence = $state('')
@@ -4,7 +4,6 @@
4
4
  import Alert from './Alert.svelte'
5
5
 
6
6
  interface Props {
7
- pageText?: string,
8
7
  onpoll?: ({ injectionsEnabled, aiEnabled }: { injectionsEnabled: boolean, aiEnabled: boolean }) => void,
9
8
  onallow?: () => void,
10
9
  ondisallow?: () => void,
@@ -12,7 +11,6 @@
12
11
  }
13
12
 
14
13
  const {
15
- pageText = '',
16
14
  onpoll = () => null,
17
15
  onallow = () => null,
18
16
  ondisallow = () => null,
@@ -36,7 +34,7 @@
36
34
  }
37
35
 
38
36
  async function setSession(): Promise<void> {
39
- const result = await fetchAsSession(pageText)
37
+ const result = await fetchAsSession()
40
38
 
41
39
  if (!result) return
42
40
 
@@ -49,7 +47,7 @@
49
47
  }
50
48
 
51
49
  function takeOverEditing(): void {
52
- saveCurrentSession(pageText)
50
+ saveCurrentSession()
53
51
  ontakeover()
54
52
  }
55
53
  </script>
@@ -21,6 +21,7 @@
21
21
 
22
22
  let { navigate = () => null, searchQuery = $bindable(''), filter = $bindable({}), children }: Props = $props()
23
23
 
24
+ // svelte-ignore non_reactive_update
24
25
  let element: HTMLElement | null = null
25
26
  let height: string | null = $state(null)
26
27
  let clientWidth: number = $state(window.innerWidth)