diff --git a/.changeset/explicit-devmode-and-legacy-removal.md b/.changeset/explicit-devmode-and-legacy-removal.md new file mode 100644 index 0000000..e4d45ae --- /dev/null +++ b/.changeset/explicit-devmode-and-legacy-removal.md @@ -0,0 +1,16 @@ +--- +"@oneschema/importer": major +"@oneschema/react": major +"@oneschema/vue": major +"@oneschema/angular": major +--- + +Remove the deprecated launch surface and make `devMode` explicit + +`devMode` now defaults to `false` for every host. It used to default to `process.env.NODE_ENV !== "production"`, which reads a Node global that a browser bundle either inlines or leaves undefined, so whether the iframe stayed visible after a failed launch depended on the bundler rather than on the application. Wire it to your own build condition — `devMode={import.meta.env.DEV}` or whatever your bundler exposes — to keep the old behavior. + +`parentId` is gone; pass the container element as `parent`. An id was resolved once, at construction, so it silently fell back to `document.body` whenever the container had not mounted yet. + +The `launched` event's payload is now `OneSchemaLaunchEvent`, a union of `OneSchemaLaunchSucceeded` and `OneSchemaLaunchFailed` discriminated on `success`, replacing `OneSchemaLaunchStatus`. Narrow on `success` before reading a branch's fields; the failure branch carries the same detail as the `OneSchemaLaunchFailure` that `launch()` rejects with. The internals `_hasAttemptedLaunch`, `_launch`, `_initWithRetry` and `_resetSession` are gone — `importer.status` and the promise `launch()` returns cover what they were reached for. + +[MIGRATING-0.8.md](https://github.com/oneschema/sdk/blob/main/MIGRATING-0.8.md) walks through the whole 0.7.7 → 0.8 hop, with a codemod for the mechanical parts. diff --git a/MIGRATING-0.8.md b/MIGRATING-0.8.md new file mode 100644 index 0000000..b960dad --- /dev/null +++ b/MIGRATING-0.8.md @@ -0,0 +1,244 @@ +# Migrating to 0.8 + +`0.8` is one hop from `0.7.7`. It carries every breaking change we intend to make in this cycle, so a host migrates once: nothing removed here is kept as a shim, and nothing is deprecated first and removed later. + +The theme is that the SDK now tells you what actually happened. `launch()` resolves when the import session is running and rejects, with a typed error, as soon as a failure is knowable; the `success` payload says how the data was delivered; your `success` and `cancel` handlers are awaited before the importer cleans up; and the wrappers can own the importer's visibility so your application does not have to. + +`@oneschema/filefeeds` and `@oneschema/filefeeds-react` are legacy, frozen at `0.5.3`, and unaffected by any of this. + +Run the codemod first — it does the mechanical renames — then work through the sections below for the call sites TypeScript flags. See [Codemod](#codemod) at the end. + +## At a glance + +| `0.7.7` | `0.8` | +| ------------------------------------------------- | -------------------------------------------------------------------------------- | +| `const { success } = importer.launch()` | `await importer.launch()`, rejecting with `OneSchemaLaunchFailure` | +| `onSuccess: (data) => …`, `data` untyped | `onSuccess: (result) => …`, narrow on `result.type` before reading `result.data` | +| an `async` handler ran unawaited | `success` and `cancel` are awaited, bounded by `handlerTimeoutMs` | +| a blocked iframe reported a `fatal` `error` event | `launch()` rejects with `OneSchemaLaunchError.Timeout` after `initTimeoutMs` | +| `parentId: "container"` | `parent: document.getElementById("container") ?? undefined` | +| `document.getElementById("_oneschema-iframe")` | `importer.iframe` | +| `importer._hasAttemptedLaunch` | `importer.status` | +| `devMode` defaulted from `process.env.NODE_ENV` | `devMode` defaults to `false`; pass it explicitly | +| React `isOpen` required | `isOpen` optional; omit it and launch through the component's `ref` | + +## Core importer + +### `launch()` and `launchSession()` return a promise + +They used to return `{ success }` synchronously, where `success: true` meant "the init message was queued" — a rejected JWT or a blocked iframe still looked like a successful launch until an event arrived later. They now return a promise that resolves with `OneSchemaLaunchInfo` (`embedInitId`, plus `sessionToken` and `embedId` once the embed reports them) when the session is actually running. + +```javascript +// 0.7.7 +const { success } = importer.launch() +if (!success) { + showError() +} + +// 0.8 +try { + const { sessionToken } = await importer.launch() +} catch (failure) { + showError(failure.message) +} +``` + +Failures reject with `OneSchemaLaunchFailure`, an `Error` subclass carrying `error` (a `OneSchemaLaunchError`), `embedInitId`, and `status`/`data`/`cause` when the failure came from an API call or an embed payload: + +```javascript +import { OneSchemaLaunchError } from "@oneschema/importer" + +try { + await importer.launch() +} catch (failure) { + if (failure.error === OneSchemaLaunchError.Timeout) { + // the iframe was blocked, or the embed never acknowledged the launch + } +} +``` + +Every failure the embed or the launch deadline produces still fires the `launched` event, so an event-driven host keeps working — but the promise rejects either way, and an unhandled rejection is reported by the browser. Attach a handler even when the event is what you act on: + +```javascript +importer.launch().catch(() => { + // the launched event already reported this +}) +``` + +The one exception is a launch the host abandons itself, through `close()`, `destroy()` or a newer `launch()`: it rejects with `OneSchemaLaunchError.Cancelled` and fires no `launched` event, since the host already knows it ended the attempt. + +`initTimeoutMs` (default `20000`) bounds the whole launch. A launch that is still pending at the deadline rejects with `OneSchemaLaunchError.Timeout` — previously a blocked iframe surfaced as a `fatal` `error` event after the retry schedule ran out. The deadline cannot be turned off: `0`, a negative number and a non-finite number all fall back to the default, because a launch that never settles cannot be reported. + +### The `success` payload is discriminated + +`OneSchemaImportResult` was `Record` and the payload's shape depended on the import strategy. It is now a union tagged with how the data was delivered: + +```typescript +importer.on("success", (result) => { + switch (result.type) { + case "local": + case "file-upload": + return saveRows(result.data) + case "webhook": + return console.log(result.eventId, result.responses) + } +}) +``` + +Read `result.data` instead of the untagged payload, and branch on `result.type` rather than checking which keys are present. The tag comes from the configured `importConfig.type`, so a `local` import that reports no rows still arrives as `local`. `launchSession()` has no import config, so a server-created session falls back to the payload's shape and reports a file-upload delivery as `local`. + +### `success` and `cancel` handlers are awaited + +A handler returning a promise now holds the resume token and `autoClose` until it settles, bounded by `handlerTimeoutMs` (default `30000`; raise it for handlers that ship rows to a slow or distant backend, and `0` waits forever). Two things are observable in an existing integration: + +- `autoClose` runs after the handler instead of before it, so a slow handler delays closing the importer. +- An exception a handler used to throw into the host's own error boundary is delivered to the `error` event instead, with the thrown value on `error.cause`. + +```javascript +importer.on("success", async (result) => { + if (result.type === "webhook") { + return + } + + await fetch("/import", { method: "POST", body: JSON.stringify(result.data) }) + // the importer closes after this resolves +}) +``` + +A handler that has not settled by `handlerTimeoutMs` gets an `error` event and the session is cleaned up without it. + +### `parentId` is gone + +Pass the element itself. `parentId` was resolved once, at construction, so it silently fell back to `document.body` whenever the container was not in the DOM yet — the single most common cause of "the importer rendered in the wrong place". + +```javascript +// 0.7.7 +oneschemaImporter({ clientId, parentId: "oneschema-container" }) + +// 0.8 +oneschemaImporter({ + clientId, + parent: document.getElementById("oneschema-container") ?? undefined, +}) +``` + +### Each instance owns its iframe + +Instances no longer share a single `_oneschema-iframe` element. Anything that looked that element up by id should hold `importer.iframe` instead, and `destroy()` removes the iframe the instance created along with its window message listener. + +### `status` replaces the underscore-prefixed internals + +`_hasAttemptedLaunch`, `_launch`, `_initWithRetry` and `_resetSession` are no longer part of the published surface. `importer.status` — `"idle"`, `"launching"`, `"launched"` or `"destroyed"` — is the supported way to ask where an instance is in its lifecycle. + +### `devMode` defaults to `false` + +It used to default to `!!(process.env.NODE_ENV !== "production")`, evaluated in your bundle at import time, which both guessed at your intent and threw `ReferenceError: process is not defined` when the ESM build was loaded without a `process` shim (CDN, import maps, Deno, workers). Pass it explicitly, wired to your own build condition, if you want the iframe shown when a launch fails: + +```javascript +oneschemaImporter({ clientId, devMode: import.meta.env.DEV }) +``` + +### The embed must be on the matching version + +The SDK stamps each launch attempt with an `embedInitId` and requires the embed to echo it, so a reply from an abandoned attempt cannot settle the attempt in flight, and it only accepts messages from the `baseUrl` origin. Both sides ship together: point `baseUrl` at a OneSchema deployment that carries the `0.8` protocol — the default production `baseUrl` does. A self-hosted or pinned embed that does not echo the field cannot be correlated, and every launch against it will time out. + +[LAUNCH-SEQUENCE.md](packages/importer/LAUNCH-SEQUENCE.md) diagrams the whole handshake, including the deadline and how overlapping launches are told apart. + +## `@oneschema/react` + +`isOpen` is now optional. Omit it and the component is uncontrolled: launch it through the component's `ref`, and the importer closes itself when the import completes, the user cancels, or a fatal error occurs. + +```jsx +const importer = useRef(null) + +const launch = async () => { + try { + await importer.current.launch() + } catch (failure) { + console.error(failure) + } +} + +return ( + <> + + + +) +``` + +The ref exposes `launch(launchParams?)`, which returns the importer's promise, `close(clean?)`, and a `status` getter. + +Supplying `isOpen` keeps the controlled behavior unchanged, including `onRequestClose`, which is only called in that mode. The mode is fixed when the component mounts: switch a component between controlled and uncontrolled by remounting it, not by dropping the prop. + +`onSuccess` and `onCancel` may return promises, which the importer awaits before it closes the session. Their listeners are registered once per importer and read through a ref, so an inline handler no longer causes listeners to be torn off and re-registered mid-emit — the reason an `onSuccess` defined in the render body could miss a `success` that landed on the same commit. Nothing changes in your code for this; if you added a `useCallback` purely to stabilize a handler's identity, it is no longer needed. + +The duplicate-launch warning keys off the importer's `status` rather than the serialized launch params, so it no longer fires for a re-render that changed nothing. + +## `@oneschema/vue` + +Vue was already uncontrolled — the plugin hands you the core importer — so the change is `launch()`'s promise. Register handlers once in `setup` rather than inside the launch function, and handle the rejection: + +```vue + +``` + +The plugin destroys its importer when the app unmounts, releasing the window message listener and, under `manageDOM`, the iframe. `useOneSchemaImporter()` throws when the plugin was never installed instead of returning `undefined` typed as an importer. + +## `@oneschema/angular` + +`OneSchemaService` still extends the importer, so the change is `launch()`'s promise. Call it from a component method that handles the rejection rather than from a template expression, which would leave it unhandled: + +```typescript +launch() { + this.oneschema.launch().catch((failure) => console.error(failure)) +} +``` + +`@oneschema/angular` depends on `@oneschema/importer` directly. If your application imports the core itself, widen your own dependency range to admit the version this wrapper requires. + +## Codemod + +An unpublished [jscodeshift](https://github.com/facebook/jscodeshift) transform handles the mechanical part. There is no package to install: check the repository out at the release tag and run the transform from disk, so you execute a reviewed revision rather than whatever `main` holds today (`jscodeshift` loads the transform into your Node process, so read it before you run it). + +```bash +git clone --depth 1 --branch @oneschema/importer@0.8.0 \ + https://github.com/oneschema/sdk.git /tmp/oneschema-sdk + +npx jscodeshift@0.15.2 \ + -t /tmp/oneschema-sdk/scripts/codemod-0.8.cjs \ + --parser=tsx \ + src/ +``` + +It only touches what it can attribute to the importer: `parentId` inside the options object of a factory imported from an `@oneschema` package, `parentId` on a component imported from one, and `launch()`/`launchSession()` on a local bound to one. Anything else keeps its `parentId` or its `launch()` and gets a `TODO`. It rewrites `parentId` to `parent: document.getElementById(…) ?? undefined` (as an option and as a React prop, since `parent` is `HTMLElement | undefined` and `getElementById` can return `null`), unwraps the exact `const { success } = importer.launch(…)` into an `await` inside a `try`/`catch` where the enclosing function is already `async`, awaits a discarded `launch()` in an `async` function, and gives a discarded one in a synchronous function a `.catch()` that logs the failure for you to replace. Everything it cannot decide safely — a `success` payload read without a `type` check, a destructured `launch()` in a non-`async` function or one binding more than `success`, a launch call whose receiver it cannot attribute, a `_`-prefixed member — is left in place with a `TODO(oneschema-0.8)` comment. Every rewrite and every `TODO` is listed in the run's summary, so a plain-JavaScript codebase still gets the list of call sites to walk. Add `--dry --print` to preview without writing. + +TypeScript flags the rest once the old types are gone, so a typed codebase does not need the codemod to find its call sites — only to save the typing. + +## Checklist + +- [ ] every `launch()` and `launchSession()` call site awaits the promise or attaches a `.catch()` +- [ ] `success` handlers narrow on `result.type` +- [ ] `parentId` replaced with `parent` +- [ ] `devMode` passed explicitly if you relied on it in development +- [ ] `handlerTimeoutMs` raised if your `success` handler can legitimately take longer than 30 seconds +- [ ] `baseUrl` points at a deployment carrying the `0.8` protocol +- [ ] React: `isOpen` kept only where you want controlled visibility, and `onRequestClose` removed where you do not diff --git a/packages/importer-angular/projects/oneschema/README.md b/packages/importer-angular/projects/oneschema/README.md index ebfc1ed..73a2741 100644 --- a/packages/importer-angular/projects/oneschema/README.md +++ b/packages/importer-angular/projects/oneschema/README.md @@ -172,6 +172,10 @@ export class OneSchemaIframeComponent implements AfterViewInit { } ``` +## Migrating from 0.7 + +[MIGRATING-0.8.md](https://github.com/oneschema/sdk/blob/main/MIGRATING-0.8.md) walks through the 0.7.7 → 0.8 hop for this package and the core importer it wraps, with a codemod for the mechanical parts. + ## Documentation Please see [📚 OneSchema's documentation](https://docs.oneschema.co/) for [📒 API reference](https://docs.oneschema.co/docs/angular#api-reference) and other helpful guides. diff --git a/packages/importer-react/README.md b/packages/importer-react/README.md index 4c9af0e..cb1e569 100644 --- a/packages/importer-react/README.md +++ b/packages/importer-react/README.md @@ -149,7 +149,7 @@ params. | `onCancel` | `() => void \| Promise` | | | Handler for when the importing flow is cancelled by user. The importer waits for a returned promise to settle before it closes | | `onError` | `(error: OneSchemaError) => void` | | | Handler for when an error occurs during the import | | `onPageLoad` | `() => void` | | | Handler for when the embedded Importer page is loaded behind the scenes. | -| `onLaunched` | `(result: OneSchemaLaunchStatus) => void` | | | Handler for when the importer is launched (aka is ready to be shown) Or when launching fails, based on result | +| `onLaunched` | `(result: OneSchemaLaunchEvent) => void` | | | Handler for when the importer is launched (aka is ready to be shown) Or when launching fails, based on result | | `onUserActivity` | `() => void` | | | Handler for when user activity is detected inside the importer iframe. Useful for resetting session idle timers in the host application. This event is throttled (fired at most once every 30 seconds). | @@ -199,7 +199,7 @@ Each event below is exposed as the matching `on*` prop. | Event | Listener arguments | Description | | --------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `page-loaded` | `Record` | The embedded importer page finished loading behind the scenes | -| `launched` | `OneSchemaLaunchStatus` | The import session was launched, or launching it failed | +| `launched` | `OneSchemaLaunchEvent` | The import session was launched, or launching it failed | | `success` | `OneSchemaImportResult` | The user finished importing. For `local` imports the data is the payload, for `webhook` imports it summarizes the delivery. Awaited: a handler returning a promise holds the resume token and `autoClose` until it settles, bounded by `handlerTimeoutMs`, and a handler that throws or rejects is reported as an `error` event | | `cancel` | none | The user cancelled the import. Awaited on the same terms as `success` | | `error` | `OneSchemaError` | Something went wrong. `severity` is `fatal` when the session cannot continue | @@ -207,6 +207,10 @@ Each event below is exposed as the matching `on*` prop. +## Migrating from 0.7 + +[MIGRATING-0.8.md](https://github.com/oneschema/sdk/blob/main/MIGRATING-0.8.md) walks through the 0.7.7 → 0.8 hop for this package and the core importer it wraps, with a codemod for the mechanical parts. + ## Documentation Please see [📚 OneSchema's documentation](https://docs.oneschema.co/) for [📒 API reference](https://docs.oneschema.co/docs/react#api-reference) and other helpful guides. diff --git a/packages/importer-react/src/OneSchemaImporter.tsx b/packages/importer-react/src/OneSchemaImporter.tsx index a441552..7ae370f 100644 --- a/packages/importer-react/src/OneSchemaImporter.tsx +++ b/packages/importer-react/src/OneSchemaImporter.tsx @@ -5,11 +5,11 @@ import oneschemaImporter, { OneSchemaImporterClass, OneSchemaImporterStatus, OneSchemaImportResult, + OneSchemaLaunchEvent, OneSchemaLaunchInfo, OneSchemaLaunchParamOptions, OneSchemaLaunchParams, OneSchemaLaunchSessionParams, - OneSchemaLaunchStatus, } from "@oneschema/importer" import React, { useCallback, @@ -147,7 +147,7 @@ export interface OneSchemaImporterBaseProps { * Handler for when the importer is launched (aka is ready to be shown) * Or when launching fails, based on result */ - onLaunched?: (result: OneSchemaLaunchStatus) => void + onLaunched?: (result: OneSchemaLaunchEvent) => void /** * Handler for when user activity is detected inside the importer iframe. diff --git a/packages/importer-vue/README.md b/packages/importer-vue/README.md index d63f9e0..211e7a6 100644 --- a/packages/importer-vue/README.md +++ b/packages/importer-vue/README.md @@ -97,6 +97,10 @@ importer.on("error", (error) => { ``` +## Migrating from 0.7 + +[MIGRATING-0.8.md](https://github.com/oneschema/sdk/blob/main/MIGRATING-0.8.md) walks through the 0.7.7 → 0.8 hop for this package and the core importer it wraps, with a codemod for the mechanical parts. + ## Documentation Please see [📚 OneSchema's documentation](https://docs.oneschema.co/) for [📒 API reference](https://docs.oneschema.co/docs/vue#api-reference) and other helpful guides. diff --git a/packages/importer/README.md b/packages/importer/README.md index cb7c65d..8966239 100644 --- a/packages/importer/README.md +++ b/packages/importer/README.md @@ -129,21 +129,20 @@ The tables below are generated from the TypeScript types by -| Option | Type | Required | Default | Description | -| ------------------ | ------------------------------ | -------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `clientId` | `string` | yes | | The client id from your OneSchema developer dashboard | -| `devMode` | `boolean` | | `!!(process.env.NODE_ENV !== "production")` | Whether to launch the importer in dev mode, which shows the iframe even when launching fails | -| `className` | `string` | | `"oneschema-iframe"` | CSS class for the iframe | -| `styles` | `Partial` | | | CSS Styles to be applied directly to the iframe | -| `languageCode` | `string` | | | Optional language code (like 'en' or 'zh') to force importer language By default, will use user's set language. Requires enterprise licensing | -| `parent` | `HTMLElement` | | | The DOM element the iframe should be appended to By default appends to document.body | -| `parentId` | `string` | | | The id of the DOM element the iframe should be appended to **Deprecated:** Pass `parent` instead. An id is resolved once, at construction, so it falls back to document.body when the element does not exist yet. | -| `saveSession` | `boolean` | | `true` | Whether to save session information to local storage and enable resuming | -| `autoClose` | `boolean` | | `true` | Whether to close the importer when complete | -| `manageDOM` | `boolean` | | `true` | Whether the class should create and append the iframe to the DOM | -| `baseUrl` | `string` | | `"https://embed.oneschema.co"` | The base URL for the iframe. By default uses OneSchema's production instance | -| `initTimeoutMs` | `number` | | `20000` | How long a launch may stay pending before `launch()` rejects with `OneSchemaLaunchError.Timeout`, in milliseconds. The deadline covers the whole launch, not only the init acknowledgement. Raise it for hosts on slow or distant connections. The deadline cannot be turned off: `0`, a negative number and a non-finite number all fall back to the default, because a launch that never settles cannot be reported. Defaults to 20000 | -| `handlerTimeoutMs` | `number` | | `30000` | How long the importer waits for the `success` and `cancel` handlers of the host to settle before it clears the resume token and applies `autoClose`, in milliseconds. Raise it for handlers that ship rows to a slow or distant backend: a handler that has not settled by the deadline gets an `error` event and the session is cleaned up without it. `0` waits forever, which reintroduces the stranded-embed failure mode where a handler that never settles leaves the importer open with a stale resume token. A negative or non-finite number falls back to the default. Defaults to 30000 | +| Option | Type | Required | Default | Description | +| ------------------ | ------------------------------ | -------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `clientId` | `string` | yes | | The client id from your OneSchema developer dashboard | +| `devMode` | `boolean` | | `false` | Whether to launch the importer in dev mode, which shows the iframe even when launching fails. Defaults to `false`; wire it to your own build condition to enable it during development | +| `className` | `string` | | `"oneschema-iframe"` | CSS class for the iframe | +| `styles` | `Partial` | | | CSS Styles to be applied directly to the iframe | +| `languageCode` | `string` | | | Optional language code (like 'en' or 'zh') to force importer language By default, will use user's set language. Requires enterprise licensing | +| `parent` | `HTMLElement` | | | The DOM element the iframe should be appended to By default appends to document.body | +| `saveSession` | `boolean` | | `true` | Whether to save session information to local storage and enable resuming | +| `autoClose` | `boolean` | | `true` | Whether to close the importer when complete | +| `manageDOM` | `boolean` | | `true` | Whether the class should create and append the iframe to the DOM | +| `baseUrl` | `string` | | `"https://embed.oneschema.co"` | The base URL for the iframe. By default uses OneSchema's production instance | +| `initTimeoutMs` | `number` | | `20000` | How long a launch may stay pending before `launch()` rejects with `OneSchemaLaunchError.Timeout`, in milliseconds. The deadline covers the whole launch, not only the init acknowledgement. Raise it for hosts on slow or distant connections. The deadline cannot be turned off: `0`, a negative number and a non-finite number all fall back to the default, because a launch that never settles cannot be reported. Defaults to 20000 | +| `handlerTimeoutMs` | `number` | | `30000` | How long the importer waits for the `success` and `cancel` handlers of the host to settle before it clears the resume token and applies `autoClose`, in milliseconds. Raise it for handlers that ship rows to a slow or distant backend: a handler that has not settled by the deadline gets an `error` event and the session is cleaned up without it. `0` waits forever, which reintroduces the stranded-embed failure mode where a handler that never settles leaves the importer open with a stale resume token. A negative or non-finite number falls back to the default. Defaults to 30000 | @@ -181,7 +180,7 @@ Or, instead of those, with a session token created through the API: | Event | Listener arguments | Description | | --------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `page-loaded` | `Record` | The embedded importer page finished loading behind the scenes | -| `launched` | `OneSchemaLaunchStatus` | The import session was launched, or launching it failed | +| `launched` | `OneSchemaLaunchEvent` | The import session was launched, or launching it failed | | `success` | `OneSchemaImportResult` | The user finished importing. For `local` imports the data is the payload, for `webhook` imports it summarizes the delivery. Awaited: a handler returning a promise holds the resume token and `autoClose` until it settles, bounded by `handlerTimeoutMs`, and a handler that throws or rejects is reported as an `error` event | | `cancel` | none | The user cancelled the import. Awaited on the same terms as `success` | | `error` | `OneSchemaError` | Something went wrong. `severity` is `fatal` when the session cannot continue | @@ -191,7 +190,9 @@ Or, instead of those, with a session token created through the API: ## Migrating from 0.7 -- `parentId` is deprecated in favor of `parent`, which takes the element itself. `parentId` is resolved once when the importer is constructed, so it silently falls back to `document.body` when the container is not in the DOM yet. +[MIGRATING-0.8.md](https://github.com/oneschema/sdk/blob/main/MIGRATING-0.8.md) walks through the whole 0.7.7 → 0.8 hop, package by package, with a codemod for the mechanical parts. In short: + +- `parentId` is gone in favor of `parent`, which takes the element itself. `parentId` was resolved once when the importer was constructed, so it silently fell back to `document.body` when the container was not in the DOM yet. - Each importer instance now creates and removes its own iframe instead of sharing a single `_oneschema-iframe` element. Anything that looked that element up by id should keep a reference to `importer.iframe` instead. - The internal `_hasAttemptedLaunch` field is gone; use `importer.status` instead. - `launch()` and `launchSession()` return a promise instead of a `{ success }` object. Replace `const { success } = importer.launch()` with `await importer.launch()` in a `try`/`catch`, or attach a `.catch()`. Every failure the embed or the launch deadline produces still fires the `launched` event, so event-driven hosts keep working, but an unhandled rejection is reported by the browser — attach a handler even when the event is what you act on. A launch the host abandons itself — `close()`, `destroy()` or a newer `launch()` — only rejects its promise with `OneSchemaLaunchError.Cancelled`; it fires no `launched` event, since the host already knows it ended the attempt. diff --git a/packages/importer/src/config.ts b/packages/importer/src/config.ts index 2d22203..f06ee7a 100644 --- a/packages/importer/src/config.ts +++ b/packages/importer/src/config.ts @@ -515,44 +515,49 @@ export interface OneSchemaLaunchInfo { embedId?: string } -export interface OneSchemaLaunchStatus { - /** - * Whether or not launch was successful - */ - success: boolean - /** - * If success is true, include a session token - */ - sessionToken?: string - /** - * If success is true, include the embed ID - */ - embedId?: string +/** + * A launch attempt that started an import session + */ +export interface OneSchemaLaunchSucceeded extends OneSchemaLaunchInfo { + success: true +} + +/** + * A launch attempt that could not start an import session. The same detail is + * carried by the `OneSchemaLaunchFailure` the `launch()` promise rejects with + */ +export interface OneSchemaLaunchFailed { + success: false /** - * If success is false, this will be why it failed + * Why the launch failed */ - error?: OneSchemaLaunchError + error: OneSchemaLaunchError /** - * If success is false, a human-readable description of the failure + * A human-readable description of the failure */ - message?: string + message: string /** - * If success is false, the HTTP status OneSchema responded with, when the - * failure came from an API call + * The HTTP status OneSchema responded with, when the failure came from an + * API call */ status?: number /** - * If success is false, the raw error body OneSchema responded with, when - * one was included + * The raw error body OneSchema responded with, when one was included */ data?: unknown /** - * An id shared with the `launch()` resolution or rejection for the same - * attempt, so a support report can name one launch + * An id shared with the `launch()` rejection for the same attempt, so a + * support report can name one launch */ embedInitId: string } +/** + * The outcome of one launch attempt, as reported by the `launched` event. + * Narrow on `success` before reading either branch's fields + */ +export type OneSchemaLaunchEvent = OneSchemaLaunchSucceeded | OneSchemaLaunchFailed + /** * Parameters for the OneSchema importer set at initialization */ @@ -563,7 +568,8 @@ export interface OneSchemaInitParams { clientId: string /** * Whether to launch the importer in dev mode, which shows the iframe even - * when launching fails + * when launching fails. Defaults to `false`; wire it to your own build + * condition to enable it during development */ devMode?: boolean /** @@ -585,11 +591,6 @@ export interface OneSchemaInitParams { * By default appends to document.body */ parent?: HTMLElement - /** - * The id of the DOM element the iframe should be appended to - * @deprecated Pass `parent` instead. An id is resolved once, at construction, so it falls back to document.body when the element does not exist yet. - */ - parentId?: string /** * Whether to save session information to local storage and enable resuming */ @@ -691,7 +692,7 @@ export type OneSchemaInitMessage = */ export const DEFAULT_PARAMS: Partial = { baseUrl: "https://embed.oneschema.co", - devMode: !!(process.env.NODE_ENV !== "production"), + devMode: false, className: "oneschema-iframe", initTimeoutMs: 20000, handlerTimeoutMs: 30000, @@ -769,7 +770,7 @@ export interface OneSchemaEventMap { /** * The import session was launched, or launching it failed */ - launched: [OneSchemaLaunchStatus] + launched: [OneSchemaLaunchEvent] /** * The user finished importing. For `local` imports the data is the payload, * for `webhook` imports it summarizes the delivery. diff --git a/packages/importer/src/importer.ts b/packages/importer/src/importer.ts index 01d44eb..fd2abd4 100644 --- a/packages/importer/src/importer.ts +++ b/packages/importer/src/importer.ts @@ -12,10 +12,10 @@ import { OneSchemaInitSessionMessage, OneSchemaInitSimpleMessage, OneSchemaLaunchError, + OneSchemaLaunchFailed, OneSchemaLaunchInfo, OneSchemaLaunchParams, OneSchemaLaunchSessionParams, - OneSchemaLaunchStatus, OneSchemaParams, OneSchemaSharedInitParams, } from "./config" @@ -62,7 +62,7 @@ const DEFAULT_LAUNCH_ERROR_MESSAGE = "OneSchema failed to launch the import sess */ function parseLaunchErrorDetail( detail: unknown, -): Pick { +): Pick { if (typeof detail === "string") { return { message: detail } } @@ -129,32 +129,10 @@ export class OneSchemaImporterClass extends EventEmitter { const iframe = document.createElement("iframe") iframe.id = `_oneschema-iframe-${++iframeCount}` this.setIframe(iframe) - this.setParent(this.#resolveParent()) + this.setParent(this.#params.parent ?? document.body) } } - #resolveParent(): HTMLElement { - if (this.#params.parent) { - return this.#params.parent - } - - if (this.#params.parentId) { - console.warn( - "OneSchema: parentId is deprecated, pass parent as an HTMLElement instead", - ) - const parent = document.getElementById(this.#params.parentId) - if (parent) { - return parent - } - - console.error( - `OneSchema config error: no element with id "${this.#params.parentId}" exists yet, appending the importer to document.body instead`, - ) - } - - return document.body - } - /** * Where this instance is in its lifecycle: * diff --git a/packages/importer/test/index.ts b/packages/importer/test/index.ts index 189215d..9303ab8 100644 --- a/packages/importer/test/index.ts +++ b/packages/importer/test/index.ts @@ -9,7 +9,7 @@ function updateStatus(message: string, data?: Record) { const importer = oneSchemaImporter({ className: "oneschema-iframe", - parentId: "oneschema-container", + parent: document.getElementById("oneschema-container")!, baseUrl: "http://embed.localschema.co:9450", templateKey: "crm_test", clientId: "67bb2e5f-f0f7-42a6-a511-18b25e67b8c4", diff --git a/scripts/codemod-0.8.cjs b/scripts/codemod-0.8.cjs new file mode 100644 index 0000000..e461b02 --- /dev/null +++ b/scripts/codemod-0.8.cjs @@ -0,0 +1,446 @@ +/** + * jscodeshift transform for the @oneschema/importer 0.7.7 -> 0.8 migration. + * + * Unpublished on purpose: check the repository out at the release tag and run + * this file from disk, see MIGRATING-0.8.md. + * + * npx jscodeshift@0.15.2 -t /scripts/codemod-0.8.cjs --parser=tsx src/ + * + * It only rewrites what it can decide from the syntax alone. Anything that + * needs a human gets a TODO(oneschema-0.8) comment instead, so a codebase + * without types still has a list of call sites to walk. + */ + +const TODO = "TODO(oneschema-0.8): " + +const REMOVED_MEMBERS = [ + "_hasAttemptedLaunch", + "_launch", + "_initWithRetry", + "_resetSession", +] + +const LAUNCH_METHODS = ["launch", "launchSession"] + +const IMPORTER_MODULES = [ + "@oneschema/importer", + "@oneschema/react", + "@oneschema/vue", + "@oneschema/angular", +] + +module.exports = function transform(fileInfo, api) { + const j = api.jscodeshift + const root = j(fileInfo.source) + const notes = [] + + const note = (message, node) => { + notes.push(`${fileInfo.path}:${node.loc ? node.loc.start.line : "?"} ${message}`) + } + + const annotate = (path, message) => { + // closest() only walks ancestors, so a path that is already a statement + // would otherwise annotate the function enclosing it. + let node = path.node + if (!j.Statement.check(node)) { + const statement = j(path).closest(j.Statement) + if (!statement.size()) { + return + } + node = statement.paths()[0].node + } + + const comments = node.comments || [] + if (comments.some((comment) => comment.value.includes(TODO))) { + return + } + + node.comments = [...comments, j.commentLine(` ${TODO}${message}`, true, false)] + } + + // Only names the file imports from an @oneschema package can be recognized as + // the importer; every other `.launch()` or `parentId` in the codebase belongs + // to the host and must not be rewritten. + const oneschemaLocals = new Set() + + root.find(j.ImportDeclaration).forEach((path) => { + if (!IMPORTER_MODULES.includes(path.node.source.value)) { + return + } + + path.node.specifiers.forEach((specifier) => { + if (specifier.local) { + oneschemaLocals.add(specifier.local.name) + } + }) + }) + + root.find(j.VariableDeclarator).forEach((path) => { + const { id, init } = path.node + if ( + id.type !== "Identifier" || + !init || + init.type !== "CallExpression" || + init.callee.type !== "Identifier" || + init.callee.name !== "require" || + init.arguments.length !== 1 + ) { + return + } + + const [source] = init.arguments + if (source.type === "StringLiteral" && IMPORTER_MODULES.includes(source.value)) { + oneschemaLocals.add(id.name) + } + }) + + // Instances: `const importer = oneschemaImporter(...)`, `new OneSchemaImporterClass(...)`, + // and refs whose declaration names a OneSchema type (`useRef`). + const importerLocals = new Set() + const refLocals = new Set() + + root.find(j.VariableDeclarator).forEach((path) => { + const { id, init } = path.node + if (id.type !== "Identifier" || !init) { + return + } + + const callee = + init.type === "CallExpression" || init.type === "NewExpression" + ? init.callee + : undefined + + if (callee && callee.type === "Identifier" && oneschemaLocals.has(callee.name)) { + importerLocals.add(id.name) + return + } + + if ( + init.type === "CallExpression" && + init.callee.type === "Identifier" && + init.callee.name === "useRef" && + j(path).toSource().includes("OneSchema") + ) { + refLocals.add(id.name) + } + }) + + const isImporterReceiver = (node) => { + if (node.type === "Identifier") { + return importerLocals.has(node.name) || oneschemaLocals.has(node.name) + } + + // `importerRef.current.launch()`; any other property receiver only counts + // when a local of that name is itself a known importer. + if (node.type === "MemberExpression" && node.property.type === "Identifier") { + if (node.property.name === "current" && node.object.type === "Identifier") { + return refLocals.has(node.object.name) || importerLocals.has(node.object.name) + } + + return importerLocals.has(node.property.name) + } + + return false + } + + const isLaunchCall = (node) => + node.type === "CallExpression" && + node.callee.type === "MemberExpression" && + node.callee.property.type === "Identifier" && + LAUNCH_METHODS.includes(node.callee.property.name) && + isImporterReceiver(node.callee.object) + + const isUnrecognizedLaunchCall = (node) => + node.type === "CallExpression" && + node.callee.type === "MemberExpression" && + node.callee.property.type === "Identifier" && + LAUNCH_METHODS.includes(node.callee.property.name) && + !isImporterReceiver(node.callee.object) + + // getElementById() widens to HTMLElement | null, which parent?: HTMLElement + // does not accept. + const parentIdReplacement = (value) => + j.logicalExpression( + "??", + j.callExpression( + j.memberExpression(j.identifier("document"), j.identifier("getElementById")), + [value], + ), + j.identifier("undefined"), + ) + + // parentId: "x" -> parent: document.getElementById("x"), inside the options + // object of a recognized importer factory only. + root.find(j.ObjectProperty, { key: { name: "parentId" } }).forEach((path) => { + const call = j(path).closest(j.CallExpression) + const callee = call.size() ? call.paths()[0].node.callee : undefined + const inImporterOptions = + callee && + ((callee.type === "Identifier" && oneschemaLocals.has(callee.name)) || + (callee.type === "MemberExpression" && + callee.property.type === "Identifier" && + LAUNCH_METHODS.includes(callee.property.name) && + isImporterReceiver(callee.object))) + + if (!inImporterOptions) { + annotate( + path, + "parentId is gone: if this is a OneSchema option, pass parent: HTMLElement instead", + ) + note( + "parentId left for a human: not a recognized importer options object", + path.node, + ) + return + } + + path.node.key = j.identifier("parent") + path.node.value = parentIdReplacement(path.node.value) + note("parentId rewritten to parent", path.node) + }) + + // parentId="x" -> parent={document.getElementById("x")}, on an imported + // OneSchema component only. + root.find(j.JSXAttribute, { name: { name: "parentId" } }).forEach((path) => { + const element = j(path).closest(j.JSXOpeningElement) + const name = element.size() ? element.paths()[0].node.name : undefined + const component = + name && name.type === "JSXIdentifier" + ? name.name + : name && + name.type === "JSXMemberExpression" && + name.property.type === "JSXIdentifier" + ? name.property.name + : undefined + + if (!component || !oneschemaLocals.has(component)) { + annotate( + path, + "parentId is gone: if this is a OneSchema component, pass parent={element} instead", + ) + note( + "parentId prop left for a human: not a recognized importer component", + path.node, + ) + return + } + + const value = path.node.value + const inner = + value && value.type === "JSXExpressionContainer" ? value.expression : value + + if (!inner || inner.type === "JSXEmptyExpression") { + annotate(path, "parentId is gone: pass parent={element} instead") + note("parentId prop left for a human: it carries no value", path.node) + return + } + + path.node.name = j.jsxIdentifier("parent") + path.node.value = j.jsxExpressionContainer(parentIdReplacement(inner)) + note("parentId prop rewritten to parent", path.node) + }) + + // Only the exact `{ success }` shorthand can be replaced by a boolean of the + // same name; an alias or a second binding would lose its declaration. + const isPlainSuccessPattern = (pattern) => { + if (pattern.properties.length !== 1) { + return false + } + + const [property] = pattern.properties + return ( + property.type === "ObjectProperty" && + !property.computed && + property.key.type === "Identifier" && + property.key.name === "success" && + property.value.type === "Identifier" && + property.value.name === "success" + ) + } + + const isSuccessDestructuring = (declarator) => + declarator.type === "VariableDeclarator" && + declarator.id.type === "ObjectPattern" && + declarator.id.properties.some( + (property) => + property.type === "ObjectProperty" && + property.key.type === "Identifier" && + property.key.name === "success", + ) && + declarator.init && + isLaunchCall(declarator.init) + + // const { success } = importer.launch() -> await importer.launch() in a try + root + .find(j.VariableDeclaration) + .filter((path) => { + const [declarator] = path.node.declarations + return ( + path.node.declarations.length === 1 && + declarator.type === "VariableDeclarator" && + declarator.id.type === "ObjectPattern" && + isPlainSuccessPattern(declarator.id) && + declarator.init && + isLaunchCall(declarator.init) + ) + }) + .forEach((path) => { + const call = path.node.declarations[0].init + const enclosing = j(path).closest(j.Function) + const isAsync = enclosing.size() > 0 && enclosing.paths()[0].node.async + + if (!isAsync) { + annotate( + path, + "launch() now returns a promise: await it in an async function, or attach a .catch()", + ) + note( + "launch() destructuring left for a human: enclosing function is not async", + path.node, + ) + return + } + + // `success` stays a boolean so the statements after it keep compiling. + const flag = j.variableDeclaration("let", [ + j.variableDeclarator(j.identifier("success"), j.booleanLiteral(true)), + ]) + const attempt = j.tryStatement( + j.blockStatement([j.expressionStatement(j.awaitExpression(call))]), + j.catchClause( + j.identifier("failure"), + null, + j.blockStatement([ + j.expressionStatement( + j.assignmentExpression( + "=", + j.identifier("success"), + j.booleanLiteral(false), + ), + ), + ]), + ), + ) + attempt.comments = [ + j.commentLine( + ` ${TODO}failure is a OneSchemaLaunchFailure: report it instead of the flag`, + true, + false, + ), + ] + + j(path).replaceWith(flag) + path.insertAfter(attempt) + note("launch() destructuring rewritten to await/try", path.node) + }) + + // Anything else destructured off a launch call keeps its bindings and gets a note. + root + .find(j.VariableDeclaration) + .filter( + (path) => + path.node.declarations.length === 1 && + isSuccessDestructuring(path.node.declarations[0]) && + !isPlainSuccessPattern(path.node.declarations[0].id), + ) + .forEach((path) => { + annotate( + path, + "launch() now returns a promise: await it and read OneSchemaLaunchInfo, or catch OneSchemaLaunchFailure", + ) + note( + "launch() destructuring left for a human: it binds more than success", + path.node, + ) + }) + + // importer.launch() as a discarded statement -> .catch() + root + .find(j.ExpressionStatement) + .filter((path) => isLaunchCall(path.node.expression)) + .forEach((path) => { + // Rejections have to go somewhere: awaiting hands them to the caller, + // and a synchronous call site gets a reporting catch to replace. + const enclosing = j(path).closest(j.Function) + if (enclosing.size() > 0 && enclosing.paths()[0].node.async) { + path.node.expression = j.awaitExpression(path.node.expression) + note("launch() awaited, rejection now propagates to the caller", path.node) + return + } + + path.node.expression = j.callExpression( + j.memberExpression(path.node.expression, j.identifier("catch")), + [ + j.arrowFunctionExpression( + [j.identifier("failure")], + j.blockStatement([ + j.expressionStatement( + j.callExpression( + j.memberExpression(j.identifier("console"), j.identifier("error")), + [j.identifier("failure")], + ), + ), + ]), + ), + ], + ) + note("launch() given a reporting .catch()", path.node) + }) + + // A launch call this transform cannot attribute to an importer: never rewritten. + root + .find(j.CallExpression) + .filter((path) => isUnrecognizedLaunchCall(path.node)) + .forEach((path) => { + annotate( + path, + "if this is a OneSchema importer, launch() now returns a promise: await it or attach a .catch()", + ) + note("launch() call left for a human: receiver is not a known importer", path.node) + }) + + // Removed internals and untagged success payloads: flag only. + root + .find(j.MemberExpression) + .filter( + (path) => + path.node.property.type === "Identifier" && + REMOVED_MEMBERS.includes(path.node.property.name), + ) + .forEach((path) => { + annotate( + path, + `${path.node.property.name} was removed: read importer.status instead`, + ) + note(`${path.node.property.name} is no longer published`, path.node) + }) + + root + .find(j.CallExpression, { + callee: { type: "MemberExpression", property: { name: "on" } }, + }) + .filter((path) => { + const [event] = path.node.arguments + return ( + event && + event.type === "StringLiteral" && + event.value === "success" && + isImporterReceiver(path.node.callee.object) + ) + }) + .forEach((path) => { + annotate( + path, + "the success payload is now discriminated: narrow on result.type before reading result.data", + ) + note("success handler needs narrowing on result.type", path.node) + }) + + if (notes.length) { + console.warn(`oneschema-0.8:\n ${notes.join("\n ")}`) + } + + return notes.length ? root.toSource({ quote: "double" }) : null +} + +module.exports.parser = "tsx"