@geolonia/embed 6.0.0 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,8 +13,3 @@ export declare function parseScriptTagApiKey(doc?: Document): {
13
13
  apiKey: string;
14
14
  stage: string;
15
15
  } | null;
16
- /**
17
- * Detect whether the embed is allowed to render in the current (possibly
18
- * iframed) context. Embed-specific: not provided by maps-core.
19
- */
20
- export declare function checkPermission(): boolean;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "6.0.0";
1
+ export declare const VERSION = "6.0.1";
@@ -1,35 +1,50 @@
1
1
  import { test, expect } from '@playwright/test';
2
- import { TEST_URL, mockGeoloniaTiles, waitForMapLoad, hasMapInstance } from './helper';
2
+ import { BASE_URL, LOAD_TIMEOUT, TEST_URL, mockGeoloniaTiles, waitForMapLoad, hasMapInstance } from './helper';
3
3
 
4
- // embed (wrapper) 固有: checkPermission() による iframe 埋め込み制限。
5
- // maps-core にこのゲートは無い。
6
- //
7
- // 拒否される側 (iframe + API key 無し + 非特例 origin) の E2E 再現は難しいため skip し、
8
- // ここでは「非 iframe では拒否されず描画される」= 許可側の経路のみを守る。
9
- test.describe('iframe 許可チェック / checkPermission (wrapper-only)', () => {
10
- test('非 iframe では拒否されず地図が描画される (iframe 拒否メッセージが出ない)', async ({ page }) => {
4
+ // 子フレーム用の別オリジン。リクエストは route で dev サーバーへ転送する
5
+ const OTHER_ORIGIN = 'http://embed-iframe.test';
6
+
7
+ // embed (wrapper) 固有: class="geolonia" の要素は、iframe の中でも API キーの有無に関係なく地図になる。
8
+ test.describe('iframe の中での描画 (wrapper-only)', () => {
9
+ test('非 iframe で地図が描画される', async ({ page }) => {
10
+ await mockGeoloniaTiles(page);
11
+ await page.goto(`${TEST_URL}/basic.html`);
12
+ await waitForMapLoad(page);
13
+
14
+ expect(await hasMapInstance(page, '#map')).toBe(true);
15
+ });
16
+
17
+ test('API キー無しの embed を別オリジンの iframe に入れても地図が描画される', async ({ page }) => {
11
18
  const consoleErrors: string[] = [];
12
19
  page.on('console', (msg) => {
13
20
  if (msg.type() === 'error') consoleErrors.push(msg.text());
14
21
  });
15
22
 
16
23
  await mockGeoloniaTiles(page);
17
- await page.goto(`${TEST_URL}/basic.html`);
18
- await waitForMapLoad(page);
24
+ await page.route(`${OTHER_ORIGIN}/**`, async (route) => {
25
+ const url = route.request().url().replace(OTHER_ORIGIN, BASE_URL);
26
+ await route.fulfill({ response: await route.fetch({ url }) });
27
+ });
28
+ await page.goto(`${TEST_URL}/iframe.html?origin=${encodeURIComponent(OTHER_ORIGIN)}`);
19
29
 
20
- // 描画されている = checkPermission が許可した
21
- expect(await hasMapInstance(page, '#map')).toBe(true);
30
+ const frame = page.frameLocator('#frame');
31
+ await expect(frame.locator('#map canvas')).toBeVisible({ timeout: 10000 });
22
32
 
23
- // iframe 拒否のメッセージは出ていないこと
33
+ const child = page.frames().find((f) => f.url().endsWith('/e2e/no-api-key.html'));
34
+ expect(child).toBeDefined();
35
+ // waitForStyleLoad と同じ条件で、子フレームの地図がスタイルまで読み終えるのを待つ
36
+ await child!.waitForFunction(
37
+ () => {
38
+ const map = (document.querySelector('#map') as any)?.geoloniaMap;
39
+ return !!(map && map.loaded() && map.isStyleLoaded());
40
+ },
41
+ undefined,
42
+ { timeout: LOAD_TIMEOUT },
43
+ );
44
+ expect(new URL(child!.url()).origin).toBe(OTHER_ORIGIN);
45
+ expect(
46
+ await child!.evaluate(() => !!(document.querySelector('#map') as any)?.geoloniaMap),
47
+ ).toBe(true);
24
48
  expect(consoleErrors.some((t) => t.includes("can't display our map in iframe"))).toBe(false);
25
49
  });
26
-
27
- // 拒否ケース (iframe + API key 無し → console.error) は E2E では再現が難しい:
28
- // - ローカルでは特例 origin (codepen 等) + referrer を満たせない
29
- // - child frame の console は親フレームから capture しにくい
30
- // このゲートは checkPermission() のユニットテスト (window.self/parent/location をモック) で
31
- // 検証する方が現実的。E2E では skip する (silent に落とさず明示)。
32
- test.skip('iframe + API key 無し → 拒否される (ユニットテストで担保)', async () => {
33
- // intentionally skipped — see comment above
34
- });
35
50
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geolonia/embed",
3
- "version": "6.0.0",
3
+ "version": "6.0.1",
4
4
  "description": "Geolonia embed JS API",
5
5
  "main": "dist/embed.js",
6
6
  "types": "dist/embed.d.ts",
package/src/lib/render.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import 'maplibre-gl/dist/maplibre-gl.css';
2
2
  import '../style.css';
3
3
  import { GeoloniaMap, keyring } from '@geolonia/maps-core';
4
- import { checkPermission, parseScriptTagApiKey } from './util';
4
+ import { parseScriptTagApiKey } from './util';
5
5
  import parseAtts, { attsToOptions } from './parse-atts';
6
6
  import type {
7
7
  EmbedAttributes,
@@ -39,8 +39,8 @@ export const renderGeoloniaMap = () => {
39
39
 
40
40
  // Backward compat: maps-core's keyring no longer scans the DOM, but legacy
41
41
  // embeds set the key only on the container via `data-key`. Seed the keyring
42
- // from the first container-side key so the iframe permission check below
43
- // (and Geolonia-style validation) sees the same effective key as before.
42
+ // from the first container-side key so Geolonia-style validation sees the
43
+ // same effective key as before.
44
44
  // Per-container `data-key` still flows through parseAtts → attsToOptions.
45
45
  if (!keyring.apiKey) {
46
46
  const keyed = document.querySelector<HTMLElement>('.geolonia[data-key]');
@@ -50,123 +50,116 @@ export const renderGeoloniaMap = () => {
50
50
  }
51
51
  }
52
52
 
53
- if (checkPermission()) {
54
- let isDOMContentLoaded = false;
55
- const isRemoved = Symbol('map-is-removed');
56
-
57
- // 手動で remove された地図に印を付けるための symbol プロパティ。
58
- type RemovableMap = GeoloniaMap & { [isRemoved]?: boolean };
59
-
60
- const alreadyRenderedMaps: {
61
- map: RemovableMap;
62
- target: HTMLElement;
63
- atts: EmbedAttributes;
64
- }[] = [];
65
-
66
- /**
67
- *
68
- * @param {HTMLElement} target
69
- */
70
- const renderSingleMap = (target: HTMLElement) => {
71
- const atts = parseAtts(target);
72
-
73
- // Dedup: if this container was already initialised (e.g. constructed
74
- // programmatically before the lazy observer fired), reuse the instance.
75
- // Must happen before extractPopupContent(), otherwise we'd wipe the
76
- // already-rendered map DOM out of the container.
77
- let map: RemovableMap | undefined = target.geoloniaMap;
78
- if (!map) {
79
- // Grab inline popup content before maps-core clears/renders the container.
80
- extractPopupContent(target);
81
- map = new GeoloniaMap(attsToOptions(target, atts));
82
- }
83
-
84
- // detect if the map removed manually
85
- map.on('remove', () => {
86
- map[isRemoved] = true;
87
- });
88
-
89
- // remove map instance automatically if the container removed.
90
- // prevent memory leak
91
- const observer = new MutationObserver((mutationRecords) => {
92
- const removed = mutationRecords.some((record) =>
93
- [...record.removedNodes].some((node) => node === target),
94
- );
95
- if (removed && !map[isRemoved]) {
96
- map.remove();
97
- }
98
- });
99
- // 親が無いコンテナは DOM から外されることがないので監視しない。
100
- if (target.parentNode) {
101
- observer.observe(target.parentNode, { childList: true });
102
- }
53
+ let isDOMContentLoaded = false;
54
+ const isRemoved = Symbol('map-is-removed');
55
+
56
+ // 手動で remove された地図に印を付けるための symbol プロパティ。
57
+ type RemovableMap = GeoloniaMap & { [isRemoved]?: boolean };
58
+
59
+ const alreadyRenderedMaps: {
60
+ map: RemovableMap;
61
+ target: HTMLElement;
62
+ atts: EmbedAttributes;
63
+ }[] = [];
64
+
65
+ /**
66
+ *
67
+ * @param {HTMLElement} target
68
+ */
69
+ const renderSingleMap = (target: HTMLElement) => {
70
+ const atts = parseAtts(target);
71
+
72
+ // Dedup: if this container was already initialised (e.g. constructed
73
+ // programmatically before the lazy observer fired), reuse the instance.
74
+ // Must happen before extractPopupContent(), otherwise we'd wipe the
75
+ // already-rendered map DOM out of the container.
76
+ let map: RemovableMap | undefined = target.geoloniaMap;
77
+ if (!map) {
78
+ // Grab inline popup content before maps-core clears/renders the container.
79
+ extractPopupContent(target);
80
+ map = new GeoloniaMap(attsToOptions(target, atts));
81
+ }
103
82
 
104
- // plugin
105
- if (isDOMContentLoaded && !map[isRemoved]) {
106
- plugins.forEach((plugin) => plugin(map, target, atts));
107
- } else {
108
- alreadyRenderedMaps.push({ map, target: target, atts });
109
- }
110
- };
111
-
112
- document.addEventListener('DOMContentLoaded', () => {
113
- isDOMContentLoaded = true;
114
- alreadyRenderedMaps.forEach(({ map, target, atts }) => {
115
- if (!map[isRemoved]) {
116
- plugins.forEach((plugin) => plugin(map, target, atts));
117
- }
118
- });
119
- // clear
120
- alreadyRenderedMaps.splice(0, alreadyRenderedMaps.length);
83
+ // detect if the map removed manually
84
+ map.on('remove', () => {
85
+ map[isRemoved] = true;
121
86
  });
122
87
 
123
- const observer = new IntersectionObserver((entries) => {
124
- entries.forEach((item) => {
125
- if (!item.isIntersecting) {
126
- return;
127
- }
128
- try {
129
- // 監視対象は下の querySelectorAll<HTMLElement> で集めた要素に限られる。
130
- renderSingleMap(item.target as HTMLElement);
131
- } catch (e) {
132
- // Not throw error because, following maps will not be rendered.
133
- console.error('[Geolonia] Failed to initialize map', e); // eslint-disable-line
134
- }
135
- observer.unobserve(item.target);
136
- });
88
+ // remove map instance automatically if the container removed.
89
+ // prevent memory leak
90
+ const observer = new MutationObserver((mutationRecords) => {
91
+ const removed = mutationRecords.some((record) =>
92
+ [...record.removedNodes].some((node) => node === target),
93
+ );
94
+ if (removed && !map[isRemoved]) {
95
+ map.remove();
96
+ }
137
97
  });
98
+ // 親が無いコンテナは DOM から外されることがないので監視しない。
99
+ if (target.parentNode) {
100
+ observer.observe(target.parentNode, { childList: true });
101
+ }
138
102
 
139
- const containers = document.querySelectorAll<HTMLElement>(
140
- '.geolonia[data-lazy-loading="off"]',
141
- );
142
- const lazyContainers = document.querySelectorAll<HTMLElement>(
143
- '.geolonia:not([data-lazy-loading="off"])',
144
- );
145
-
146
- // This is required for correct initialization! Don't delete!
147
- if (keyring.isGeoloniaStyle && !keyring.apiKey) {
148
- console.error('[Geolonia] Missing API key.'); // eslint-disable-line
103
+ // plugin
104
+ if (isDOMContentLoaded && !map[isRemoved]) {
105
+ plugins.forEach((plugin) => plugin(map, target, atts));
106
+ } else {
107
+ alreadyRenderedMaps.push({ map, target: target, atts });
149
108
  }
109
+ };
150
110
 
151
- // render Map immediately
152
- for (let i = 0; i < containers.length; i++) {
111
+ document.addEventListener('DOMContentLoaded', () => {
112
+ isDOMContentLoaded = true;
113
+ alreadyRenderedMaps.forEach(({ map, target, atts }) => {
114
+ if (!map[isRemoved]) {
115
+ plugins.forEach((plugin) => plugin(map, target, atts));
116
+ }
117
+ });
118
+ // clear
119
+ alreadyRenderedMaps.splice(0, alreadyRenderedMaps.length);
120
+ });
121
+
122
+ const observer = new IntersectionObserver((entries) => {
123
+ entries.forEach((item) => {
124
+ if (!item.isIntersecting) {
125
+ return;
126
+ }
153
127
  try {
154
- renderSingleMap(containers[i]);
128
+ // 監視対象は下の querySelectorAll<HTMLElement> で集めた要素に限られる。
129
+ renderSingleMap(item.target as HTMLElement);
155
130
  } catch (e) {
156
131
  // Not throw error because, following maps will not be rendered.
157
132
  console.error('[Geolonia] Failed to initialize map', e); // eslint-disable-line
158
133
  }
159
- }
134
+ observer.unobserve(item.target);
135
+ });
136
+ });
137
+
138
+ const containers = document.querySelectorAll<HTMLElement>(
139
+ '.geolonia[data-lazy-loading="off"]',
140
+ );
141
+ const lazyContainers = document.querySelectorAll<HTMLElement>(
142
+ '.geolonia:not([data-lazy-loading="off"])',
143
+ );
144
+
145
+ // This is required for correct initialization! Don't delete!
146
+ if (keyring.isGeoloniaStyle && !keyring.apiKey) {
147
+ console.error('[Geolonia] Missing API key.'); // eslint-disable-line
148
+ }
160
149
 
161
- // set intersection observer
162
- for (let i = 0; i < lazyContainers.length; i++) {
163
- observer.observe(lazyContainers[i]);
150
+ // render Map immediately
151
+ for (let i = 0; i < containers.length; i++) {
152
+ try {
153
+ renderSingleMap(containers[i]);
154
+ } catch (e) {
155
+ // Not throw error because, following maps will not be rendered.
156
+ console.error('[Geolonia] Failed to initialize map', e); // eslint-disable-line
164
157
  }
165
- } else {
166
- /* eslint-disable-next-line no-console */
167
- console.error(
168
- "[Geolonia] We are very sorry, but we can't display our map in iframe.",
169
- );
158
+ }
159
+
160
+ // set intersection observer
161
+ for (let i = 0; i < lazyContainers.length; i++) {
162
+ observer.observe(lazyContainers[i]);
170
163
  }
171
164
  };
172
165
 
package/src/lib/util.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- import { keyring } from '@geolonia/maps-core';
4
-
5
3
  /**
6
4
  * Parse the Geolonia API key from the `?geolonia-api-key=` query of the
7
5
  * embed `<script>` tag (backward compatibility).
@@ -41,77 +39,3 @@ export function parseScriptTagApiKey(
41
39
 
42
40
  return null;
43
41
  }
44
-
45
- /**
46
- * Detect whether the embed is allowed to render in the current (possibly
47
- * iframed) context. Embed-specific: not provided by maps-core.
48
- */
49
- export function checkPermission() {
50
- // It looks that isn't iFrame, so returns true.
51
- if (window.self === window.parent) {
52
- return true;
53
- }
54
-
55
- // Always returns true if API key is loaded.
56
- if (keyring.apiKey) {
57
- return true;
58
- }
59
-
60
- /**
61
- * For the https://codepen.io/
62
- * iFrame による Codepen の地図の認可外のサイトへの埋め込みを許可しない
63
- */
64
- if (
65
- window.self.location.origin === 'https://cdpn.io' ||
66
- window.self.location.origin === 'https://codepen.io'
67
- ) {
68
- if (
69
- window.self !== window.parent &&
70
- window.document.referrer.indexOf('https://codepen.io') === 0
71
- ) {
72
- return true;
73
- }
74
- }
75
-
76
- /**
77
- * For the https://jsfiddle.net/
78
- */
79
- if (window.self.location.origin === 'https://fiddle.jshell.net') {
80
- if (
81
- window.self !== window.parent &&
82
- window.document.referrer.indexOf('https://jsfiddle.net') === 0
83
- ) {
84
- return true;
85
- }
86
- }
87
-
88
- /**
89
- * For the https://codesandbox.io/
90
- *
91
- * Note:
92
- * codesandbox.io has two preview window, one is in right sidebar with iframe and
93
- * another one is in new window.
94
- */
95
- if (window.self.location.origin.match(/csb\.app$/)) {
96
- if (
97
- window.self !== window.parent &&
98
- window.document.referrer.indexOf('https://codesandbox.io') === 0
99
- ) {
100
- return true;
101
- }
102
- }
103
-
104
- /**
105
- * `window.parent` will be blocked if same origin policy is activated.
106
- * So, it should be caught.
107
- */
108
- try {
109
- if (window.self.location.origin === window.top?.location.origin) {
110
- return true;
111
- }
112
- } catch {
113
- return false;
114
- }
115
-
116
- return false;
117
- }
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = '6.0.0';
1
+ export const VERSION = '6.0.1';