From 84ab641e78a7a463f4b3aab0b3f6487855dd3aca Mon Sep 17 00:00:00 2001 From: K8Sewell Date: Mon, 12 Oct 2026 18:23:20 -0500 Subject: [PATCH 1/2] Add auth and error handling sections --- README.md | 153 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) diff --git a/README.md b/README.md index 0c64cea..a3bcd64 100644 --- a/README.md +++ b/README.md @@ -42,3 +42,156 @@ and navigating to examples/index.html. git commit -m "Release v1.2.3" git tag v1.2.3 git push origin main v1.2.3 + +## Error handling + +`loadManifest()` and `loadManifestJson()` reject with an `Error` when loading fails, including when a child manifest or sub-collection fails, an index doesn't exist, the JSON isn't a IIIF resource, or collections contain themselves or are nested more than 10 deep. Errors from manifesto are passed through unchanged. + +| Property | When it's set | +| ---------- | ------------------------------------------------------- | +| `message` | Always | +| `url` | The URL that failed; may be a child resource | +| `status` | HTTP errors only (e.g. `404`) | +| `response` | HTTP errors only; the raw `Response` | +| `index` | Missing `manifestIndex` / `collectionIndex` errors only | + +```ts +try { + const helper = await loadManifest({ manifestUri }); +} catch (err: any) { + showMessage( + err?.status === 404 ? "Manifest not found." : "Unable to load manifest." + ); +} +``` + +Older versions of manifesto may reject with `undefined`, so read errors defensively. + +`ExternalResource.getData()` resolves rather than rejects when a request fails. It rejects only when there is no `dataUri` to fetch. After it resolves, check `status` and `error`. + +`status` is one of: + +- the HTTP status of the response; +- `302` when the server returned a lower tier of [tiered access](https://iiif.io/api/auth/1.0/#tiered-access) (for example a lower-resolution image) and there is a login service for the full version. This is set by Manifold, not by the server: the browser follows real redirects without reporting them; +- `0` when no HTTP response arrived (network failure, CORS, timeout or abort). + +`error` is `undefined` on success. Otherwise it is an `Error` with `url` and `reason`: + +| `reason` | When it's set | +| ---------------- | ---------------------------------------------------------------------------- | +| `"http"` | The response had a non-2xx status, such as `401` for an invalid access token | +| `"invalid-json"` | The response had a 2xx status, but the body wasn't a usable JSON object | +| `"network"` | No response arrived (network failure or CORS) | +| `"timeout"` | The request took longer than `timeout` | +| `"abort"` | The request was aborted | + +`error` is reset at the start of each `getData()` call, so a retry that succeeds clears it. + +Authentication is a separate check from `error`. A `401` sets `error` with `reason: "http"`, but its body is still read: login and other auth services are parsed into properties such as `loginService`, and the body is stored in `data`. Check for auth before treating `error` as a failure: + +```ts +await resource.getData(accessToken); + +if (resource.status === 401 && resource.isAccessControlled()) { + showLogin(resource.loginService); +} else if (resource.error) { + showMessage( + `Unable to load ${resource.error.url} (${resource.error.reason}).` + ); +} +``` + +manifesto's auth flow only reads `status`, so it is not affected by `error`. + +Set `timeout` (milliseconds) before calling `getData()` to limit how long a request may take. The default `0` means no timeout. + +## IIIF Auth + +Manifold supports the [IIIF Authentication API 1.0](https://iiif.io/api/auth/1.0/). Pass `authApiVersion: 0.9` to `ExternalResource` for servers that still use the older 0.9 services. Auth API 2.0 is not supported. + +Manifold doesn't run the login flow itself. `ExternalResource` finds a resource's auth services and checks whether the user can access it. manifesto's `Utils.loadExternalResourcesAuth1()` runs the flow and calls back into your viewer to open login windows and fetch tokens. + +### What the manifest needs + +Manifold looks at the first painting annotation on each canvas and the first body of that annotation (the first item if the body is a `Choice`). Content in other annotations or bodies isn't checked. + +- **Images:** if that body has an image service, Manifold requests `{service id}/info.json`. Put the auth services in the `info.json`, not the manifest. +- **Everything else** (audio, video, PDFs): Manifold uses the body's `id`. Put the auth services on the body in the manifest. + +Services are matched by `profile`: + +| Service | `profile` | Where it goes | +| ------------- | ---------------------------------------- | --------------------------------------------------------------------- | +| Click-through | `http://iiif.io/api/auth/1/clickthrough` | On the body or in the `info.json` | +| Login | `http://iiif.io/api/auth/1/login` | On the body or in the `info.json` | +| External | `http://iiif.io/api/auth/1/external` | On the body or in the `info.json` | +| Kiosk | `http://iiif.io/api/auth/1/kiosk` | On the body or in the `info.json` | +| Token | `http://iiif.io/api/auth/1/token` | Inside the click-through, login, external or kiosk service | +| Logout | `http://iiif.io/api/auth/1/logout` | Inside the click-through, login, external or kiosk service | +| Probe | `http://iiif.io/api/auth/1/probe` | On the body (inside the access service also works, but is deprecated) | + +Give each resource one access service (click-through, login, external or kiosk), and give that service a token service, or the user can't be granted access. The probe isn't part of the Auth 1.0 spec: it's an extension used by the British Library and the Universal Viewer (`AuthProbeService1`), and Auth 2.0 later standardised a different probe. A probe is only used alongside an access service; on its own it's ignored. In Presentation 3 you can declare a service once in the manifest's top-level `services` and refer to it by `id` from each body. + +An audio body with a login service and a probe: + +```json +{ + "id": "https://example.org/media/recording.mpd", + "type": "Sound", + "format": "application/dash+xml", + "service": [ + { + "id": "https://example.org/auth/login", + "type": "AuthCookieService1", + "profile": "http://iiif.io/api/auth/1/login", + "label": "Log in to Example Library", + "service": [ + { + "id": "https://example.org/auth/token", + "type": "AuthTokenService1", + "profile": "http://iiif.io/api/auth/1/token" + } + ] + }, + { + "id": "https://example.org/media/recording/probe.json", + "type": "AuthProbeService1", + "profile": "http://iiif.io/api/auth/1/probe" + } + ] +} +``` + +### How access is checked + +`ExternalResource.getData(accessToken?)` makes at most one request, depending on what the resource has: + +| Resource | Request | Result | +| -------------------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| Has a probe service | `GET` the probe | `302` if a successful probe's `contentLocation` differs from the content's URL; otherwise the response status | +| Has an image service | `GET` the `info.json` | Auth services are read from the body, even on a `401`. `302` if the `info.json` `id` differs and there's a login or kiosk service | +| Other, with no auth services | None | `200` | +| Other, with auth services but no probe | `HEAD` the content | The response status | + +`302` is Manifold's marker for [tiered access](https://iiif.io/api/auth/1.0/#tiered-access), not a real HTTP redirect. See [Error handling](#error-handling) for `status` and `error`. + +When an access token is given, it's sent as `Authorization: Bearer `. Requests are made without credentials, so cookies are never sent to the probe, `info.json` or content: access depends on the token alone. + +### The flow + +`Utils.loadExternalResourcesAuth1()` runs these steps for each resource: + +1. **With a stored token:** call `getData(token)`. A `200` means done. Anything else runs the auth chain. +2. **Without a stored token:** call `getData()`. A `302` or `401` runs the auth chain. Any other status skips it. +3. **Auth chain:** + - A `302` that hasn't been handled yet calls your `handleMovedTemporarily` callback, so the viewer can show the lower tier and offer a login. To log in, set `resource.isResponseHandled = true` and load the resource again. + - Otherwise it tries the services in this order: external, kiosk, click-through, login. For each, it opens the interaction (a login window, for example), waits for the user, gets a token from the token service and calls `getData(token)` again. + - If nothing worked, it calls `showOutOfOptionsMessages` with the last service it tried, so you can show that service's failure messages. +4. **Result:** a final status of `200` or `302` returns the resource. Anything else, including `403`, rejects with an authorization-failed error. + +### What servers should return + +- **Probe:** a JSON object. On success use a `2xx` status, and include `contentLocation` if the user will get a different version from the content's URL. Use `401` when the user needs to log in. +- **`info.json`:** a `401` with the full `info.json` (including its auth services) when the user needs to log in, or a `200` with a different `id` for a lower tier. +- **`403`:** use only when logging in won't help. The flow doesn't offer a login for it. +- **CORS:** allow the `Authorization` request header on the probe, `info.json` and content, so the token can be sent. From 4a0abc392b83ca3897a7bd349c506d093683db5e Mon Sep 17 00:00:00 2001 From: K8Sewell Date: Mon, 12 Oct 2026 18:23:50 -0500 Subject: [PATCH 2/2] Refactor error handling --- __tests__/bootstrapper.test.ts | 449 +++++++++++++++++++ __tests__/externalResource.test.ts | 690 +++++++++++++++++++++++++++++ src/Bootstrapper.ts | 62 ++- src/ExternalResource.ts | 239 +++++----- 4 files changed, 1315 insertions(+), 125 deletions(-) create mode 100644 __tests__/bootstrapper.test.ts create mode 100644 __tests__/externalResource.test.ts diff --git a/__tests__/bootstrapper.test.ts b/__tests__/bootstrapper.test.ts new file mode 100644 index 0000000..6a6d924 --- /dev/null +++ b/__tests__/bootstrapper.test.ts @@ -0,0 +1,449 @@ +import { Collection, Utils } from "manifesto.js"; +import { loadManifest, loadManifestJson } from "../src"; + +const TOP_ID = "https://example.org/iiif/collection/top"; +const SUB_ID = "https://example.org/iiif/collection/sub"; +const MANIFEST_ID = "https://example.org/iiif/manifest/1"; + +type Ref = { id: string; label: string }; + +// Builds the same IIIF documents in each Presentation API version's shape. +interface Presentation { + collection(id: string, refs: { collections?: Ref[]; manifests?: Ref[] }): any; + manifest(id: string): any; +} + +const v2: Presentation = { + collection: (id, { collections, manifests }) => { + const json: any = { + "@context": "http://iiif.io/api/presentation/2/context.json", + "@id": id, + "@type": "sc:Collection", + label: id, + }; + if (collections) { + json.collections = collections.map((c) => ({ + "@id": c.id, + "@type": "sc:Collection", + label: c.label, + })); + } + if (manifests) { + json.manifests = manifests.map((m) => ({ + "@id": m.id, + "@type": "sc:Manifest", + label: m.label, + })); + } + return json; + }, + manifest: (id) => ({ + "@context": "http://iiif.io/api/presentation/2/context.json", + "@id": id, + "@type": "sc:Manifest", + label: id, + sequences: [{ "@type": "sc:Sequence", canvases: [] }], + }), +}; + +const v3: Presentation = { + collection: (id, { collections = [], manifests = [] }) => ({ + "@context": "http://iiif.io/api/presentation/3/context.json", + id, + type: "Collection", + label: { en: [id] }, + items: [ + ...collections.map((c) => ({ + id: c.id, + type: "Collection", + label: { en: [c.label] }, + })), + ...manifests.map((m) => ({ + id: m.id, + type: "Manifest", + label: { en: [m.label] }, + })), + ], + }), + manifest: (id) => ({ + "@context": "http://iiif.io/api/presentation/3/context.json", + id, + type: "Manifest", + label: { en: [id] }, + items: [], + }), +}; + +// Mirrors the error shape Manifesto rejects with (IIIF-Commons/manifesto#196). +function httpError(status: number, url: string): Error { + const error: any = new Error("Not Found"); + error.status = status; + error.url = url; + error.response = { status }; + return error; +} + +function indexError(message: string, url: string, index: number): Error { + const error: any = new Error(message); + error.url = url; + error.index = index; + return error; +} + +// Serves JSON by URL; rejects after `limit` calls so a runaway loop still ends. +function serveJson(byUrl: Record any>, limit = 50) { + let calls = 0; + return jest.spyOn(Utils, "loadManifest").mockImplementation((url) => { + calls++; + if (calls > limit) { + return Promise.reject(new Error("runaway loading loop")); + } + return Promise.resolve(byUrl[url]()); + }); +} + +// Fails fast instead of hitting the Jest timeout when a promise never settles. +function settle(promise: Promise, ms = 500): Promise { + return Promise.race([ + promise, + new Promise((_, reject) => + setTimeout(() => reject(new Error("promise did not settle")), ms) + ), + ]); +} + +// Shared documents for one Presentation API version. +function fixtures(iiif: Presentation) { + return { + topCollection: () => + iiif.collection(TOP_ID, { + collections: [{ id: SUB_ID, label: "Sub" }], + manifests: [{ id: MANIFEST_ID, label: "Manifest 1" }], + }), + subCollection: () => + iiif.collection(SUB_ID, { + manifests: [{ id: MANIFEST_ID, label: "Manifest 1" }], + }), + // A collection with no manifests whose only member is another collection. + wrapperCollection: (id: string, childId: string) => + iiif.collection(id, { collections: [{ id: childId, label: childId }] }), + manifest: () => iiif.manifest(MANIFEST_ID), + }; +} + +describe.each([ + ["Presentation 2", v2], + ["Presentation 3", v3], +])("Bootstrapper loading (%s)", (_name, iiif) => { + const { topCollection, subCollection, wrapperCollection, manifest } = + fixtures(iiif); + const MANIFEST_2_ID = "https://example.org/iiif/manifest/2"; + + afterEach(() => { + jest.restoreAllMocks(); + }); + + test("loads a manifest from JSON", async () => { + const helper = await settle( + loadManifestJson(manifest(), { manifestUri: MANIFEST_ID }) + ); + + expect(helper.manifest!.id).toBe(MANIFEST_ID); + expect(helper.iiifResource!.id).toBe(MANIFEST_ID); + }); + + test("loads a manifest from a URL", async () => { + const load = serveJson({ [MANIFEST_ID]: manifest }); + + const helper = await settle(loadManifest({ manifestUri: MANIFEST_ID })); + + expect(load).toHaveBeenCalledWith(MANIFEST_ID); + expect(helper.manifest!.id).toBe(MANIFEST_ID); + }); + + test("defaults the locale to en-GB", async () => { + const helper = await settle( + loadManifestJson(manifest(), { manifestUri: MANIFEST_ID }) + ); + + expect(helper.options.locale).toBe("en-GB"); + }); + + test("loads the manifest at manifestIndex from a collection", async () => { + serveJson({ + [MANIFEST_ID]: manifest, + [MANIFEST_2_ID]: () => iiif.manifest(MANIFEST_2_ID), + }); + const json = iiif.collection(TOP_ID, { + manifests: [ + { id: MANIFEST_ID, label: "Manifest 1" }, + { id: MANIFEST_2_ID, label: "Manifest 2" }, + ], + }); + + const helper = await settle( + loadManifestJson(json, { manifestUri: TOP_ID, manifestIndex: 1 }) + ); + + expect(helper.manifest!.id).toBe(MANIFEST_2_ID); + expect(helper.manifestIndex).toBe(1); + expect(helper.iiifResource!.id).toBe(TOP_ID); + }); + + test("loads a manifest from the sub-collection at collectionIndex", async () => { + serveJson({ [SUB_ID]: subCollection, [MANIFEST_ID]: manifest }); + + const helper = await settle( + loadManifestJson(topCollection(), { + manifestUri: TOP_ID, + collectionIndex: 0, + manifestIndex: 0, + }) + ); + + expect(helper.manifest!.id).toBe(MANIFEST_ID); + expect(helper.collectionIndex).toBe(0); + expect(helper.iiifResource!.id).toBe(TOP_ID); + }); + + test("loads the first sub-collection when a collection has only sub-collections", async () => { + serveJson({ [SUB_ID]: subCollection, [MANIFEST_ID]: manifest }); + const json = iiif.collection(TOP_ID, { + collections: [{ id: SUB_ID, label: "Sub" }], + }); + + const helper = await settle( + loadManifestJson(json, { manifestUri: TOP_ID, manifestIndex: 0 }) + ); + + expect(helper.manifest!.id).toBe(MANIFEST_ID); + }); + + test("dives through nested collections to find the first manifest", async () => { + const MIDDLE_ID = "https://example.org/iiif/collection/middle"; + serveJson({ + [MIDDLE_ID]: () => wrapperCollection(MIDDLE_ID, SUB_ID), + [SUB_ID]: subCollection, + [MANIFEST_ID]: manifest, + }); + + const helper = await settle( + loadManifestJson(wrapperCollection(TOP_ID, MIDDLE_ID), { + manifestUri: TOP_ID, + manifestIndex: 0, + }) + ); + + expect(helper.manifest!.id).toBe(MANIFEST_ID); + expect(helper.iiifResource!.id).toBe(TOP_ID); + }); +}); + +describe.each([ + ["Presentation 2", v2], + ["Presentation 3", v3], +])("Bootstrapper error handling (%s)", (_name, iiif) => { + const { topCollection, subCollection, wrapperCollection, manifest } = + fixtures(iiif); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + test("rejects with Manifesto's error when the top-level manifest fails to load", async () => { + const error = httpError(404, MANIFEST_ID); + jest.spyOn(Utils, "loadManifest").mockRejectedValue(error); + + await expect( + settle(loadManifest({ manifestUri: MANIFEST_ID })) + ).rejects.toBe(error); + }); + + test("rejects when a collection's manifest fails to load", async () => { + const error = httpError(404, MANIFEST_ID); + jest + .spyOn(Collection.prototype, "getManifestByIndex") + .mockRejectedValue(error); + + await expect( + settle( + loadManifestJson(topCollection(), { + manifestUri: TOP_ID, + manifestIndex: 0, + }) + ) + ).rejects.toBe(error); + }); + + test("rejects with Manifesto's error when the manifest index does not exist", async () => { + const error = indexError("Manifest index not found", TOP_ID, 99); + jest + .spyOn(Collection.prototype, "getManifestByIndex") + .mockRejectedValue(error); + + await expect( + settle( + loadManifestJson(topCollection(), { + manifestUri: TOP_ID, + manifestIndex: 99, + }) + ) + ).rejects.toBe(error); + }); + + test("rejects when a child collection fails to load", async () => { + const error = httpError(404, SUB_ID); + jest + .spyOn(Collection.prototype, "getCollectionByIndex") + .mockRejectedValue(error); + + await expect( + settle( + loadManifestJson(topCollection(), { + manifestUri: TOP_ID, + collectionIndex: 0, + manifestIndex: 0, + }) + ) + ).rejects.toBe(error); + }); + + test("rejects when a child collection loads but its manifest fails", async () => { + const error = httpError(500, MANIFEST_ID); + const sub = Utils.parseManifest(subCollection()) as Collection; + jest + .spyOn(Collection.prototype, "getCollectionByIndex") + .mockResolvedValue(sub); + jest + .spyOn(Collection.prototype, "getManifestByIndex") + .mockRejectedValue(error); + + await expect( + settle( + loadManifestJson(topCollection(), { + manifestUri: TOP_ID, + collectionIndex: 0, + manifestIndex: 0, + }) + ) + ).rejects.toBe(error); + }); + + test("rejects when an older Manifesto throws synchronously for a missing index", async () => { + const error = new Error("Manifest index not found"); + const sub = Utils.parseManifest(subCollection()) as Collection; + jest + .spyOn(Collection.prototype, "getCollectionByIndex") + .mockResolvedValue(sub); + jest + .spyOn(Collection.prototype, "getManifestByIndex") + .mockImplementation(() => { + throw error; + }); + + await expect( + settle( + loadManifestJson(topCollection(), { + manifestUri: TOP_ID, + collectionIndex: 0, + manifestIndex: 5, + }) + ) + ).rejects.toBe(error); + }); + + test("rejects when a child collection loads but no manifestIndex is given", async () => { + const sub = Utils.parseManifest(subCollection()) as Collection; + jest + .spyOn(Collection.prototype, "getCollectionByIndex") + .mockResolvedValue(sub); + + await expect( + settle( + loadManifestJson(topCollection(), { + manifestUri: TOP_ID, + collectionIndex: 0, + }) + ) + ).rejects.toMatchObject({ message: "Manifest index not found" }); + }); + + test("rejects with Manifesto's error when the collection index does not exist", async () => { + await expect( + settle( + loadManifestJson(topCollection(), { + manifestUri: TOP_ID, + collectionIndex: 5, + manifestIndex: 0, + }) + ) + ).rejects.toMatchObject({ message: "Collection index not found" }); + }); + + test("loads the manifest when collectionIndex is given but there are no sub-collections", async () => { + serveJson({ [MANIFEST_ID]: manifest }); + const json = iiif.collection(TOP_ID, { + manifests: [{ id: MANIFEST_ID, label: "Manifest 1" }], + }); + + const helper = await settle( + loadManifestJson(json, { + manifestUri: TOP_ID, + collectionIndex: 0, + manifestIndex: 0, + }) + ); + + expect(helper.manifest!.id).toBe(MANIFEST_ID); + }); + + test("rejects when a collection contains itself", async () => { + serveJson({ [TOP_ID]: () => wrapperCollection(TOP_ID, TOP_ID) }); + + const promise = settle( + loadManifestJson(wrapperCollection(TOP_ID, TOP_ID), { + manifestUri: TOP_ID, + manifestIndex: 0, + }) + ); + + await expect(promise).rejects.toBeInstanceOf(Error); + await expect(promise).rejects.toMatchObject({ + message: "Collection contains itself", + url: TOP_ID, + }); + }); + + test("rejects when collections are nested more than 10 deep", async () => { + const id = (i: number) => `https://example.org/iiif/collection/${i}`; + const byUrl: Record any> = {}; + for (let i = 0; i < 30; i++) { + byUrl[id(i)] = () => wrapperCollection(id(i), id(i + 1)); + } + serveJson(byUrl); + + const promise = settle( + loadManifestJson(wrapperCollection(id(0), id(1)), { + manifestUri: id(0), + manifestIndex: 0, + }) + ); + + await expect(promise).rejects.toBeInstanceOf(Error); + await expect(promise).rejects.toMatchObject({ + message: "Collections are nested too deeply", + }); + }); + + test("rejects with an Error carrying the url when the JSON is not a IIIF resource", async () => { + const promise = settle( + loadManifestJson({ foo: "bar" }, { manifestUri: MANIFEST_ID }) + ); + + await expect(promise).rejects.toBeInstanceOf(Error); + await expect(promise).rejects.toMatchObject({ + message: "Unable to load IIIF resource", + url: MANIFEST_ID, + }); + }); +}); diff --git a/__tests__/externalResource.test.ts b/__tests__/externalResource.test.ts new file mode 100644 index 0000000..31ea3d9 --- /dev/null +++ b/__tests__/externalResource.test.ts @@ -0,0 +1,690 @@ +import { loadManifestJson } from "../src"; +import { ExternalResource } from "../src/ExternalResource"; + +const blAvAuthNew = require("./fixtures/bl-av-auth.json"); + +const INFO_URI = "https://example.org/iiif/image/1/info.json"; +const LOGIN_PROFILE = "http://iiif.io/api/auth/1/login"; +const LOGIN_URI = "https://example.org/login"; +const VIDEO_URI = "https://example.org/video.mp4"; + +// Builds an info.json in each Image API version's shape. Auth 1 services keep +// `@id` in both, as Image API 3 requires for services from older specs. +interface ImageApi { + info(id: string | null, options?: { login?: boolean; service?: any }): any; +} + +const loginService = { + "@context": "http://iiif.io/api/auth/1/context.json", + "@id": LOGIN_URI, + "@type": "AuthCookieService1", + profile: LOGIN_PROFILE, +}; + +const image2: ImageApi = { + info: (id, { login = false, service } = {}) => { + const json: any = { + "@context": "http://iiif.io/api/image/2/context.json", + protocol: "http://iiif.io/api/image", + width: 1000, + height: 800, + profile: ["http://iiif.io/api/image/2/level2.json"], + }; + if (id) json["@id"] = id; + if (service !== undefined) json.service = service; + else if (login) json.service = [loginService]; + return json; + }, +}; + +const image3: ImageApi = { + info: (id, { login = false, service } = {}) => { + const json: any = { + "@context": "http://iiif.io/api/image/3/context.json", + type: "ImageService3", + protocol: "http://iiif.io/api/image", + width: 1000, + height: 800, + profile: "level2", + }; + if (id) json.id = id; + if (service !== undefined) json.service = service; + else if (login) json.service = [loginService]; + return json; + }, +}; + +type MockXhr = { + open: jest.Mock; + send: jest.Mock; + setRequestHeader: jest.Mock; + status: number; + responseText: string; + timeout: number; + withCredentials: boolean; + onload?: () => void; + onerror?: () => void; + ontimeout?: () => void; + onabort?: () => void; +}; + +const originalXhr = window.XMLHttpRequest; + +function installXhr(): MockXhr { + const xhr: MockXhr = { + open: jest.fn(), + send: jest.fn(), + setRequestHeader: jest.fn(), + status: 0, + responseText: "", + timeout: 0, + withCredentials: false, + }; + // @ts-ignore + window.XMLHttpRequest = jest.fn(() => xhr); + return xhr; +} + +// Fails fast instead of hitting the Jest timeout when a promise never settles. +function settle(promise: Promise, ms = 500): Promise { + return Promise.race([ + promise, + new Promise((_, reject) => + setTimeout(() => reject(new Error("promise did not settle")), ms) + ), + ]); +} + +// Completes the next getData() request with an HTTP response. +async function respondWith( + resource: ExternalResource, + status: number, + body: string +): Promise { + const xhr = installXhr(); + const promise = settle(resource.getData()); + xhr.status = status; + xhr.responseText = body; + xhr.onload!(); + return promise; +} + +async function probedResource(): Promise { + const helper = await loadManifestJson(blAvAuthNew, { + manifestUri: blAvAuthNew.id, + }); + return new ExternalResource(helper.getCanvasByIndex(0), { + authApiVersion: 1, + }); +} + +async function infoJsonResource(): Promise { + const resource = await probedResource(); + resource.probeService = null; + resource.dataUri = INFO_URI; + return resource; +} + +describe("ExternalResource.getData error handling", () => { + afterEach(() => { + window.XMLHttpRequest = originalXhr; + }); + + test("rejects with an Error when there is no dataUri", async () => { + const resource = await infoJsonResource(); + resource.dataUri = null; + + const promise = settle(resource.getData()); + + await expect(promise).rejects.toBeInstanceOf(Error); + await expect(promise).rejects.toMatchObject({ + message: "There is no dataUri to fetch", + }); + }); + + test("resolves with an invalid-json error when the probe response is not JSON", async () => { + const resource = await probedResource(); + const probeUri = resource.probeService!.id; + const xhr = installXhr(); + + const promise = settle(resource.getData()); + xhr.status = 200; + xhr.responseText = "Login"; + xhr.onload!(); + + await expect(promise).resolves.toBe(resource); + expect(resource.status).toBe(200); + expect(resource.error).toBeInstanceOf(Error); + expect(resource.error).toMatchObject({ + url: probeUri, + reason: "invalid-json", + }); + }); + + test("resolves with an invalid-json error when info.json is not JSON", async () => { + const resource = await infoJsonResource(); + const xhr = installXhr(); + + const promise = settle(resource.getData()); + xhr.status = 200; + xhr.responseText = "Proxy error"; + xhr.onload!(); + + await expect(promise).resolves.toBe(resource); + expect(resource.status).toBe(200); + expect(resource.error).toBeInstanceOf(Error); + expect(resource.error).toMatchObject({ + url: INFO_URI, + reason: "invalid-json", + }); + }); + + test.each(["null", "42", '"text"'])( + "resolves with an invalid-json error when the probe response is %s", + async (body) => { + const resource = await probedResource(); + const xhr = installXhr(); + + const promise = settle(resource.getData()); + xhr.status = 200; + xhr.responseText = body; + xhr.onload!(); + + await expect(promise).resolves.toBe(resource); + expect(resource.error).toMatchObject({ reason: "invalid-json" }); + } + ); + + test.each(["null", "42", '"text"'])( + "resolves with an invalid-json error when info.json is %s", + async (body) => { + const resource = await infoJsonResource(); + const xhr = installXhr(); + + const promise = settle(resource.getData()); + xhr.status = 200; + xhr.responseText = body; + xhr.onload!(); + + await expect(promise).resolves.toBe(resource); + expect(resource.error).toMatchObject({ reason: "invalid-json" }); + } + ); + + test("resolves with a network error when the request fails with a non-JSON body", async () => { + const resource = await infoJsonResource(); + const xhr = installXhr(); + + const promise = settle(resource.getData()); + xhr.status = 0; + xhr.responseText = "Bad gateway"; + xhr.onerror!(); + + await expect(promise).resolves.toBe(resource); + expect(resource.status).toBe(0); + expect(resource.error).toBeInstanceOf(Error); + expect(resource.error).toMatchObject({ url: INFO_URI, reason: "network" }); + }); + + test("resolves with a network error when the probe request fails", async () => { + const resource = await probedResource(); + const probeUri = resource.probeService!.id; + const xhr = installXhr(); + + const promise = settle(resource.getData()); + xhr.onerror!(); + + await expect(promise).resolves.toBe(resource); + expect(resource.status).toBe(0); + expect(resource.error).toMatchObject({ url: probeUri, reason: "network" }); + }); + + test.each(["timeout", "abort"])( + "resolves with a %s error when the request is cut short", + async (reason) => { + const resource = await infoJsonResource(); + const xhr = installXhr(); + + const promise = settle(resource.getData()); + const handler = reason === "timeout" ? xhr.ontimeout : xhr.onabort; + expect(handler).toBeDefined(); + handler!(); + + await expect(promise).resolves.toBe(resource); + expect(resource.status).toBe(0); + expect(resource.error).toBeInstanceOf(Error); + expect(resource.error).toMatchObject({ url: INFO_URI, reason }); + } + ); + + test.each(["timeout", "abort"])( + "resolves with a %s error when the probe request is cut short", + async (reason) => { + const resource = await probedResource(); + const probeUri = resource.probeService!.id; + const xhr = installXhr(); + + const promise = settle(resource.getData()); + const handler = reason === "timeout" ? xhr.ontimeout : xhr.onabort; + expect(handler).toBeDefined(); + handler!(); + + await expect(promise).resolves.toBe(resource); + expect(resource.status).toBe(0); + expect(resource.error).toMatchObject({ url: probeUri, reason }); + } + ); + + test("does not set a request timeout by default", async () => { + const resource = await infoJsonResource(); + const xhr = installXhr(); + + resource.getData(); + + expect(resource.timeout).toBe(0); + expect(xhr.timeout).toBe(0); + }); + + test("applies the timeout property to the request", async () => { + const resource = await infoJsonResource(); + resource.timeout = 5000; + const xhr = installXhr(); + + resource.getData(); + + expect(xhr.timeout).toBe(5000); + }); + +}); + +// A v3 manifest with one video canvas; `login` adds an Auth 1 login service. +function videoManifest(login: boolean): any { + const body: any = { + id: VIDEO_URI, + type: "Video", + format: "video/mp4", + }; + if (login) { + body.service = [loginService]; + } + return { + "@context": "http://iiif.io/api/presentation/3/context.json", + id: "https://example.org/iiif/manifest/video", + type: "Manifest", + label: { en: ["Video"] }, + items: [ + { + id: "https://example.org/iiif/canvas/1", + type: "Canvas", + width: 640, + height: 480, + duration: 10, + items: [ + { + id: "https://example.org/iiif/canvas/1/page", + type: "AnnotationPage", + items: [ + { + id: "https://example.org/iiif/canvas/1/page/anno", + type: "Annotation", + motivation: "painting", + target: "https://example.org/iiif/canvas/1", + body, + }, + ], + }, + ], + }, + ], + }; +} + +async function videoResource(login: boolean): Promise { + const json = videoManifest(login); + const helper = await loadManifestJson(json, { manifestUri: json.id }); + return new ExternalResource(helper.getCanvasByIndex(0), { + authApiVersion: 1, + }); +} + +describe("ExternalResource.getData successful loading", () => { + const TOKEN = { accessToken: "abc123", expiresIn: 3600 } as any; + + afterEach(() => { + window.XMLHttpRequest = originalXhr; + }); + + test("requests the probe service with a GET", async () => { + const resource = await probedResource(); + const xhr = installXhr(); + + resource.getData(); + + expect(resource.isProbed).toBe(true); + expect(xhr.open).toHaveBeenCalledWith( + "GET", + resource.probeService!.id, + true + ); + expect(xhr.withCredentials).toBe(false); + expect(xhr.setRequestHeader).not.toHaveBeenCalled(); + }); + + test("sends the access token to the probe service", async () => { + const resource = await probedResource(); + const xhr = installXhr(); + + resource.getData(TOKEN); + + expect(xhr.setRequestHeader).toHaveBeenCalledWith( + "Authorization", + "Bearer abc123" + ); + }); + + test("resolves with the probe data when the probe succeeds", async () => { + const resource = await probedResource(); + const body = { contentLocation: resource.dataUri }; + + await expect( + respondWith(resource, 200, JSON.stringify(body)) + ).resolves.toBe(resource); + expect(resource.status).toBe(200); + expect(resource.error).toBeUndefined(); + expect(resource.data).toEqual(body); + }); + + test("requests info.json with a GET", async () => { + const resource = await infoJsonResource(); + const xhr = installXhr(); + + resource.getData(); + + expect(xhr.open).toHaveBeenCalledWith("GET", INFO_URI, true); + expect(xhr.withCredentials).toBe(false); + }); + + test("sends the access token with the info.json request", async () => { + const resource = await infoJsonResource(); + const xhr = installXhr(); + + resource.getData(TOKEN); + + expect(xhr.setRequestHeader).toHaveBeenCalledWith( + "Authorization", + "Bearer abc123" + ); + }); + + test("resolves with 200 without a request when the resource is not access controlled", async () => { + const resource = await videoResource(false); + const xhr = installXhr(); + + await expect(settle(resource.getData())).resolves.toBe(resource); + + expect(resource.dataUri).toBe(VIDEO_URI); + expect(resource.status).toBe(200); + expect(resource.error).toBeUndefined(); + expect(xhr.open).not.toHaveBeenCalled(); + }); + + test("checks an access-controlled resource with a HEAD request", async () => { + const resource = await videoResource(true); + const xhr = installXhr(); + + const promise = settle(resource.getData(TOKEN)); + expect(xhr.open).toHaveBeenCalledWith("HEAD", VIDEO_URI, true); + expect(xhr.setRequestHeader).toHaveBeenCalledWith( + "Authorization", + "Bearer abc123" + ); + xhr.status = 200; + xhr.responseText = ""; + xhr.onload!(); + + await expect(promise).resolves.toBe(resource); + expect(resource.status).toBe(200); + expect(resource.error).toBeUndefined(); + }); +}); + +describe("ExternalResource.getData HTTP status handling", () => { + const HTML = "Unauthorized"; + + afterEach(() => { + window.XMLHttpRequest = originalXhr; + }); + + test.each([ + [401, "HTML", HTML], + [401, "empty", ""], + [403, "HTML", HTML], + [403, "empty", ""], + ])( + "resolves with an http error when the probe returns %i with an %s body", + async (status, _kind, body) => { + const resource = await probedResource(); + const probeUri = resource.probeService!.id; + + await expect(respondWith(resource, status, body)).resolves.toBe( + resource + ); + expect(resource.status).toBe(status); + expect(resource.error).toBeInstanceOf(Error); + expect(resource.error).toMatchObject({ url: probeUri, reason: "http" }); + } + ); + + test.each([401, 403])( + "resolves with an http error and keeps the data when the probe returns %i with a JSON body", + async (status) => { + const resource = await probedResource(); + const probeUri = resource.probeService!.id; + const body = { heading: "Access denied" }; + + await respondWith(resource, status, JSON.stringify(body)); + + expect(resource.status).toBe(status); + expect(resource.error).toMatchObject({ url: probeUri, reason: "http" }); + expect(resource.data).toEqual(body); + } + ); + + test("reports 200 when a successful probe has no contentLocation", async () => { + const resource = await probedResource(); + + await respondWith(resource, 200, JSON.stringify({})); + + expect(resource.status).toBe(200); + expect(resource.error).toBeUndefined(); + }); + + test("reports 200 when a successful probe's contentLocation matches the dataUri", async () => { + const resource = await probedResource(); + + await respondWith( + resource, + 200, + JSON.stringify({ contentLocation: resource.dataUri }) + ); + + expect(resource.status).toBe(200); + }); + + test("reports tiered access (302) when a successful probe's contentLocation differs", async () => { + const resource = await probedResource(); + + await respondWith( + resource, + 200, + JSON.stringify({ contentLocation: "https://example.org/lower-tier.mp4" }) + ); + + expect(resource.status).toBe(302); + }); + + test.each([401, 403])( + "resolves with an http error when info.json returns %i with an HTML body", + async (status) => { + const resource = await infoJsonResource(); + + await respondWith(resource, status, HTML); + + expect(resource.status).toBe(status); + expect(resource.error).toMatchObject({ url: INFO_URI, reason: "http" }); + } + ); + + test("resolves with an http error when info.json returns 401 with an empty body", async () => { + const resource = await infoJsonResource(); + + await respondWith(resource, 401, ""); + + expect(resource.status).toBe(401); + expect(resource.error).toMatchObject({ url: INFO_URI, reason: "http" }); + }); +}); + +describe.each([ + ["Image API 2", image2], + ["Image API 3", image3], +])("ExternalResource.getData info.json handling (%s)", (_name, imageApi) => { + const IMAGE_URI = INFO_URI.replace("/info.json", ""); + + afterEach(() => { + window.XMLHttpRequest = originalXhr; + }); + + async function respond( + resource: ExternalResource, + body: any + ): Promise { + const xhr = installXhr(); + const promise = settle(resource.getData()); + xhr.status = 200; + xhr.responseText = JSON.stringify(body); + xhr.onload!(); + return promise; + } + + test("resolves with the info.json data and dimensions", async () => { + const resource = await infoJsonResource(); + const info = imageApi.info(IMAGE_URI); + + await expect(respond(resource, info)).resolves.toBe(resource); + expect(resource.status).toBe(200); + expect(resource.error).toBeUndefined(); + expect(resource.data).toEqual(info); + expect(resource.width).toBe(1000); + expect(resource.height).toBe(800); + }); + + test("finds the login service", async () => { + const resource = await infoJsonResource(); + + await respond(resource, imageApi.info(IMAGE_URI, { login: true })); + + expect(resource.loginService).not.toBe(null); + expect(resource.loginService!.id).toBe(LOGIN_URI); + }); + + test("does not report tiered access when the id matches the request", async () => { + const resource = await infoJsonResource(); + + await respond(resource, imageApi.info(IMAGE_URI, { login: true })); + + expect(resource.status).toBe(200); + }); + + test("does not report tiered access when the id ends in /info.json", async () => { + const resource = await infoJsonResource(); + + await respond(resource, imageApi.info(INFO_URI, { login: true })); + + expect(resource.status).toBe(200); + }); + + test("reports tiered access (302) when the id differs and there is a login service", async () => { + const resource = await infoJsonResource(); + + await respond( + resource, + imageApi.info("https://example.org/iiif/image/1-lower-tier", { + login: true, + }) + ); + + expect(resource.status).toBe(302); + }); + + test("does not report tiered access when the id differs but there is no login service", async () => { + const resource = await infoJsonResource(); + + await respond( + resource, + imageApi.info("https://example.org/iiif/image/1-lower-tier") + ); + + expect(resource.status).toBe(200); + }); + + test("does not report tiered access when info.json has no id", async () => { + const resource = await infoJsonResource(); + + await respond(resource, imageApi.info(null, { login: true })); + + expect(resource.loginService).not.toBe(null); + expect(resource.status).toBe(200); + }); + + test("resolves with an http error and still finds the login service when info.json returns 401", async () => { + const resource = await infoJsonResource(); + const info = imageApi.info(IMAGE_URI, { login: true }); + + await respondWith(resource, 401, JSON.stringify(info)); + + expect(resource.status).toBe(401); + expect(resource.error).toMatchObject({ url: INFO_URI, reason: "http" }); + expect(resource.loginService!.id).toBe(LOGIN_URI); + expect(resource.data).toEqual(info); + }); + + test("resolves with an http error when a 401 info.json's services cannot be read", async () => { + const resource = await infoJsonResource(); + + await respondWith( + resource, + 401, + JSON.stringify(imageApi.info(IMAGE_URI, { service: "login" })) + ); + + expect(resource.status).toBe(401); + expect(resource.error).toMatchObject({ url: INFO_URI, reason: "http" }); + }); + + test("resolves with an invalid-json error when info.json services cannot be read", async () => { + const resource = await infoJsonResource(); + + await expect( + respond(resource, imageApi.info(IMAGE_URI, { service: "login" })) + ).resolves.toBe(resource); + expect(resource.status).toBe(200); + expect(resource.error).toMatchObject({ + url: INFO_URI, + reason: "invalid-json", + }); + }); + + test("clears the previous error when a retry succeeds", async () => { + const resource = await infoJsonResource(); + const failing = installXhr(); + const first = settle(resource.getData()); + failing.onerror!(); + await first; + + await respond(resource, imageApi.info(IMAGE_URI)); + + expect(resource.status).toBe(200); + expect(resource.error).toBeUndefined(); + }); +}); diff --git a/src/Bootstrapper.ts b/src/Bootstrapper.ts index a029acf..7d57ef6 100644 --- a/src/Bootstrapper.ts +++ b/src/Bootstrapper.ts @@ -9,8 +9,17 @@ import { Utils, } from "manifesto.js"; +const MAX_COLLECTION_DEPTH = 10; + +function loadError(message: string, url?: string): Error { + const error: any = new Error(message); + error.url = url; + return error; +} + export class Bootstrapper { private _options: IManifoldOptions; + private _visited: Set = new Set(); constructor(options: IManifoldOptions) { this._options = options; @@ -61,6 +70,10 @@ export class Bootstrapper { resolve: (helper: Helper) => void, reject: (error: any) => void ): void { + if (bootstrapper._options.manifestUri) { + bootstrapper._visited.add(bootstrapper._options.manifestUri); + } + const iiifResource: IIIFResource | null = Utils.parseManifest(json, < IManifestoOptions >{ @@ -101,10 +114,6 @@ export class Bootstrapper { (iiifResource) .getCollectionByIndex(collectionIndex) .then((collection: Collection) => { - if (!collection) { - reject("Collection index not found"); - } - // Special case: we're trying to load the first manifest of the // specified collection, but the collection has no manifests but does have // subcollections. Thus, we should dive in until we find something @@ -114,19 +123,36 @@ export class Bootstrapper { manifestIndex === 0 && collection.getTotalCollections() > 0 ) { + if (bootstrapper._visited.has(collection.id)) { + reject( + loadError("Collection contains itself", collection.id) + ); + return; + } + if (bootstrapper._visited.size > MAX_COLLECTION_DEPTH) { + reject( + loadError( + "Collections are nested too deeply", + collection.id + ) + ); + return; + } bootstrapper._options.collectionIndex = 0; bootstrapper._options.manifestUri = collection.id; bootstrapper.bootstrap(resolve, reject); - } else if (manifestIndex !== undefined) { - collection - .getManifestByIndex(manifestIndex) - .then((manifest: Manifest) => { - bootstrapper._options.manifest = manifest; - const helper: Helper = new Helper(bootstrapper._options); - resolve(helper); - }); + return; } - }); + + return collection + .getManifestByIndex(manifestIndex as number) + .then((manifest: Manifest) => { + bootstrapper._options.manifest = manifest; + const helper: Helper = new Helper(bootstrapper._options); + resolve(helper); + }); + }) + .catch(reject); } else { (iiifResource) .getManifestByIndex(bootstrapper._options.manifestIndex as number) @@ -134,7 +160,8 @@ export class Bootstrapper { bootstrapper._options.manifest = manifest; const helper: Helper = new Helper(bootstrapper._options); resolve(helper); - }); + }) + .catch(reject); } } else { bootstrapper._options.manifest = iiifResource; @@ -142,7 +169,12 @@ export class Bootstrapper { resolve(helper); } } else { - console.error("Unable to load IIIF resource"); + reject( + loadError( + "Unable to load IIIF resource", + bootstrapper._options.manifestUri + ) + ); } } } diff --git a/src/ExternalResource.ts b/src/ExternalResource.ts index 145a614..a1e1b66 100644 --- a/src/ExternalResource.ts +++ b/src/ExternalResource.ts @@ -12,6 +12,25 @@ import { Utils, } from "manifesto.js"; +// Returns null for invalid JSON and for JSON that isn't an object (e.g. `null`, `42`). +function parseJsonObject(text: string): any | null { + try { + const data = JSON.parse(text); + return data !== null && typeof data === "object" ? data : null; + } catch { + return null; + } +} + +function isSuccess(status: number): boolean { + return status >= 200 && status < 300; +} + +// An unusable body on an HTTP error is reported as the HTTP error, not bad JSON. +function unusableBodyReason(status: number): "invalid-json" | "http" { + return isSuccess(status) ? "invalid-json" : "http"; +} + export class ExternalResource implements IExternalResource { public authAPIVersion: number; public authHoldingPage: any = null; @@ -30,6 +49,7 @@ export class ExternalResource implements IExternalResource { public probeService: Service | null = null; public restrictedService: Service | null = null; public status: number; + public timeout: number = 0; public tokenService: Service | null = null; public width: number; @@ -295,6 +315,35 @@ export class ExternalResource implements IExternalResource { } } + private _resolveWithError( + xhr: XMLHttpRequest, + url: string, + reason: "invalid-json" | "http" | "network" | "timeout" | "abort", + resolve: (resource: ExternalResource) => void + ): void { + this._setError(xhr, url, reason); + resolve(this); + } + + private _setError( + xhr: XMLHttpRequest, + url: string, + reason: "invalid-json" | "http" | "network" | "timeout" | "abort" + ): void { + const messages = { + "invalid-json": "Invalid JSON response", + http: "HTTP error", + network: "Network error", + timeout: "Request timed out", + abort: "Request aborted", + }; + const error: any = new Error(messages[reason]); + error.url = url; + error.reason = reason; + this.status = xhr.status; + this.error = error; + } + public isAccessControlled(): boolean { if ( this.clickThroughService || @@ -319,10 +368,11 @@ export class ExternalResource implements IExternalResource { public getData(accessToken?: IAccessToken): Promise { const that = this; that.data = {}; + that.error = undefined; return new Promise((resolve, reject) => { if (!that.dataUri) { - reject("There is no dataUri to fetch"); + reject(new Error("There is no dataUri to fetch")); return; } @@ -332,41 +382,12 @@ export class ExternalResource implements IExternalResource { if (that.probeService) { that.isProbed = true; - // leaving this in for reference until the XHR version is fully tested - // $.ajax({ - // url: that.probeService.id, - // type: 'GET', - // dataType: 'json', - // beforeSend: (xhr) => { - // if (accessToken) { - // xhr.setRequestHeader("Authorization", "Bearer " + accessToken.accessToken); - // } - // } - // }).done((data: any) => { - - // let contentLocation: string = unescape(data.contentLocation); - - // if (contentLocation !== that.dataUri) { - // that.status = HTTPStatusCode.MOVED_TEMPORARILY; - // } else { - // that.status = HTTPStatusCode.OK; - // } - - // resolve(that); - - // }).fail((error) => { - - // that.status = error.status; - // that.error = error; - // resolve(that); - - // }); - - // xhr implementation + const probeUri: string = that.probeService.id; const xhr: XMLHttpRequest = new XMLHttpRequest(); - xhr.open("GET", that.probeService.id, true); + xhr.open("GET", probeUri, true); // This has been disabled as the request should use the access token. xhr.withCredentials = false; + xhr.timeout = that.timeout; if (accessToken) { xhr.setRequestHeader( @@ -376,12 +397,26 @@ export class ExternalResource implements IExternalResource { } xhr.onload = () => { - const data = JSON.parse(xhr.responseText); - const contentLocation: string = unescape(data.contentLocation); + const data = parseJsonObject(xhr.responseText); + if (!data) { + that._resolveWithError( + xhr, + probeUri, + unusableBodyReason(xhr.status), + resolve + ); + return; + } that.status = xhr.status; - if (contentLocation !== that.dataUri) { + if (!isSuccess(xhr.status)) { + that._setError(xhr, probeUri, "http"); + } else if ( + // Only a successful probe can point at a lower tier of tiered access. + data.contentLocation && + unescape(data.contentLocation) !== that.dataUri + ) { that.status = HTTPStatusCode.MOVED_TEMPORARILY; } @@ -390,10 +425,12 @@ export class ExternalResource implements IExternalResource { resolve(that); }; - xhr.onerror = () => { - that.status = xhr.status; - resolve(that); - }; + xhr.onerror = () => + that._resolveWithError(xhr, probeUri, "network", resolve); + xhr.ontimeout = () => + that._resolveWithError(xhr, probeUri, "timeout", resolve); + xhr.onabort = () => + that._resolveWithError(xhr, probeUri, "abort", resolve); xhr.send(); } else { @@ -417,65 +454,11 @@ export class ExternalResource implements IExternalResource { type = "HEAD"; } - // leaving this in for reference until the XHR version is fully tested - // $.ajax({ - // url: that.dataUri, - // type: type, - // dataType: 'json', - // beforeSend: (xhr) => { - // if (accessToken) { - // xhr.setRequestHeader("Authorization", "Bearer " + accessToken.accessToken); - // } - // } - // }).done((data: any) => { - - // // if it's a resource without an info.json - // // todo: if resource doesn't have a @profile - // if (!data) { - // that.status = HTTPStatusCode.OK; - // resolve(that); - // } else { - // let uri: string = unescape(data['@id']); - - // that.data = data; - // that._parseAuthServices(that.data); - - // // remove trailing /info.json - // if (uri.endsWith('/info.json')){ - // uri = uri.substr(0, uri.lastIndexOf('/')); - // } - - // let dataUri: string | null = that.dataUri; - - // if (dataUri && dataUri.endsWith('/info.json')){ - // dataUri = dataUri.substr(0, dataUri.lastIndexOf('/')); - // } - - // // if the request was redirected to a degraded version and there's a login service to get the full quality version - // if (uri !== dataUri && that.loginService) { - // that.status = HTTPStatusCode.MOVED_TEMPORARILY; - // } else { - // that.status = HTTPStatusCode.OK; - // } - - // resolve(that); - // } - - // }).fail((error) => { - - // that.status = error.status; - // that.error = error; - // if (error.responseJSON){ - // that._parseAuthServices(error.responseJSON); - // } - // resolve(that); - - // }); - - // xhr implementation + const dataUri: string = that.dataUri; const xhr: XMLHttpRequest = new XMLHttpRequest(); - xhr.open(type, that.dataUri, true); + xhr.open(type, dataUri, true); xhr.withCredentials = false; + xhr.timeout = that.timeout; if (accessToken) { xhr.setRequestHeader( "Authorization", @@ -488,31 +471,55 @@ export class ExternalResource implements IExternalResource { // todo: if resource doesn't have a @profile if (!xhr.responseText) { that.status = xhr.status || HTTPStatusCode.OK; + if (!isSuccess(that.status)) { + that._setError(xhr, dataUri, "http"); + } resolve(that); } else { - const data = JSON.parse(xhr.responseText); + const data = parseJsonObject(xhr.responseText); + if (!data) { + that._resolveWithError( + xhr, + dataUri, + unusableBodyReason(xhr.status), + resolve + ); + return; + } const status = xhr.status; - let uri: string = unescape(data["@id"] || data.id); + const id: string | undefined = data["@id"] || data.id; + let uri: string | null = id ? unescape(id) : null; that.data = data; - that._parseAuthServices(that.data); + try { + that._parseAuthServices(that.data); + } catch { + that._resolveWithError( + xhr, + dataUri, + unusableBodyReason(status), + resolve + ); + return; + } that._parseDescriptorDimensions(that.data); // remove trailing /info.json - if (uri.endsWith("/info.json")) { + if (uri && uri.endsWith("/info.json")) { uri = uri.substr(0, uri.lastIndexOf("/")); } - let dataUri: string | null = that.dataUri; + let baseUri: string = dataUri; - if (dataUri && dataUri.endsWith("/info.json")) { - dataUri = dataUri.substr(0, dataUri.lastIndexOf("/")); + if (baseUri.endsWith("/info.json")) { + baseUri = baseUri.substr(0, baseUri.lastIndexOf("/")); } - // if the request was redirected to a degraded version and there's a login service to get the full quality version + // if the request was redirected to a lower tier of tiered access and there's a login service to get the full version if ( status === HTTPStatusCode.OK && - uri !== dataUri && + uri !== null && + uri !== baseUri && (that.loginService || that.kioskService) ) { that.status = HTTPStatusCode.MOVED_TEMPORARILY; @@ -520,17 +527,29 @@ export class ExternalResource implements IExternalResource { that.status = status; } + if (!isSuccess(status)) { + that._setError(xhr, dataUri, "http"); + } + resolve(that); } }; xhr.onerror = () => { - that.status = xhr.status; - if (xhr.responseText) { - that._parseAuthServices(JSON.parse(xhr.responseText)); + const data = parseJsonObject(xhr.responseText); + if (data) { + try { + that._parseAuthServices(data); + } catch { + // Auth services on an error body are optional. + } } - resolve(that); + that._resolveWithError(xhr, dataUri, "network", resolve); }; + xhr.ontimeout = () => + that._resolveWithError(xhr, dataUri, "timeout", resolve); + xhr.onabort = () => + that._resolveWithError(xhr, dataUri, "abort", resolve); xhr.send(); }