-
Notifications
You must be signed in to change notification settings - Fork 3
chore: update-readme #496
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
chore: update-readme #496
Conversation
|
WalkthroughComprehensive README documentation updates across 11 packages, introducing refreshed API references with Effect-TS patterns, modernized package namespaces, consolidated installation sections, and new public method signatures alongside practical usage examples and monorepo-aligned build instructions. Changes
Sequence Diagram(s)No sequence diagram generated; changes are documentation-only across heterogeneous packages without a unifying control-flow modification. Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes
Areas requiring attention:
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
Tip 📝 Customizable high-level summaries are now available in beta!You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.
Example instruction:
Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
View your CI Pipeline Execution ↗ for commit 98d65ca
☁️ Nx Cloud last updated this comment at |
@forgerock/davinci-client
@forgerock/oidc-client
@forgerock/protect
@forgerock/sdk-types
@forgerock/sdk-utilities
@forgerock/iframe-manager
@forgerock/sdk-logger
@forgerock/sdk-oidc
@forgerock/sdk-request-middleware
@forgerock/storage
commit: |
Codecov Report✅ All modified and coverable lines are covered by tests. ❌ Your project status has failed because the head coverage (18.79%) is below the target coverage (40.00%). You can increase the head coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## main #496 +/- ##
=======================================
Coverage 18.79% 18.79%
=======================================
Files 140 140
Lines 27640 27640
Branches 980 980
=======================================
Hits 5195 5195
Misses 22445 22445 🚀 New features to boost your workflow:
|
|
Deployed 541409a to https://ForgeRock.github.io/ping-javascript-sdk/pr-496/541409a1eacfde09ea0efc15de0bf92f507bd8ab branch gh-pages in ForgeRock/ping-javascript-sdk |
📦 Bundle Size Analysis📦 Bundle Size Analysis🚨 Significant Changes🔻 @forgerock/journey-client - 0.0 KB (-82.4 KB, -100.0%) 📊 Minor Changes📈 @forgerock/journey-client - 82.4 KB (+0.0 KB) ➖ No Changes➖ @forgerock/device-client - 9.2 KB 13 packages analyzed • Baseline from latest Legend🆕 New package ℹ️ How bundle sizes are calculated
🔄 Updated automatically on each push to this PR |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/sdk-effects/iframe-manager/README.md (1)
32-58: Fix critical error handling mismatch in iframe-manager.effects.ts.The implementation has a critical behavior mismatch with the documented API. When error parameters are detected in the redirect URL, the code incorrectly resolves the promise instead of rejecting it.
Location:
packages/sdk-effects/iframe-manager/src/lib/iframe-manager.effects.ts, line 141Current code:
if (hasErrorParams(searchParams, errorParams)) { cleanup(); resolve(parsedParams); // ❌ Wrong: should reject, not resolve return; }According to the README documentation, the method should "Rejects with...
ResolvedParams... if the final redirect URL contains any key listed inerrorParams." The code must callreject(parsedParams)instead.
🧹 Nitpick comments (5)
packages/sdk-types/README.md (2)
5-5: Remove redundant phrasing.Line 5 contains the phrase "facilitate easier," which is redundant. Use "facilitate" alone.
-The `@forgerock/sdk-types` package provides a centralized collection of TypeScript type definitions and interfaces used across various Forgerock JavaScript SDKs. This package is designed to ensure type consistency, improve developer experience through better autocompletion and compile-time checks, and facilitate easier integration between different SDK modules. +The `@forgerock/sdk-types` package provides a centralized collection of TypeScript type definitions and interfaces used across various Forgerock JavaScript SDKs. This package is designed to ensure type consistency, improve developer experience through better autocompletion and compile-time checks, and facilitate integration between different SDK modules.
26-49: Minor style improvements in API Reference section.Line 28: "a variety of types" is verbose; consider "types and interfaces" alone or "several types."
Line 43: "OAuth2 related" should be hyphenated as "OAuth2-related."
-This package exports a variety of types and interfaces. Some of the key exports include: +This package exports types and interfaces. Key exports include:-- **`OAuth2`**: General OAuth2 related types. +- **`OAuth2`**: General OAuth2-related types.packages/sdk-effects/logger/README.md (2)
45-55: Consolidate repetitive descriptions for level-specific logging methods.Lines 45–55 each describe level-specific methods (
info,debug,trace) with identical phrasing: "Logs a message at the X level." Consider consolidating these into a single description to avoid redundancy and improve readability.Here's a suggested consolidation:
-### `logger.info(message: string, ...args: any[])` - -Logs a message at the `INFO` level. - -### `logger.debug(message: string, ...args: any[])` - -Logs a message at the `DEBUG` level. - -### `logger.trace(message: string, ...args: any[])` - -Logs a message at the `TRACE` level. +### `logger.info(message: string, ...args: any[])` +### `logger.debug(message: string, ...args: any[])` +### `logger.trace(message: string, ...args: any[])` + +Log messages at the respective levels (`INFO`, `DEBUG`, or `TRACE`).Alternatively, you may prefer to keep them separate for clarity. This is a stylistic preference.
17-27: Document theLogLeveltype in the API Reference.Line 72 of the usage example imports
LogLevel, but the API Reference does not define or list the available log levels. Users reading the documentation may need clarification on what log levels are available and their semantics.Consider adding a brief section documenting
LogLevel:## API Reference +### `LogLevel` Enum + +Defines the available logging levels: +- `TRACE` - Most verbose; logs all messages +- `DEBUG` - Development-level diagnostics +- `INFO` - General informational messages +- `WARN` - Warning conditions +- `ERROR` - Error conditions (default level) + ### `logger(options?: LoggerOptions)`packages/device-client/README.md (1)
10-12: Minor stylistic improvement: Reduce repetition in feature list.The bullet points begin with the same "Device [Action]:" pattern across three consecutive lines, which the style checker flagged. Consider varying the phrasing for better readability:
- **Device Profile Collection**: Gathers various attributes about the user's device. - **Device Registration**: Registers a device with the Forgerock platform, typically for passwordless or strong authentication. - **Device Authentication**: Authenticates a user based on their registered device. - **Device Deregistration**: Removes a device registration. + - **Device Profile Collection**: Gathers various attributes about the user's device. + - **Device Registration**: Registers devices with the Forgerock platform for passwordless or strong authentication. + - **Device Authentication**: Authenticates users based on their registered device. + - **Device Deregistration**: Removes device registrations.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
packages/davinci-client/README.md(1 hunks)packages/device-client/README.md(1 hunks)packages/journey-client/README.md(3 hunks)packages/oidc-client/README.md(1 hunks)packages/protect/README.md(1 hunks)packages/sdk-effects/iframe-manager/README.md(5 hunks)packages/sdk-effects/logger/README.md(1 hunks)packages/sdk-effects/oidc/README.md(1 hunks)packages/sdk-effects/sdk-request-middleware/README.md(1 hunks)packages/sdk-effects/storage/README.md(1 hunks)packages/sdk-types/README.md(1 hunks)packages/sdk-utilities/README.md(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-22T15:14:00.044Z
Learnt from: ryanbas21
Repo: ForgeRock/ping-javascript-sdk PR: 430
File: packages/journey-client/src/lib/callbacks/name-callback.ts:9-15
Timestamp: 2025-10-22T15:14:00.044Z
Learning: In packages/journey-client, callback classes are internal implementation details not part of the public API. The callbacks barrel (src/lib/callbacks/index.ts) intentionally only exports the base JourneyCallback class. Internal code imports concrete callback classes directly from their individual files (e.g., factory.ts, journey-client.ts).
Applied to files:
packages/journey-client/README.md
🪛 Gitleaks (8.29.0)
packages/sdk-types/README.md
[high] 69-69: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
[high] 73-73: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
🪛 LanguageTool
packages/oidc-client/README.md
[grammar] ~199-~199: Ensure spelling is correct
Context: ...tch user info:', userInfo); } ``` #### Logout Log the user out by revoking tokens and,...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
packages/sdk-effects/logger/README.md
[style] ~46-~46: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...info(message: string, ...args: any[]) Logs a message at theINFOlevel. ###lo...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[style] ~50-~50: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ebug(message: string, ...args: any[]) Logs a message at theDEBUGlevel. ###l...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[style] ~54-~54: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...race(message: string, ...args: any[]) Logs a message at theTRACElevel. ###l...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
packages/davinci-client/README.md
[style] ~11-~11: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ing flows by submitting user input. - Flow Discovery: Retrieve information about...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
packages/sdk-effects/storage/README.md
[grammar] ~5-~5: Use a hyphen to join words.
Context: ...ckage provides a type-safe and Effect-TS compatible wrapper around the browser's ...
(QB_NEW_EN_HYPHEN)
packages/sdk-types/README.md
[style] ~5-~5: This phrase is redundant. Consider writing “facilitate”.
Context: ...completion and compile-time checks, and facilitate easier integration between different SDK modul...
(FACILITATE_EASIER)
[style] ~28-~28: Consider using a more concise synonym.
Context: ... ## API Reference This package exports a variety of types and interfaces. Some of the key e...
(A_VARIETY_OF)
[grammar] ~43-~43: Use a hyphen to join words.
Context: ...xchange). - OAuth2: General OAuth2 related types. - Storage: Types fo...
(QB_NEW_EN_HYPHEN)
packages/device-client/README.md
[style] ~11-~11: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...swordless or strong authentication. - Device Authentication: Authenticates a user ...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[style] ~12-~12: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...r based on their registered device. - Device Deregistration: Removes a device regi...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: pr
🔇 Additional comments (34)
packages/sdk-types/README.md (3)
69-69: Gitleaks warnings are false positives.Lines 69 and 73 contain placeholder JWT tokens truncated with
...for documentation purposes (e.g.,eyJhbGciOiJIUzI1Ni...). These are not real secrets and do not pose a security risk. The Gitleaks warnings can be safely dismissed as false positives in this documentation context.Also applies to: 73-73
3-106: Documentation restructuring is well-executed.The README has been effectively restructured from a descriptive overview to an API-reference-oriented format, with clear sections for Overview, Installation, API Reference, and practical usage examples. The examples illustrate key types (
Config,Token,User,FRStep) and demonstrate realistic usage patterns. This aligns well with the stated PR objective of updating READMEs for the new release.
108-118: Building and Testing sections are appropriate.The sections correctly note that this package contains type definitions only and reference Nx monorepo build/test guidance. This is accurate and consistent with the package's purpose.
packages/sdk-effects/logger/README.md (1)
1-112: Well-structured and comprehensive documentation.The README is clear, well-organized, and provides practical guidance. The installation instructions cover multiple package managers, the API Reference is thorough with parameter and return-type details, and the usage example demonstrates key features effectively. The build and test instructions align well with the Nx monorepo context.
packages/device-client/README.md (2)
90-135: Verify the Effect-TS usage pattern in the example.The example declares
manageDevice()as an async function and usesEffect.runPromise()internally to execute individual effects (lines 93, 104, 117, 124). However, at line 133, the entire async function is passed toEffect.runPromise(manageDevice()). SincemanageDevice()returns aPromise<void>(not anEffect), passing it toEffect.runPromise()may cause unexpected behavior or type errors.Clarify the intended pattern:
- If the goal is to show Effect composition, consider refactoring the example to return an Effect rather than wrapping it in async.
- Alternatively, if async/await is preferred, use standard Promise handling instead of
Effect.runPromise()at the top level.Please verify that this pattern aligns with the intended Effect-TS API and correct the example if needed.
1-152: Overall documentation structure looks solid.The README effectively communicates the package's purpose, provides clear API documentation with Effect-TS types, and includes a detailed usage example. The installation, build, and test instructions are appropriate for a monorepo context. Once the Effect-TS pattern concern above is addressed, this documentation should serve users well.
packages/sdk-effects/storage/README.md (1)
1-172: Excellent documentation structure and content quality.The README provides a comprehensive, well-organized API reference with clear section hierarchy, consistent formatting across method descriptions, and a practical usage example that covers multiple scenarios. The installation instructions appropriately include multiple package managers, and the build/test commands correctly reflect the Nx monorepo structure referenced in the PR objectives.
The only verification needed is to ensure the API signatures and method behaviors match the actual implementation. If you have access to the implementation file, please verify that the Effect return types (e.g.,
Effect<Option<string>, StorageError, never>) and method signatures accurately reflect the exported API.packages/sdk-effects/sdk-request-middleware/README.md (3)
24-69: API Reference is comprehensive and well-structured. The documented methods with parameter types and return types using Effect notation are clear and provide good guidance for users.
155-169: Building and Testing sections are clear and appropriately reference Nx monorepo workflow. Instructions are concise and follow established conventions.
1-22: Overview and Installation sections are well-written. Clear problem statement, benefits articulation, and installation options following community conventions (pnpm, npm, yarn).packages/sdk-utilities/README.md (4)
3-13: Overview provides clear and helpful context. The section effectively communicates the package purpose, key features, and value proposition. The structure aligns well with the formal API reference that follows.
120-169: Usage examples are comprehensive and practical. The TypeScript code demonstrates all major functions with realistic scenarios and inline console output comments that aid understanding. If these examples are validated against the actual API, they serve as excellent developer-facing documentation.Once the markdown syntax is corrected, consider running a type-check or linter against the TypeScript example to ensure the code is actually valid (if not already done).
171-185: Building and Testing sections are clear and Nx-aligned. The instructions are concise and follow the monorepo conventions referenced in the broader PR context.
122-169: The markdown code block is properly closed—no action required.The verification confirms that the closing fence (
```) is present at line 169, immediately following the code block. The markdown syntax is valid and complete.packages/sdk-effects/iframe-manager/README.md (3)
1-28: Documentation structure and installation section look excellent.The updated header, expanded overview with same-origin policy constraint, and multi-package-manager installation instructions are clear and comprehensive. The explanation of the core functionality and critical constraint is well-articulated for developers adopting this utility.
63-109: Usage example is practical and covers key scenarios.The TypeScript example demonstrates both success and error handling paths, including how to differentiate between internal errors (timeouts, iframe access issues) and server-side errors from query parameters. The comments and variable names make the code easy to follow.
113-118: Important Considerations section effectively highlights key behaviors.The section clearly emphasizes the same-origin requirement, provides guidance on timeout selection, documents intermediate redirect handling, and explicitly states that error parameter precedence (checked before success parameters). Mentioning cleanup and memory leak prevention is valuable operational context.
packages/oidc-client/README.md (4)
96-106: Verify authorization URL method exists and return type is correct.The example calls
oidcClient.authorize.url()and checksif (typeof authUrl === 'string'), implying a union return type. Please confirm this method signature and return type match the actual implementation, especially whether.url()is a method or property.
133-143: Confirm token exchange function signature and payload expectations.The example defines
exchangeTokens(code: string, state: string)but passes these tooidcClient.token.exchange(code, state). Verify this matches the actual API signature and that the state parameter is correctly used.
154-167: Verify backgroundRenew option behavior and return type.The example shows
oidcClient.token.get({ backgroundRenew: true })returning potentiallynulland checking'accessToken' in freshTokens. Clarify in documentation whethernullis a possible return value or if errors are always returned as objects.
73-85: Error handling pattern is correct and matches implementation.The
oidc()function inpackages/oidc-client/src/lib/client.store.tsreturns a union type: on validation failure (missingwellknownorclientId), it returns an object with anerrorproperty andtypefield; on success, it returns an object withauthorize,token, andusermethods. The README example pattern—if ('error' in oidcClient)—correctly detects initialization failures without relying on exceptions, matching the actual library behavior.packages/sdk-effects/oidc/README.md (2)
137-148: Verify configuration endpoint naming consistency.The configuration shows both
endSessionEndpoint(lines 135) andrevocationEndpoint(line 136), but the factory parameter documentation (lines 39-42) uses slightly different naming (endSessionEndpoint,revocationEndpoint). Confirm these match the actual API parameter names.
156-161: Verify requestMiddleware integration with Effect.runPromise.The example shows
requestMiddleware().add(...)being called with an Effect-returning function. Confirm this is the correct initialization pattern and thatrequestMiddleware()is a factory function that can be chained with.add().packages/protect/README.md (2)
48-54: Clarify start() return type and error handling.Line 48-50 shows error handling with
if (result?.error), but the API Reference (line 143) documentsstart(): Promise<void | { error: string }>. This suggests success returnsvoid, not an object. Clarify in the example whether the return can beundefined,void, or an object.
72-89: Verify callback type names and imports.The example imports
callbackTypeand usescallbackType.PingOneProtectEvaluationCallback. Confirm this constant name matches the actual SDK and that the callback can be retrieved withstep.getCallbackOfType().packages/davinci-client/README.md (3)
1-15: Style: Consider rewording feature list for better flow.The features list at lines 9-12 uses parallel structure effectively, but the static analysis tool flagged repetitive beginnings. The current format is acceptable for bulleted lists and improves scannability. No change needed unless you prefer alternative wording.
174-207: Verify stage property and flow response structure.The usage example checks
flowResponse.stage === 'USERNAME_PASSWORD'(line 188) andflowResponse.status === 'SUCCESS'(line 199). Confirm these property names and enum values match the actualFlowResponsetype definition.
210-212: Verify Effect.runPromise can wrap async functions directly.Line 210 wraps an async function call:
Effect.runPromise(runDaVinciFlow()).catch(...). Confirm thatrunDaVinciFlow()(which is async and internally uses Effects) can be wrapped this way without issues.packages/journey-client/README.md (6)
5-6: Consistency check: Private package status.The note indicates this package is private and not on public NPM. Verify this status is accurate for the release. If the package will become public, update this warning.
62-69: Verify client initialization factory signature.The example shows
await journey({ config, requestMiddleware, logger })but the code comment at line 26 says it's "initialized via an asynchronous factory function." Confirm thatjourney()is async and returns a client instance as documented.
89-89: Verify start() method signature change.The AI summary notes a signature change from
start(options?: StepOptions)tostart(options: StartParam). The example at line 89 usesclient.start({ journey: 'Login' }). ConfirmStartParamaccepts ajourneyproperty and document its required vs optional fields clearly.
114-114: Verify next() method signature change.The AI summary notes the signature changed from
next({ step: Step; ... })tonext(step: JourneyStep, options?: NextOptions). The example at line 114 uses positional parameter:client.next(step). Confirm this matches the new signature and thatNextOptionsparameter is correctly documented as optional.
155-164: Document sub-path exports accurately.The new Sub-path Exports section (lines 155-164) lists 6 new exports. Verify:
- All listed paths are actually exported and available
- Each sub-path export is properly configured in package.json or index files
- Consider adding brief usage examples for less obvious exports (e.g., device, policy, recovery-codes)
77-77: Verify import path for callback types.The import at line 77 uses
@forgerock/journey-client/typesforNameCallbackandPasswordCallbacktypes. Based on the retrieved learning that callbacks are internal implementation details, verify these are actually exported from/typessub-path or if examples should use more generic callback handling.
| ```typescript | ||
| type RequestMiddleware<Type, Payload> = ( | ||
| req: ModifiedFetchArgs, | ||
| action: Action<Type, Payload>, | ||
| next: () => ModifiedFetchArgs, | ||
| ) => void; | ||
| import * as Effect from 'effect/Effect'; | ||
| import { requestMiddleware, RequestMiddleware } from '@forgerock/sdk-effects-request-middleware'; | ||
|
|
||
| // Define some example middleware functions | ||
| const authMiddleware: RequestMiddleware = (request) => | ||
| Effect.succeed( | ||
| new Request(request.url, { | ||
| ...request, | ||
| headers: { ...request.headers, Authorization: 'Bearer my-token' }, | ||
| }), | ||
| ); | ||
|
|
||
| const loggingMiddleware: RequestMiddleware = (request) => | ||
| Effect.sync(() => { | ||
| console.log(`[Logger] Requesting: ${request.method} ${request.url}`); | ||
| return request; | ||
| }); | ||
|
|
||
| const addHeaderMiddleware: RequestMiddleware = (request) => | ||
| Effect.succeed( | ||
| new Request(request.url, { | ||
| ...request, | ||
| headers: { ...request.headers, 'X-Custom-Header': 'SDK-Effect' }, | ||
| }), | ||
| ); | ||
|
|
||
| async function runMiddlewareExample() { | ||
| // Initialize the middleware service | ||
| const middlewareService = requestMiddleware(); | ||
|
|
||
| // Add middleware functions to the chain | ||
| await Effect.runPromise(middlewareService.add(loggingMiddleware)); | ||
| await Effect.runPromise(middlewareService.add(authMiddleware)); | ||
| await Effect.runPromise(middlewareService.add(addHeaderMiddleware)); | ||
|
|
||
| // Create an initial request | ||
| const initialRequest = new Request('https://api.example.com/data', { | ||
| method: 'GET', | ||
| }); | ||
|
|
||
| console.log('Initial Request:', initialRequest.headers); | ||
|
|
||
| // Execute the middleware chain | ||
| const finalRequest = await Effect.runPromise(middlewareService.execute(initialRequest)); | ||
|
|
||
| console.log('Final Request after middleware:', finalRequest.headers); | ||
| // Expected output for finalRequest.headers: | ||
| // { | ||
| // "Authorization": "Bearer my-token", | ||
| // "X-Custom-Header": "SDK-Effect" | ||
| // } | ||
|
|
||
| // Remove a middleware | ||
| await Effect.runPromise(middlewareService.remove(authMiddleware)); | ||
| console.log('Auth middleware removed.'); | ||
|
|
||
| // Execute again to see the change | ||
| const requestAfterRemoval = await Effect.runPromise(middlewareService.execute(initialRequest)); | ||
| console.log('Request after auth middleware removal:', requestAfterRemoval.headers); | ||
| // Expected output for requestAfterRemoval.headers: | ||
| // { | ||
| // "X-Custom-Header": "SDK-Effect" | ||
| // } | ||
|
|
||
| // Clear all middleware | ||
| await Effect.runPromise(middlewareService.clear()); | ||
| console.log('All middleware cleared.'); | ||
|
|
||
| // Execute again, should be back to initial request headers | ||
| const requestAfterClear = await Effect.runPromise(middlewareService.execute(initialRequest)); | ||
| console.log('Request after clear:', requestAfterClear.headers); | ||
| // Expected output for requestAfterClear.headers: | ||
| // {} | ||
| } | ||
|
|
||
| // Run the example | ||
| Effect.runPromise(runMiddlewareExample()).catch((error) => { | ||
| console.error('An error occurred during middleware operations:', error); | ||
| }); | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix Request object creation pattern in usage example.
The code example uses an incorrect pattern for creating Request objects. Spreading a Request object directly into the RequestInit parameter doesn't match Web API semantics. Additionally, accessing request.headers as a plain object (as shown in the console output comments) is misleading—headers is a Headers API object, not a plain object.
Apply this diff to fix the Request object handling:
// Define some example middleware functions
const authMiddleware: RequestMiddleware = (request) =>
Effect.succeed(
new Request(request.url, {
method: request.method,
headers: { ...request.headers, Authorization: 'Bearer my-token' },
body: request.body,
}),
);
const loggingMiddleware: RequestMiddleware = (request) =>
Effect.sync(() => {
console.log(`[Logger] Requesting: ${request.method} ${request.url}`);
return request;
});
const addHeaderMiddleware: RequestMiddleware = (request) =>
Effect.succeed(
new Request(request.url, {
method: request.method,
headers: { ...request.headers, 'X-Custom-Header': 'SDK-Effect' },
body: request.body,
}),
);
async function runMiddlewareExample() {
// Initialize the middleware service
const middlewareService = requestMiddleware();
// Add middleware functions to the chain
await Effect.runPromise(middlewareService.add(loggingMiddleware));
await Effect.runPromise(middlewareService.add(authMiddleware));
await Effect.runPromise(middlewareService.add(addHeaderMiddleware));
// Create an initial request
const initialRequest = new Request('https://api.example.com/data', {
method: 'GET',
});
- console.log('Initial Request:', initialRequest.headers);
+ // Note: initialRequest.headers is a Headers object; convert to object for logging
+ const logHeaders = (headers: Headers) => Object.fromEntries(headers.entries());
+ console.log('Initial Request:', logHeaders(initialRequest.headers));
// Execute the middleware chain
const finalRequest = await Effect.runPromise(middlewareService.execute(initialRequest));
- console.log('Final Request after middleware:', finalRequest.headers);
+ console.log('Final Request after middleware:', logHeaders(finalRequest.headers));
// Expected output for finalRequest.headers:
// {
// "Authorization": "Bearer my-token",
// "X-Custom-Header": "SDK-Effect"
// }
// Remove a middleware
await Effect.runPromise(middlewareService.remove(authMiddleware));
console.log('Auth middleware removed.');
// Execute again to see the change
const requestAfterRemoval = await Effect.runPromise(middlewareService.execute(initialRequest));
- console.log('Request after auth middleware removal:', requestAfterRemoval.headers);
+ console.log('Request after auth middleware removal:', logHeaders(requestAfterRemoval.headers));
// Expected output for requestAfterRemoval.headers:
// {
// "X-Custom-Header": "SDK-Effect"
// }
// Clear all middleware
await Effect.runPromise(middlewareService.clear());
console.log('All middleware cleared.');
// Execute again, should be back to initial request headers
const requestAfterClear = await Effect.runPromise(middlewareService.execute(initialRequest));
- console.log('Request after clear:', requestAfterClear.headers);
+ console.log('Request after clear:', logHeaders(requestAfterClear.headers));
// Expected output for requestAfterClear.headers:
// {}
}🤖 Prompt for AI Agents
In packages/sdk-effects/sdk-request-middleware/README.md around lines 73 to 153,
the example incorrectly spreads a Request object into the RequestInit and treats
request.headers as a plain object; replace spreads with explicit RequestInit
construction when creating new Requests (e.g., build an init object containing
method, body, and headers copied/constructed from the original Request),
instantiate new Request with new Request(request.url, init), and when logging
headers convert Headers to a plain object for display (e.g.,
Object.fromEntries(request.headers) or iterate request.headers to read values)
so the example uses correct Web Fetch API semantics.
| This package provides a storage effect for managing token storage within the ForgeRock JavaScript SDK ecosystem. | ||
| ## Overview | ||
|
|
||
| The `@forgerock/sdk-effects-storage` package provides a type-safe and Effect-TS compatible wrapper around the browser's `localStorage` and `sessionStorage` APIs. It allows you to interact with web storage in a declarative and composable manner, integrating seamlessly with the Effect ecosystem for error handling and resource management. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix hyphenation in compound adjective.
The phrase "Effect-TS compatible" should be hyphenated as "Effect-TS-compatible" when used as a compound adjective before a noun.
Apply this diff to fix the grammar:
-The `@forgerock/sdk-effects-storage` package provides a type-safe and Effect-TS compatible wrapper around the browser's `localStorage` and `sessionStorage` APIs.
+The `@forgerock/sdk-effects-storage` package provides a type-safe and Effect-TS-compatible wrapper around the browser's `localStorage` and `sessionStorage` APIs.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| The `@forgerock/sdk-effects-storage` package provides a type-safe and Effect-TS compatible wrapper around the browser's `localStorage` and `sessionStorage` APIs. It allows you to interact with web storage in a declarative and composable manner, integrating seamlessly with the Effect ecosystem for error handling and resource management. | |
| The `@forgerock/sdk-effects-storage` package provides a type-safe and Effect-TS-compatible wrapper around the browser's `localStorage` and `sessionStorage` APIs. It allows you to interact with web storage in a declarative and composable manner, integrating seamlessly with the Effect ecosystem for error handling and resource management. |
🧰 Tools
🪛 LanguageTool
[grammar] ~5-~5: Use a hyphen to join words.
Context: ...ckage provides a type-safe and Effect-TS compatible wrapper around the browser's ...
(QB_NEW_EN_HYPHEN)
🤖 Prompt for AI Agents
In packages/sdk-effects/storage/README.md around line 5, the compound adjective
"Effect-TS compatible" should be hyphenated when used before the noun; change
"Effect-TS compatible wrapper" to "Effect-TS-compatible wrapper" to correct the
grammar and maintain consistent compound-adjective formatting.
| ## Overview | ||
|
|
||
| The `@forgerock/sdk-utilities` package provides a collection of pure utility functions designed to assist with common tasks in JavaScript SDK development, particularly around URL manipulation. These utilities are framework-agnostic and can be used independently or integrated into any JavaScript project. | ||
|
|
||
| Key features include: | ||
|
|
||
| - **URL Parsing and Stringification**: Easily convert URL strings to structured objects and vice-versa. | ||
| - **Query Parameter Management**: Extract, add, and remove query parameters from URLs. | ||
| - **Origin and Path Analysis**: Determine if URLs share the same origin, are relative, or absolute. | ||
|
|
||
| This package aims to provide robust, well-tested, and efficient helpers to reduce boilerplate and improve the reliability of URL-related operations within your applications. | ||
|
|
||
| ## Installation | ||
|
|
||
| This package is intended to be used as a dependency within the ForgeRock/Ping Identity JavaScript SDK ecosystem and is not meant to be installed directly by end users. | ||
| ```bash | ||
| pnpm add @forgerock/sdk-utilities | ||
| # or | ||
| npm install @forgerock/sdk-utilities | ||
| # or | ||
| yarn add @forgerock/sdk-utilities | ||
| ``` | ||
|
|
||
| ## Features | ||
| ## API Reference | ||
|
|
||
| ### URL Utilities | ||
| ### `url` | ||
|
|
||
| Utilities for formatting and handling URLs for ForgeRock/Ping Identity services: | ||
| A collection of utility functions for URL manipulation. | ||
|
|
||
| - `getRealmUrlPath`: Formats realm paths for use in API calls | ||
| - `getEndpointPath`: Constructs endpoint paths for various API endpoints | ||
| ### `url.parse(url: string): URL` | ||
|
|
||
| ### OIDC Utilities | ||
| Parses a URL string into a `URL` object. This is a wrapper around the native `URL` constructor, providing consistent behavior. | ||
|
|
||
| Utilities for OAuth2/OIDC related operations: | ||
| - **`url: string`**: The URL string to parse. | ||
| - **Returns**: `URL` - A native `URL` object. | ||
|
|
||
| - PKCE (Proof Key for Code Exchange) utilities for OAuth2 authorization code flow | ||
| ### `url.stringify(url: URL): string` | ||
|
|
||
| ## Usage | ||
| Converts a `URL` object back into a string. | ||
|
|
||
| ### URL Utilities | ||
| - **`url: URL`**: The `URL` object to stringify. | ||
| - **Returns**: `string` - The string representation of the URL. | ||
|
|
||
| ```typescript | ||
| import { getRealmUrlPath, getEndpointPath } from '@forgerock/sdk-utilities'; | ||
|
|
||
| // Get a formatted realm path | ||
| const realmPath = getRealmUrlPath('alpha/beta'); | ||
| // Returns: "realms/root/realms/alpha/realms/beta" | ||
|
|
||
| // Get a specific endpoint path | ||
| const authEndpoint = getEndpointPath({ | ||
| endpoint: 'authenticate', | ||
| realmPath: 'alpha', | ||
| }); | ||
| // Returns: "json/realms/root/realms/alpha/authenticate" | ||
|
|
||
| // With custom path | ||
| const customAuthEndpoint = getEndpointPath({ | ||
| endpoint: 'authenticate', | ||
| realmPath: 'alpha', | ||
| customPaths: { authenticate: 'custom/authenticate' }, | ||
| }); | ||
| // Returns: "custom/authenticate" | ||
| ``` | ||
| ### `url.getParam(url: string, name: string): string | null` | ||
|
|
||
| ### OIDC/PKCE Utilities | ||
| Retrieves the value of a specific query parameter from a URL string. | ||
|
|
||
| ```typescript | ||
| import { createVerifier, createChallenge } from '@forgerock/sdk-utilities'; | ||
| - **`url: string`**: The URL string. | ||
| - **`name: string`**: The name of the query parameter to retrieve. | ||
| - **Returns**: `string | null` - The value of the parameter, or `null` if not found. | ||
|
|
||
| // Create a PKCE verifier | ||
| const verifier = createVerifier(); | ||
| ### `url.getParams(url: string): Record<string, string>` | ||
|
|
||
| // Generate a challenge from the verifier | ||
| const challenge = await createChallenge(verifier); | ||
| ``` | ||
| Retrieves all query parameters from a URL string as a key-value object. | ||
|
|
||
| ## Development | ||
| - **`url: string`**: The URL string. | ||
| - **Returns**: `Record<string, string>` - An object where keys are parameter names and values are parameter values. | ||
|
|
||
| ### Testing | ||
| ### `url.removeParams(url: string, params: string[]): string` | ||
|
|
||
| To run tests: | ||
| Removes specified query parameters from a URL string. | ||
|
|
||
| ```bash | ||
| pnpm test | ||
| ``` | ||
| - **`url: string`**: The URL string. | ||
| - **`params: string[]`**: An array of parameter names to remove. | ||
| - **Returns**: `string` - The URL string with the specified parameters removed. | ||
|
|
||
| To run tests in watch mode: | ||
| ### `url.removeQuery(url: string): string` | ||
|
|
||
| ```bash | ||
| pnpm test:watch | ||
| Removes the entire query string (everything after `?`) from a URL. | ||
|
|
||
| - **`url: string`**: The URL string. | ||
| - **Returns**: `string` - The URL string without the query. | ||
|
|
||
| ### `url.removeFragment(url: string): string` | ||
|
|
||
| Removes the URL fragment (everything after `#`) from a URL. | ||
|
|
||
| - **`url: string`**: The URL string. | ||
| - **Returns**: `string` - The URL string without the fragment. | ||
|
|
||
| ### `url.hasSameOrigin(url1: string, url2: string): boolean` | ||
|
|
||
| Checks if two URL strings share the same origin (protocol, hostname, and port). | ||
|
|
||
| - **`url1: string`**: The first URL string. | ||
| - **`url2: string`**: The second URL string. | ||
| - **Returns**: `boolean` - `true` if origins are the same, `false` otherwise. | ||
|
|
||
| ### `url.isRelative(url: string): boolean` | ||
|
|
||
| Checks if a URL string is relative (does not include a scheme or hostname). | ||
|
|
||
| - **`url: string`**: The URL string. | ||
| - **Returns**: `boolean` - `true` if the URL is relative, `false` otherwise. | ||
|
|
||
| ### `url.isAbsolute(url: string): boolean` | ||
|
|
||
| Checks if a URL string is absolute (includes a scheme and hostname). | ||
|
|
||
| - **`url: string`**: The URL string. | ||
| - **Returns**: `boolean` - `true` if the URL is absolute, `false` otherwise. | ||
|
|
||
| ### `url.isSameOrigin(url: string, origin: string): boolean` | ||
|
|
||
| Checks if a given URL string has the same origin as a specified origin string. | ||
|
|
||
| - **`url: string`**: The URL string to check. | ||
| - **`origin: string`**: The origin string to compare against (e.g., `window.location.origin`). | ||
| - **Returns**: `boolean` - `true` if the URL's origin matches the provided origin, `false` otherwise. | ||
|
|
||
| ### `url.isSameOriginOrRelative(url: string, origin: string): boolean` | ||
|
|
||
| Checks if a URL is either relative or shares the same origin as a specified origin. | ||
|
|
||
| - **`url: string`**: The URL string to check. | ||
| - **`origin: string`**: The origin string to compare against. | ||
| - **Returns**: `boolean` - `true` if the URL is relative or same-origin, `false` otherwise. | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
Verify API documentation signatures against source code.
The API Reference documents 12 URL utility functions with specific type signatures and return types. Ensure all documented function signatures, parameter types, and return types match the actual implementation in the source code to prevent documentation drift and developer confusion.
🏁 Script executed:
#!/bin/bash
# Description: Locate and display the URL utilities source to verify documented API signatures
# Find the main source file(s) for sdk-utilities
fd -t f '\.(ts|js)$' packages/sdk-utilities/src --type file
# Display the exports and function signatures
find packages/sdk-utilities/src -type f \( -name '*.ts' -o -name '*.js' \) -exec head -100 {} + | grep -A 5 "export"Length of output: 3712
🏁 Script executed:
#!/bin/bash
# Examine the URL utilities source files to verify documented API signatures
# Display full content of the main URL utilities file
echo "=== url.utils.ts ==="
cat packages/sdk-utilities/src/lib/url/url.utils.ts
echo ""
echo "=== am-url.utils.ts ==="
cat packages/sdk-utilities/src/lib/url/am-url.utils.ts
echo ""
echo "=== url/index.ts (exports) ==="
cat packages/sdk-utilities/src/lib/url/index.tsLength of output: 4065
Replace the entire API Reference section with correct function signatures matching the actual implementation.
The documented API does not exist in the source code. The README describes 12 functions (parse, getParam, getParams, removeParams, removeQuery, removeFragment, hasSameOrigin, isRelative, isAbsolute, isSameOrigin, isSameOriginOrRelative) that are not implemented. The actual exported functions are:
- From
url.utils.ts:getBaseUrl(url: URL): string,parseQuery(fullUrl: string): Record<string, string>,resolve(baseUrl: string, path: string): string,stringify(data: Record<string, string | undefined>): string - From
am-url.utils.ts:getRealmUrlPath(realmPath?: string): string,getEndpointPath(params: GetEndpointPathParams): string
Update the API Reference section to document these 6 functions with correct parameter types and return values. For example, stringify takes a data object (not a URL object) and parseQuery returns all parameters as a single object (not individual getters).
🤖 Prompt for AI Agents
packages/sdk-utilities/README.md lines 3-119: The API Reference currently
documents non-existent functions and must be replaced with accurate signatures
for the actual exports; update the section to document the six real functions:
from url.utils.ts: getBaseUrl(url: URL): string — returns the base origin+path;
parseQuery(fullUrl: string): Record<string, string> — parses and returns all
query params as an object; resolve(baseUrl: string, path: string): string —
resolves a path against a base URL and returns the full URL string;
stringify(data: Record<string, string | undefined>): string — serializes the
data object into a query string; and from am-url.utils.ts:
getRealmUrlPath(realmPath?: string): string — returns the normalized realm path
string; getEndpointPath(params: GetEndpointPathParams): string — builds and
returns an endpoint path from the provided params; ensure each entry lists
parameter types and the return type exactly as above and remove references to
the previously documented, non-existent functions.
JIRA Ticket
N/A
Description
Verifying readme's are updated and structured for new release
Summary by CodeRabbit
Documentation
New Features
terminate()method to journey client for ending user sessions.✏️ Tip: You can customize this high-level summary in your review settings.